RynthSuite as of 2026-11-23 (internal 327a8263): release 2026.11.23.1
This commit is contained in:
parent
660e6b5b1c
commit
759009b569
196 changed files with 21066 additions and 1021 deletions
|
|
@ -11,7 +11,9 @@
|
|||
// - each building's doors: its 0xFFFF portal polygons wide and tall enough to walk through with
|
||||
// their foot at the floor (not a window), with a point a step inside and one a step outside;
|
||||
// - walks inside a building between two spots (the cell path, laid through doorways and across
|
||||
// rooms as the patrol lays them), kept out of the circles of portal objects standing inside.
|
||||
// rooms as the patrol lays them), kept out of the circles of portal objects standing inside;
|
||||
// - what its cells place (tables, chairs, beds, cabinets: GeometryLoader's statics), as the dungeon
|
||||
// map's placed objects, less the stairs (see "Placed objects" below).
|
||||
// Cached per landblock (the last MaxBlocks). Tick thread.
|
||||
|
||||
using System;
|
||||
|
|
@ -35,6 +37,13 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
|
|||
internal const double MinDoorWidth = 0.8, MinDoorHeight = 1.5;
|
||||
/// <summary>A door's foot at most this far above or below the floor just inside it (else a window).</summary>
|
||||
internal const double DoorSillMax = 0.75;
|
||||
/// <summary>An opening under this tall can be a window with a deep sill (see TryDoor); no door this tall or taller is
|
||||
/// judged one.</summary>
|
||||
internal const double WindowTallMax = 2.4;
|
||||
/// <summary>The highest step a body walks up (AC's step-up height).</summary>
|
||||
internal const double StepUpMeters = 0.6;
|
||||
/// <summary>The floor a body stands on inside, for the window test: this far in and more (past a sill's depth).</summary>
|
||||
internal const double WindowRoomFrom = 0.75;
|
||||
/// <summary>A door's step out over a floor of the landblock at most this far below is no door from the ground.</summary>
|
||||
internal const double StepOutBelow = 12.0;
|
||||
/// <summary>Doors of one building whose centres are this close are one (a double door's two halves).</summary>
|
||||
|
|
@ -47,6 +56,8 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
|
|||
/// <summary>A bend round a portal keeps this much more than its circle.</summary>
|
||||
internal const double PortalBendMargin = 0.4;
|
||||
internal const int MaxBlocks = 25;
|
||||
/// <summary>A cell's floor centre in furniture moves at most this far to be out of it.</summary>
|
||||
internal const double CentreOutOfPlaced = 3.0;
|
||||
|
||||
/// <summary>A portal object inside a building: its circle (world units).</summary>
|
||||
internal readonly record struct PortalSpot(uint Id, double X, double Y, double Z, double R = PortalKeepOutMeters);
|
||||
|
|
@ -74,11 +85,46 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
|
|||
public int ExitRecords;
|
||||
/// <summary>Openings to the outside shared by two cells, joined (JoinSharedOpenings).</summary>
|
||||
public int SharedOpenings;
|
||||
/// <summary>What the cells place: pieces given, how many went on the map (furniture), how many were left out as stairs.</summary>
|
||||
public int PlacedGiven, Furniture, Stairs;
|
||||
|
||||
private Dictionary<uint, DungeonNavNode>? _pointGraph;
|
||||
/// <summary><see cref="Graph"/> with each cell that has a floor at its floor's centre (<see cref="AtFloorCentres"/>), for laying a walk's points.</summary>
|
||||
public Dictionary<uint, DungeonNavNode> PointGraph => _pointGraph ??= AtFloorCentres(Graph, Geo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A copy of <paramref name="graph"/> with each cell that has a floor moved to its floor's centre. Every
|
||||
/// cell of a building sits at the building's own origin, so where a step has no doorway (the top of a
|
||||
/// stair is a floor opening, not a doorway) the walk's points fell back to the origin, on the ground
|
||||
/// floor: DreamWeave Thread E74E#14 (2026-11-17), every walk up its stairs went from the stair's foot
|
||||
/// back to the middle of the ground floor, then straight at the monster above, and ended under it.
|
||||
/// </summary>
|
||||
internal static Dictionary<uint, DungeonNavNode> AtFloorCentres(Dictionary<uint, DungeonNavNode> graph, DungeonGeometry? geo)
|
||||
{
|
||||
var g = new Dictionary<uint, DungeonNavNode>(graph.Count);
|
||||
foreach (var (id, n) in graph)
|
||||
{
|
||||
var m = new DungeonNavNode { CellId = n.CellId, NS = n.NS, EW = n.EW, Z = n.Z, Neighbors = n.Neighbors };
|
||||
if (geo != null && geo.TryCellFloorCentre(id, out double x, out double y, out double z))
|
||||
{
|
||||
// A centre in furniture (E74E#0's 0103: on a 0.45 m dais): the nearest spot of the cell's floor out of it.
|
||||
if (geo.PlacedCount > 0 && DungeonPathfinder.InsidePlacedAt(geo, x, y, z))
|
||||
DungeonPathfinder.NearestOutOfPlaced(geo, ref x, ref y, z, CentreOutOfPlaced, new[] { id });
|
||||
m.NS = DungeonGeometry.WorldToNav(y);
|
||||
m.EW = DungeonGeometry.WorldToNav(x);
|
||||
m.Z = (float)z;
|
||||
}
|
||||
g[id] = m;
|
||||
}
|
||||
return g;
|
||||
}
|
||||
|
||||
private readonly DatDatabase? _cellDat;
|
||||
private readonly Func<DungeonLOS?>? _los;
|
||||
private readonly Func<uint, bool>? _isDungeon;
|
||||
private readonly Func<uint, IReadOnlyList<(uint SetupId, uint CellId, BoundingVolume Mesh)>?>? _statics;
|
||||
private readonly Func<double, double, double>? _terrain;
|
||||
private readonly Dictionary<uint, Block?> _blocks = new();
|
||||
private readonly Queue<uint> _order = new();
|
||||
|
||||
|
|
@ -107,12 +153,18 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
|
|||
internal int WalksWorkedOut { get; private set; }
|
||||
private static long Key(double v) => (long)Math.Round(v / WalkKeySpacing);
|
||||
|
||||
/// <summary>On the real dats: <paramref name="isDungeon"/> says which landblocks are dungeons (their cells are no building's).</summary>
|
||||
public BuildingMap(DatDatabase? cellDat, Func<DungeonLOS?>? los, Func<uint, bool>? isDungeon = null)
|
||||
/// <summary>On the real dats: <paramref name="isDungeon"/> says which landblocks are dungeons (their cells are no building's);
|
||||
/// <paramref name="statics"/> gives what a landblock's cells place (GeometryLoader.GetDungeonStaticMeshes; null: no furniture);
|
||||
/// <paramref name="terrain"/> the ground's height at a world spot (GeometryLoader.GetTerrainZWorld; NaN unknown; null: no window test).</summary>
|
||||
public BuildingMap(DatDatabase? cellDat, Func<DungeonLOS?>? los, Func<uint, bool>? isDungeon = null,
|
||||
Func<uint, IReadOnlyList<(uint SetupId, uint CellId, BoundingVolume Mesh)>?>? statics = null,
|
||||
Func<double, double, double>? terrain = null)
|
||||
{
|
||||
_cellDat = cellDat;
|
||||
_los = los;
|
||||
_isDungeon = isDungeon;
|
||||
_statics = statics;
|
||||
_terrain = terrain;
|
||||
}
|
||||
|
||||
internal DatDatabase? CellDat => _cellDat;
|
||||
|
|
@ -133,7 +185,7 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
|
|||
if (_isDungeon != null && _isDungeon(landblock)) b = null;
|
||||
else
|
||||
{
|
||||
try { b = Load(landblock, _cellDat, _los?.Invoke()); }
|
||||
try { b = Load(landblock, _cellDat, _los?.Invoke(), _statics, _terrain); }
|
||||
catch { b = null; }
|
||||
}
|
||||
while (_order.Count >= MaxBlocks) _blocks.Remove(_order.Dequeue());
|
||||
|
|
@ -190,6 +242,124 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
|
|||
return p;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The rooms walked through from <paramref name="fromCell"/> to <paramref name="toCell"/>, the shortest
|
||||
/// by the walk itself: from where it stands to each doorway in turn, then to the goal (Dijkstra, a cell
|
||||
/// entered at its doorway). A building's cells all sit at the building's own origin, so the dungeon A*
|
||||
/// (cell centre to cell centre) saw every step as 0 m and took whichever path came first: DreamWeave
|
||||
/// Thread BA17#4 (2026-11-17), from 012C to the door in 0122 it went five rooms round (west, north, east
|
||||
/// through the raised 012D) instead of two, and its last leg, 012D's doorway to the door, ran into the
|
||||
/// wall; the character ran at it for two minutes ("He's also still running into walls").
|
||||
/// </summary>
|
||||
internal static List<uint> WalkCells(Block blk, uint fromCell, Vec from, uint toCell, Vec to)
|
||||
{
|
||||
var g = blk.Graph;
|
||||
if (!g.ContainsKey(fromCell) || !g.ContainsKey(toCell)) return new List<uint>();
|
||||
if (fromCell == toCell) return new List<uint> { fromCell };
|
||||
var at = new Dictionary<uint, Vec> { [fromCell] = from }; // where each cell is entered
|
||||
var cost = new Dictionary<uint, double> { [fromCell] = 0 };
|
||||
var came = new Dictionary<uint, uint>();
|
||||
var open = new PriorityQueue<uint, double>();
|
||||
var done = new HashSet<uint>();
|
||||
open.Enqueue(fromCell, 0);
|
||||
double best = double.MaxValue;
|
||||
while (open.Count > 0)
|
||||
{
|
||||
uint c = open.Dequeue();
|
||||
if (!done.Add(c)) continue;
|
||||
if (cost[c] >= best) break;
|
||||
var p = at[c];
|
||||
if (c == toCell) { best = Math.Min(best, cost[c] + p.DistanceTo(to)); continue; }
|
||||
var n = g[c];
|
||||
foreach (uint nb in n.Neighbors)
|
||||
{
|
||||
if (done.Contains(nb) || !g.TryGetValue(nb, out var o) || DungeonPathfinder.IsDropEdge(n, o)) continue;
|
||||
// No doorway known (a floor or ceiling opening: a stair's top, a stairwell, a hole): the next
|
||||
// room's floor centre (PointGraph), not no distance. At no cost, E74E#14 (2026-11-17) went from
|
||||
// the ground floor up through the air under its platform and down to the far end of the second
|
||||
// floor, rather than up the stairs beside it.
|
||||
Vec d = blk.Geo != null && blk.Geo.TryGetDoorway(c, nb, out var door)
|
||||
? new Vec(door.X, door.Y, door.Z)
|
||||
: blk.PointGraph.TryGetValue(nb, out var m)
|
||||
? new Vec(DungeonGeometry.NavToWorld(m.EW), DungeonGeometry.NavToWorld(m.NS), m.Z)
|
||||
: p;
|
||||
double step = cost[c] + p.DistanceTo(d) + 0.1; // a little for each doorway: fewer rooms when equal
|
||||
if (step >= cost.GetValueOrDefault(nb, double.MaxValue)) continue;
|
||||
cost[nb] = step;
|
||||
at[nb] = d;
|
||||
came[nb] = c;
|
||||
open.Enqueue(nb, step);
|
||||
}
|
||||
}
|
||||
if (!came.ContainsKey(toCell)) return new List<uint>();
|
||||
var path = new List<uint>();
|
||||
for (uint c = toCell; ; c = came[c])
|
||||
{
|
||||
path.Add(c);
|
||||
if (c == fromCell) break;
|
||||
}
|
||||
path.Reverse();
|
||||
return path;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A leg of the walk that crosses a wall (SegmentClear says no) is bent through one point it can go by
|
||||
/// with both halves clear: a room's middle or a doorway on the way (the walk's own cells), the one
|
||||
/// adding the least. BA17#4 (2026-11-17): from the raised 012D the walk went from its doorway straight
|
||||
/// at the front door across 012B, into the wall; by 012B's middle both halves are clear. A leg with
|
||||
/// no such point is left as it was.
|
||||
/// </summary>
|
||||
internal static int MendBlockedLegs(List<Vec> way, IReadOnlyList<uint> cells, DungeonGeometry geo, Func<Vec, Vec, bool> clear)
|
||||
{
|
||||
var vias = new List<Vec>();
|
||||
foreach (uint c in cells)
|
||||
if (geo.TryCellFloorCentre(c, out double x, out double y, out double z)) vias.Add(new Vec(x, y, z));
|
||||
for (int i = 0; i + 1 < cells.Count; i++)
|
||||
if (geo.TryGetDoorway(cells[i], cells[i + 1], out var d)) vias.Add(new Vec(d.X, d.Y, d.Z, true));
|
||||
int mended = 0;
|
||||
for (int i = 0; i + 1 < way.Count && mended < 8; i++)
|
||||
{
|
||||
Vec a = way[i], b = way[i + 1];
|
||||
if (clear(a, b)) continue;
|
||||
Vec? best = null;
|
||||
double bestLen = double.MaxValue;
|
||||
foreach (var v in vias)
|
||||
{
|
||||
if (v.DistanceTo(a) < 0.3 || v.DistanceTo(b) < 0.3) continue;
|
||||
double len = a.DistanceTo(v) + v.DistanceTo(b);
|
||||
if (len >= bestLen || !clear(a, v) || !clear(v, b)) continue;
|
||||
best = v;
|
||||
bestLen = len;
|
||||
}
|
||||
if (best is Vec via)
|
||||
{
|
||||
way.Insert(i + 1, via);
|
||||
mended++;
|
||||
i++; // the second half is clear: on past it
|
||||
continue;
|
||||
}
|
||||
// No one point: two (a room's middle, then a doorway, say), all three parts clear.
|
||||
Vec? b1 = null, b2 = null;
|
||||
foreach (var v in vias)
|
||||
{
|
||||
if (v.DistanceTo(a) < 0.3 || !clear(a, v)) continue;
|
||||
foreach (var w in vias)
|
||||
{
|
||||
if (w.Equals(v) || w.DistanceTo(b) < 0.3) continue;
|
||||
double len = a.DistanceTo(v) + v.DistanceTo(w) + w.DistanceTo(b);
|
||||
if (len >= bestLen || !clear(v, w) || !clear(w, b)) continue;
|
||||
b1 = v; b2 = w; bestLen = len;
|
||||
}
|
||||
}
|
||||
if (b1 is not Vec v1 || b2 is not Vec v2) continue;
|
||||
way.Insert(i + 1, v1);
|
||||
way.Insert(i + 2, v2);
|
||||
mended++;
|
||||
i += 2;
|
||||
}
|
||||
return mended;
|
||||
}
|
||||
|
||||
private PathResult WorkOutInside(uint fromCell, Vec from, uint toCell, Vec to)
|
||||
{
|
||||
var none = new PathResult(PathStatus.NoPath, Array.Empty<Vec>(), 0, 0);
|
||||
|
|
@ -197,10 +367,18 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
|
|||
var blk = BlockFor(fromCell >> 16);
|
||||
if (blk == null) return none;
|
||||
if (!blk.ByCell.TryGetValue(fromCell, out var bf) || !blk.ByCell.TryGetValue(toCell, out var bt) || bf != bt) return none;
|
||||
var cells = DungeonPathfinder.FindPath(fromCell, toCell, blk.Graph);
|
||||
// Each end in the cell whose floor holds it. A door is mostly a thin cell of its own, and its step in, 1.5 m
|
||||
// in, is on the next cell's floor (BA17#4's front door 0122: 012B's; Holtburg A9B4's 010B: 0104's): a walk
|
||||
// from it in the door's cell went back out to the doorway between the two first, then in again.
|
||||
if (blk.Geo != null)
|
||||
{
|
||||
fromCell = CellHolding(blk.Geo, fromCell, bf.Cells, from.X, from.Y, from.Z);
|
||||
toCell = CellHolding(blk.Geo, toCell, bt.Cells, to.X, to.Y, to.Z);
|
||||
}
|
||||
var cells = WalkCells(blk, fromCell, from, toCell, to);
|
||||
if (cells.Count == 0) return none;
|
||||
|
||||
var pts = DungeonPathfinder.BuildPathPoints(cells, blk.Graph, blk.Geo, null,
|
||||
var pts = DungeonPathfinder.BuildPathPoints(cells, blk.PointGraph, blk.Geo, null,
|
||||
DungeonGeometry.WorldToNav(from.Y), DungeonGeometry.WorldToNav(from.X), from.Z,
|
||||
DungeonGeometry.WorldToNav(to.Y), DungeonGeometry.WorldToNav(to.X), to.Z, out _, mergeSamePieces: false);
|
||||
var way = new List<Vec>(pts.Count + 2) { from };
|
||||
|
|
@ -212,6 +390,7 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
|
|||
var cellsOf = bf.Cells;
|
||||
Func<Vec, bool>? onFloor = geo == null ? null : v => geo.OnFloorOfAny(cellsOf, v.X, v.Y, v.Z);
|
||||
Func<Vec, Vec, bool>? clear = geo == null ? null : (a, b) => geo.SegmentClear(cellsOf, a.X, a.Y, a.Z, b.X, b.Y, b.Z, 0.3);
|
||||
if (geo != null && clear != null) MendBlockedLegs(way, cells, geo, clear);
|
||||
var status = KeepOutOfPortals(way, Portals, onFloor, clear, out double gap);
|
||||
if (status == PathStatus.NoPath) return none;
|
||||
|
||||
|
|
@ -388,8 +567,11 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
|
|||
/// A landblock's buildings from the dats: its cell graph, the room geometry (with DungeonLOS), and
|
||||
/// the polygons of its portal records to the outside (other cell 0xFFFF). Without DungeonLOS no
|
||||
/// door is known (the hunt then leaves its buildings alone, and walks out of one the way in).
|
||||
/// <paramref name="statics"/>: what the cells place, for the furniture (none: the rooms bare, as before).
|
||||
/// </summary>
|
||||
internal static Block Load(uint landblock, DatDatabase cellDat, DungeonLOS? los)
|
||||
internal static Block Load(uint landblock, DatDatabase cellDat, DungeonLOS? los,
|
||||
Func<uint, IReadOnlyList<(uint SetupId, uint CellId, BoundingVolume Mesh)>?>? statics = null,
|
||||
Func<double, double, double>? terrain = null)
|
||||
{
|
||||
// A graph of its own (never DungeonPathfinder's cached one): shared openings add edges to it.
|
||||
var graph = DungeonPathfinder.BuildGraph(landblock, cellDat);
|
||||
|
|
@ -417,7 +599,10 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
|
|||
}
|
||||
foreach (var p in los.GetDungeonMapFloorPolygons(landblock))
|
||||
if (p.Vertices != null && !p.IsPortal) floors.Add((p.CellId, p.Vertices));
|
||||
var block = Build(landblock, graph, portals, floors, walls, exitPolys);
|
||||
IReadOnlyList<(uint SetupId, uint CellId, BoundingVolume Mesh)>? placed = null;
|
||||
try { placed = statics?.Invoke(landblock); }
|
||||
catch { placed = null; } // no statics: the rooms bare, the doors and walks as before
|
||||
var block = Build(landblock, graph, portals, floors, walls, exitPolys, placed, terrain);
|
||||
block.ExitRecords = exits.Count;
|
||||
return block;
|
||||
}
|
||||
|
|
@ -503,15 +688,27 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
|
|||
/// the outside (each in its cell): openings shared by two cells join them; the cells joined to each
|
||||
/// other are a building; each opening wide and tall enough, its foot at the floor inside and the
|
||||
/// ground (no floor of the landblock) under its step out, is a door (facing out of its cell).
|
||||
/// <paramref name="statics"/> (what the cells place) go on the geometry as furniture before the doors
|
||||
/// are looked for, so no door's step in is inside one (AddFurniture).
|
||||
/// </summary>
|
||||
internal static Block Build(uint landblock, Dictionary<uint, DungeonNavNode> graph,
|
||||
IReadOnlyList<(uint, Vector3[])>? portals, IReadOnlyList<(uint, Vector3[])>? floors,
|
||||
IReadOnlyList<(uint, Vector3[])>? walls, IReadOnlyList<(uint Cell, Vector3[] Poly)> exitPolys)
|
||||
IReadOnlyList<(uint, Vector3[])>? walls, IReadOnlyList<(uint Cell, Vector3[] Poly)> exitPolys,
|
||||
IReadOnlyList<(uint SetupId, uint CellId, BoundingVolume Mesh)>? statics = null,
|
||||
Func<double, double, double>? terrain = null)
|
||||
{
|
||||
var exits = JoinSharedOpenings(graph, exitPolys, out int joined);
|
||||
DungeonGeometry? geo = portals == null ? null
|
||||
: DungeonGeometry.Build(graph, portals, floors ?? Array.Empty<(uint, Vector3[])>(), walls ?? Array.Empty<(uint, Vector3[])>());
|
||||
var block = new Block { Landblock = landblock, Graph = graph, Geo = geo, SharedOpenings = joined };
|
||||
if (geo != null) DungeonPathfinder.MarkBuildingMap(geo);
|
||||
if (geo != null && statics is { Count: > 0 })
|
||||
{
|
||||
var f = AddFurniture(geo, statics);
|
||||
block.PlacedGiven = statics.Count;
|
||||
block.Furniture = f.Kept;
|
||||
block.Stairs = f.Stairs.Count;
|
||||
}
|
||||
|
||||
// Buildings: the cells joined to each other (union-find over the portal records, either way).
|
||||
var parent = new Dictionary<uint, uint>(graph.Count);
|
||||
|
|
@ -548,7 +745,7 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
|
|||
foreach (var (cell, poly) in exits)
|
||||
{
|
||||
if (!block.ByCell.TryGetValue(cell, out var b) || !graph.TryGetValue(cell, out var node)) continue;
|
||||
if (TryDoor(cell, node, poly, geo, b.Cells, out var door, out string why))
|
||||
if (TryDoor(cell, node, poly, geo, b.Cells, out var door, out string why, terrain))
|
||||
{
|
||||
bool same = false;
|
||||
foreach (var d in b.Doors)
|
||||
|
|
@ -564,10 +761,12 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
|
|||
/// The door an opening to the outside makes, in <paramref name="cell"/>: facing out of the cell (the
|
||||
/// floor behind it is the cell's, else the cell's origin is behind it), its inner point on the cell's
|
||||
/// floor, its outer point OutsideMeters out. False (and why) for one too narrow, too low, or with its
|
||||
/// foot off the floor inside (a window).
|
||||
/// foot off the floor inside (a window). The inner point is never inside furniture, nor the leg in to
|
||||
/// it through one (InnerPoint). It can be past a doorway, in the next cell: a walk from it starts there
|
||||
/// (WorkOutInside, CellHolding).
|
||||
/// </summary>
|
||||
internal static bool TryDoor(uint cell, DungeonNavNode node, Vector3[] poly, DungeonGeometry? geo, IReadOnlyCollection<uint> buildingCells,
|
||||
out OutdoorHunt.Door door, out string why)
|
||||
out OutdoorHunt.Door door, out string why, Func<double, double, double>? terrain = null)
|
||||
{
|
||||
door = default;
|
||||
if (!DungeonGeometry.TryOpening(poly, out double x, out double y, out double z, out double nx, out double ny, out double width, out double top))
|
||||
|
|
@ -599,6 +798,30 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
|
|||
found = geo.TryFloorHeight(x - nx * s, y - ny * s, z, 2.5, out floor);
|
||||
if (!found) { why = "no floor inside it"; return false; }
|
||||
if (Math.Abs(z - floor) > DoorSillMax) { why = string.Format(inv, "its foot is {0:F1} m off the floor (a window)", z - floor); return false; }
|
||||
|
||||
// A window with a deep sill: the floor just inside is the sill's own top, level with the foot, and the
|
||||
// room's floor is a metre below (DreamWeave Thread B470#25, 2026-11-19: the hunt walked at its two 1.5 m
|
||||
// tall windows, 1.0 m over the room's floor and the ground, as doors). Under WindowTallMax, a foot more than a
|
||||
// step over both the ground outside and the floor a body stands on inside (WindowRoomFrom to InnerLongest in;
|
||||
// none there: no floor to step down to) is a window. Over the 1,633 landblocks with buildings this took 416
|
||||
// of 6,322 doors, every one 1.5 to 2.0 m tall; 9 buildings were left without a door, each an opening 5.7 m
|
||||
// up a tower or a wide window.
|
||||
if (terrain != null && top - z < WindowTallMax)
|
||||
{
|
||||
double ground = terrain(x + nx * OutsideMeters, y + ny * OutsideMeters);
|
||||
if (!double.IsNaN(ground) && z - ground > StepUpMeters)
|
||||
{
|
||||
double room = double.NaN;
|
||||
for (double s = InnerLongest; s >= WindowRoomFrom - 1e-9 && double.IsNaN(room); s -= 0.25)
|
||||
if (geo.TryFloorHeight(x - nx * s, y - ny * s, z, 2.5, out double f)) room = f;
|
||||
if (double.IsNaN(room) || z - room > StepUpMeters)
|
||||
{
|
||||
why = string.Format(inv, "a window: {0:F1} m tall, its foot {1:F1} m over the ground outside and {2}", top - z, z - ground,
|
||||
double.IsNaN(room) ? "no floor a step past it inside" : string.Format(inv, "{0:F1} m over the floor inside", z - room));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The step out is onto the ground: no floor of the landblock under it, from 8 m below to just
|
||||
|
|
@ -610,21 +833,237 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
|
|||
return false;
|
||||
}
|
||||
|
||||
// The inner point: as far in as InnerLongest that is on the building's floor.
|
||||
double inS = -1;
|
||||
if (geo != null)
|
||||
// The inner point: as far in as InnerLongest that is on the building's floor (and clear of furniture).
|
||||
double ix = x - nx, iy = y - ny;
|
||||
if (geo != null && !InnerPoint(geo, buildingCells, x, y, nx, ny, floor, out ix, out iy, out bool furniture))
|
||||
{
|
||||
for (double s = InnerLongest; s >= InnerShortest - 1e-9; s -= 0.25)
|
||||
if (geo.OnFloorOfAny(buildingCells, x - nx * s, y - ny * s, floor)) { inS = s; break; }
|
||||
if (inS < 0) { why = "no floor a step inside it"; return false; }
|
||||
why = furniture ? "furniture stands a step inside it" : "no floor a step inside it";
|
||||
return false;
|
||||
}
|
||||
else inS = 1.0;
|
||||
|
||||
door = new OutdoorHunt.Door(cell,
|
||||
Inner: new Vec(x - nx * inS, y - ny * inS, floor, true),
|
||||
Inner: new Vec(ix, iy, floor, true),
|
||||
At: new Vec(x, y, z, true),
|
||||
Outside: new Vec(x + nx * OutsideMeters, y + ny * OutsideMeters, z, true));
|
||||
why = "";
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>How far a door's step in goes to either side of its centre line when furniture is on the line.</summary>
|
||||
internal const double InnerSideways = 0.5;
|
||||
|
||||
/// <summary>
|
||||
/// The door's inner point: on its centre line as far in as InnerLongest (shortened in 0.25 m steps to
|
||||
/// InnerShortest) on the building's floor, not inside furniture, the leg in to it from the door crossing
|
||||
/// none; else the same InnerSideways either side of the line. False when none is (<paramref name="furniture"/>:
|
||||
/// one had a floor, furniture was in the way).
|
||||
/// </summary>
|
||||
private static bool InnerPoint(DungeonGeometry geo, IReadOnlyCollection<uint> buildingCells, double x, double y, double nx, double ny,
|
||||
double floor, out double ix, out double iy, out bool furniture)
|
||||
{
|
||||
furniture = false;
|
||||
bool objects = geo.PlacedCount > 0;
|
||||
foreach (double side in objects ? new[] { 0.0, InnerSideways, -InnerSideways } : new[] { 0.0 })
|
||||
{
|
||||
double ox = -ny * side, oy = nx * side;
|
||||
for (double s = InnerLongest; s >= InnerShortest - 1e-9; s -= 0.25)
|
||||
{
|
||||
ix = x - nx * s + ox; iy = y - ny * s + oy;
|
||||
if (!geo.OnFloorOfAny(buildingCells, ix, iy, floor)) continue;
|
||||
if (objects && !LegClearOfPlaced(geo, x, y, ix, iy, floor)) { furniture = true; continue; }
|
||||
return true;
|
||||
}
|
||||
}
|
||||
ix = iy = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>The straight walk from (x0, y0) to (x1, y1), on the floor under it (the nearest within a metre of
|
||||
/// <paramref name="floor"/>, then of the last sample's), is inside no placed object anywhere along it (every 0.1 m,
|
||||
/// the far end included). The floor under a door's step in can be a step below its sill (Holtburg A9B4#0's door
|
||||
/// 0102: the sill at 67.0, the room at 66.0, a bench there whose top is the sill's height).</summary>
|
||||
internal static bool LegClearOfPlaced(DungeonGeometry geo, double x0, double y0, double x1, double y1, double floor)
|
||||
{
|
||||
double len = Math.Sqrt(Sq(x1 - x0) + Sq(y1 - y0));
|
||||
int n = Math.Max(1, (int)Math.Ceiling(len / 0.1));
|
||||
double h = floor;
|
||||
for (int k = 1; k <= n; k++)
|
||||
{
|
||||
double t = (double)k / n, px = x0 + (x1 - x0) * t, py = y0 + (y1 - y0) * t;
|
||||
if (geo.TryFloorHeight(px, py, h, 1.0, out double fh)) h = fh;
|
||||
if (geo.InsidePlaced(px, py, h)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The building's cell whose floor (the nearest in height to <paramref name="floor"/>, within 0.6 m) holds (x, y):
|
||||
/// <paramref name="cell"/> itself when its floor does; <paramref name="cell"/> too when none does.</summary>
|
||||
private static uint CellHolding(DungeonGeometry geo, uint cell, IReadOnlyCollection<uint> buildingCells, double x, double y, double floor)
|
||||
{
|
||||
if (geo.TryCellFloorHeight(cell, x, y, floor, out double h0) && Math.Abs(h0 - floor) <= 0.6) return cell;
|
||||
uint best = cell;
|
||||
double bestDz = 0.6;
|
||||
foreach (uint c in buildingCells)
|
||||
if (c != cell && geo.TryCellFloorHeight(c, x, y, floor, out double h) && Math.Abs(h - floor) <= bestDz) { best = c; bestDz = Math.Abs(h - floor); }
|
||||
return best;
|
||||
}
|
||||
|
||||
// ── Placed objects (2026-11-18) ─────────────────────────────────────────────────────────────
|
||||
//
|
||||
// A building's cells place its furniture (tables, chairs, beds, stools, benches, cabinets) and, in most
|
||||
// buildings, its stairs too: 6,350 of the 6,571 placed stairs world-wide stand on a flat cell floor, the
|
||||
// object the only thing to walk up. Without them every walk went through the furniture (the survey's six
|
||||
// landblocks 7D64, E74E, BA17, A9B4, A9B3 and DF61: 194 of 1,110 walks, 88 of their corners inside a piece).
|
||||
// The furniture goes on the map as the dungeon map's placed objects (DungeonGeometry.AddPlacedObjects: walls
|
||||
// round what is in a body's way at its floor), the stairs stay off it: as walls the ground floor would meet a
|
||||
// stair's sides on every walk up (stairs as floors is a later step).
|
||||
//
|
||||
// A stair is a CONNECTOR that also climbs by itself. The map's own class alone is not enough here: its chain
|
||||
// of walkable faces runs across objects, so a chair (its seat, then the top of its back at 1.02 m), a cup on a
|
||||
// table and a cabinet beside one are connectors too (in the six landblocks 107 of the 184 connectors are such
|
||||
// furniture). What climbs by itself: a sloped walkable face of some size (a ramp, a stair's stringer: furniture
|
||||
// tops are flat), walkable faces at three heights or more over 0.9 m, or a slab raised a metre or more (the landing
|
||||
// between DF61 010C's two ramps). A sphere's cap is sloped too, but in triangles too small to count; its rings are
|
||||
// walkable faces at many heights though, so the loader's round solids (its cylinders and spheres) are never stairs: a
|
||||
// 1 m ball the chain ran to from a dais beside it was taken for steps and left off (8090012A's 0x0200035E, review of
|
||||
// wf/obst-int). Besides those
|
||||
// 77, a piece the map doesn't take for a connector is still a stair when it is a ramp up from its own floor (the
|
||||
// bottom step of a stair whose chain doesn't reach the next: 7 in the six). Measured: every stair of the six the
|
||||
// survey's own rule found is one of these 84, but for 7 spheres and platforms that rule counted by their caps.
|
||||
// Dungeons are not touched: there every object the map takes stays a wall (DungeonPathfinder.AddPlacedObjectsTo).
|
||||
|
||||
/// <summary>A walkable face less flat than this (nz) is a slope: a ramp, a stair's stringer.</summary>
|
||||
internal const double StairSlopeNz = 0.95;
|
||||
/// <summary>A sloped face at least this big (m2, one triangle) makes a connector a stair; a sphere's cap rings are smaller.</summary>
|
||||
internal const double StairSlopeTriangle = 0.3;
|
||||
/// <summary>Stepped: walkable faces at StairSteps heights or more, StairStepGap apart, spanning StairStepSpan.</summary>
|
||||
internal const double StairStepGap = 0.15, StairStepSpan = 0.9;
|
||||
internal const int StairSteps = 3;
|
||||
/// <summary>A raised slab: its bottom this far over its floor, its flat walkable area (m2) this big.</summary>
|
||||
internal const double StairSlabRaised = 1.0, StairSlabArea = 1.0;
|
||||
|
||||
/// <summary>Which of a landblock's placed objects a building map takes: what the dungeon map would (in the body band at its
|
||||
/// floor) less the stairs, whose keys it keeps.</summary>
|
||||
internal sealed class FurnitureFilter
|
||||
{
|
||||
private readonly Dictionary<PieceKey, Vector3[]> _tris = new();
|
||||
private readonly HashSet<PieceKey> _round = new();
|
||||
/// <summary>The pieces left out as stairs.</summary>
|
||||
public readonly HashSet<PieceKey> Stairs = new();
|
||||
/// <summary>How many went on the map.</summary>
|
||||
public int Kept;
|
||||
|
||||
/// <summary><paramref name="round"/>: the pieces that are the loader's cylinders and spheres (BoundingVolume.Round), never stairs.</summary>
|
||||
public FurnitureFilter(IEnumerable<(uint SetupId, uint CellId, Vector3[] Triangles)> pieces, IEnumerable<PieceKey>? round = null)
|
||||
{
|
||||
foreach (var (setup, cell, tris) in pieces)
|
||||
if (KeyOf(setup, cell, tris) is PieceKey k) _tris.TryAdd(k, tris);
|
||||
if (round != null) _round.UnionWith(round);
|
||||
}
|
||||
|
||||
public PlacedObjectOptions Options => new() { Keep = Keep };
|
||||
|
||||
private bool Keep(PlacedInfo p)
|
||||
{
|
||||
if (p.Class is not (PlacedClass.Obstacle or PlacedClass.StepOver or PlacedClass.Connector)) return false;
|
||||
var k = new PieceKey(p.Setup, p.Cell, p.MinX, p.MinY, p.MinZ, p.MaxX, p.MaxY, p.MaxZ);
|
||||
if (!_round.Contains(k) && _tris.TryGetValue(k, out var t)
|
||||
&& (p.Class == PlacedClass.Connector ? ClimbsByItself(t, p.Floor) : RampFromFloor(t, p.Floor)))
|
||||
{
|
||||
Stairs.Add(k);
|
||||
return false;
|
||||
}
|
||||
Kept++;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A placed piece by its model, cell and box (the box PlacedSolid gives it: its vertices' own).</summary>
|
||||
internal readonly record struct PieceKey(uint Setup, uint Cell, double MinX, double MinY, double MinZ, double MaxX, double MaxY, double MaxZ);
|
||||
|
||||
internal static PieceKey? KeyOf(uint setup, uint cell, Vector3[]? tris)
|
||||
{
|
||||
if (tris == null || tris.Length < 3) return null;
|
||||
int n = tris.Length - tris.Length % 3;
|
||||
double minX = double.MaxValue, minY = double.MaxValue, minZ = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue, maxZ = double.MinValue;
|
||||
for (int k = 0; k < n; k++)
|
||||
{
|
||||
var p = tris[k];
|
||||
if (p.X < minX) minX = p.X; if (p.X > maxX) maxX = p.X;
|
||||
if (p.Y < minY) minY = p.Y; if (p.Y > maxY) maxY = p.Y;
|
||||
if (p.Z < minZ) minZ = p.Z; if (p.Z > maxZ) maxZ = p.Z;
|
||||
}
|
||||
return new PieceKey(setup, cell, minX, minY, minZ, maxX, maxY, maxZ);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A piece standing on <paramref name="floor"/> climbs by itself (see the section's comment): a sloped walkable
|
||||
/// triangle of StairSlopeTriangle or more, walkable faces at StairSteps heights over StairStepSpan, or a raised slab.
|
||||
/// Either winding counts: the dats list some stairs' faces both ways round (Holtburg A9B3's 020001B4).
|
||||
/// </summary>
|
||||
internal static bool ClimbsByItself(Vector3[] t, double floor)
|
||||
{
|
||||
double bottom = double.MaxValue, flat = 0;
|
||||
int lo = int.MaxValue, hi = int.MinValue;
|
||||
var heights = new HashSet<int>();
|
||||
bool slope = false;
|
||||
for (int i = 0; i + 2 < t.Length; i += 3)
|
||||
{
|
||||
var p0 = t[i]; var p1 = t[i + 1]; var p2 = t[i + 2];
|
||||
bottom = Math.Min(bottom, Math.Min(p0.Z, Math.Min(p1.Z, p2.Z)));
|
||||
double ux = p1.X - p0.X, uy = p1.Y - p0.Y, uz = p1.Z - p0.Z, vx = p2.X - p0.X, vy = p2.Y - p0.Y, vz = p2.Z - p0.Z;
|
||||
double cx = uy * vz - uz * vy, cy = uz * vx - ux * vz, cz = ux * vy - uy * vx, len = Math.Sqrt(cx * cx + cy * cy + cz * cz);
|
||||
if (len < 1e-9) continue;
|
||||
double nz = Math.Abs(cz) / len;
|
||||
if (nz < DungeonGeometry.WalkableNz) continue;
|
||||
double area = len / 2;
|
||||
if (nz < StairSlopeNz) { if (area >= StairSlopeTriangle) slope = true; }
|
||||
else flat += area;
|
||||
double h = (p0.Z + p1.Z + p2.Z) / 3.0 - floor;
|
||||
if (h < StairStepGap || h > 6.0) continue;
|
||||
int step = (int)Math.Round(h / StairStepGap);
|
||||
if (heights.Add(step)) { lo = Math.Min(lo, step); hi = Math.Max(hi, step); }
|
||||
}
|
||||
if (slope) return true;
|
||||
if (heights.Count >= StairSteps && (hi - lo) * StairStepGap >= StairStepSpan - 1e-9) return true;
|
||||
// A slab's top and bottom are both flat walkable faces: half the area is its top.
|
||||
return bottom - floor >= StairSlabRaised && flat / 2 >= StairSlabArea;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A piece the map doesn't take for a connector that is still a ramp up from its floor: a sloped walkable triangle of
|
||||
/// StairSlopeTriangle or more whose foot is on the floor (within StairStepGap). The bottom step of a stair whose next
|
||||
/// one the chain doesn't reach (E74E's door steps: 01000ACA, 0 to 0.6 m, under 01000AC5 and 01000ACD up to the sill
|
||||
/// at 32.0), a dais with sloped sides (7D64's 0200033D). A desk's or a lectern's top is no ramp: its foot is off the floor.
|
||||
/// </summary>
|
||||
internal static bool RampFromFloor(Vector3[] t, double floor)
|
||||
{
|
||||
for (int i = 0; i + 2 < t.Length; i += 3)
|
||||
{
|
||||
var p0 = t[i]; var p1 = t[i + 1]; var p2 = t[i + 2];
|
||||
double ux = p1.X - p0.X, uy = p1.Y - p0.Y, uz = p1.Z - p0.Z, vx = p2.X - p0.X, vy = p2.Y - p0.Y, vz = p2.Z - p0.Z;
|
||||
double cx = uy * vz - uz * vy, cy = uz * vx - ux * vz, cz = ux * vy - uy * vx, len = Math.Sqrt(cx * cx + cy * cy + cz * cz);
|
||||
if (len < 1e-9) continue;
|
||||
double nz = Math.Abs(cz) / len;
|
||||
if (nz < DungeonGeometry.WalkableNz || nz >= StairSlopeNz || len / 2 < StairSlopeTriangle) continue;
|
||||
if (Math.Min(p0.Z, Math.Min(p1.Z, p2.Z)) - floor <= StairStepGap) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>The furniture onto <paramref name="geo"/> (DungeonGeometry.AddPlacedObjects, the stairs left out).</summary>
|
||||
internal static FurnitureFilter AddFurniture(DungeonGeometry geo, IReadOnlyList<(uint SetupId, uint CellId, BoundingVolume Mesh)> statics)
|
||||
{
|
||||
var pieces = new List<(uint, uint, Vector3[])>(statics.Count);
|
||||
var round = new List<PieceKey>();
|
||||
foreach (var s in statics)
|
||||
if (s.Mesh?.MeshTriangles is { Length: >= 3 } t)
|
||||
{
|
||||
pieces.Add((s.SetupId, s.CellId, t));
|
||||
if (s.Mesh.Round && KeyOf(s.SetupId, s.CellId, t) is PieceKey k) round.Add(k);
|
||||
}
|
||||
var filter = new FurnitureFilter(pieces, round);
|
||||
geo.AddPlacedObjects(pieces, filter.Options);
|
||||
return filter;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -36,6 +36,18 @@
|
|||
// returning false, a "too busy" line for it, or an error in its UseDone) turns the fast
|
||||
// path off for the rest of the pass, logged. Every refusal during buffing is counted for
|
||||
// as a running total since load, logged one line each, and each pass ends with a summary line.
|
||||
//
|
||||
// Vital casts in the between-fights top-off (2026-11-20): Heal Self, Revitalize and Stamina to
|
||||
// Mana after one another waited on the same animation gate after each UseDone (200-750 ms in the
|
||||
// logs: Revitalize UseDone 20:52:40.784, the next one sent 40.996; Executor's Blessing UseDone
|
||||
// 11:55:01.293, Stamina to Mana sent 02.049), on top of the server's 2.2 s cast and 1.0 s recoil.
|
||||
// The same ACE rule holds for them (one Player_Magic path). SentVital records a vital cast;
|
||||
// EligibleVital lets the NEXT vital cast skip the animation gate when the last action was our
|
||||
// own vital cast answered UseDone(0), with every condition above. BuffManager asks only with no
|
||||
// monster within Monster Range (in a fight nothing changes), in Magic stance, and lets only a
|
||||
// vital cast ride it (no kit, potion, stance change or buff). A refusal of a fast vital cast
|
||||
// turns the vital fast path off for VitalOffMs. A buff never chains on a vital's UseDone, and a
|
||||
// vital never on a buff's (Eligible / EligibleVital check which kind went last).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
|
@ -56,6 +68,8 @@ internal sealed class BuffCastChain
|
|||
private long _movesAfter;
|
||||
private bool _moveCounted; // MovementWaits counted for this send
|
||||
private bool _wasFast;
|
||||
private bool _wasVital; // the last cast recorded was a vital (SentVital), not a buff
|
||||
private DateTime _vitalOffUntil = DateTime.MinValue; // a refused fast vital cast: no vital fast path until then
|
||||
private bool _heldForAnimation; // the next buff goes through the animation gate (HoldForAnimation)
|
||||
private bool _answerSeen; // the first UseDone after it was read
|
||||
private bool _answerOk; // ... and it was UseDone(0), the next UseDone after the send
|
||||
|
|
@ -75,6 +89,13 @@ internal sealed class BuffCastChain
|
|||
public int PassesSwitchedOff { get; private set; }
|
||||
/// <summary>Times the fast path was refused because a movement call went out after the last buff.</summary>
|
||||
public int MovementWaits { get; private set; }
|
||||
/// <summary>Vital casts recorded (SentVital), and those that went on the vital fast path.</summary>
|
||||
public int VitalCasts { get; private set; }
|
||||
public int VitalFastCasts { get; private set; }
|
||||
/// <summary>Times a refusal turned the vital fast path off for VitalOffMs.</summary>
|
||||
public int VitalSwitchOffs { get; private set; }
|
||||
/// <summary>How long a refused fast vital cast keeps the vital fast path off.</summary>
|
||||
public const double VitalOffMs = 60_000;
|
||||
|
||||
/// <summary>True when a refusal turned the fast path off for the rest of this pass.</summary>
|
||||
public bool OffThisPass => _offThisPass;
|
||||
|
|
@ -113,6 +134,7 @@ internal sealed class BuffCastChain
|
|||
_movesAfter = moves;
|
||||
_moveCounted = false;
|
||||
_wasFast = fast;
|
||||
_wasVital = false;
|
||||
_heldForAnimation = false;
|
||||
_answerSeen = false;
|
||||
_answerOk = false;
|
||||
|
|
@ -122,6 +144,54 @@ internal sealed class BuffCastChain
|
|||
if (fast) { FastCasts++; _passFast++; }
|
||||
}
|
||||
|
||||
/// <summary>A vital cast went out (Heal Self, Revitalize, Stamina to Mana ... out of a fight): the
|
||||
/// same tracking as <see cref="Sent"/>, counted as a vital, not a buff of the pass.</summary>
|
||||
public void SentVital(int spellId, string name, int seqAtSend, long started, long attacks, long moves, bool fast)
|
||||
{
|
||||
_spellId = spellId;
|
||||
_name = name;
|
||||
_seqAtSend = seqAtSend;
|
||||
_startedAfter = started;
|
||||
_attacksAfter = attacks;
|
||||
_movesAfter = moves;
|
||||
_moveCounted = false;
|
||||
_wasFast = fast;
|
||||
_wasVital = true;
|
||||
_heldForAnimation = false;
|
||||
_answerSeen = false;
|
||||
_answerOk = false;
|
||||
_answerSeenAt = DateTime.MinValue;
|
||||
VitalCasts++;
|
||||
if (fast) VitalFastCasts++;
|
||||
}
|
||||
|
||||
/// <summary>The client refused a vital cast (nothing went out). On the vital fast path: off for VitalOffMs.</summary>
|
||||
public void VitalClientRefused(int spellId, string name, bool fast, DateTime now, Action<string> log)
|
||||
{
|
||||
ClientRefusals++;
|
||||
log($"[BuffChain] refusal (client): CastSpell refused vital '{name}' (id {spellId}){(fast ? " on the fast path" : "")}" +
|
||||
$" - totals client {ClientRefusals}, server {ServerRefusals}, too-busy lines {TooBusyLines}");
|
||||
if (fast) VitalOff("the client refused a fast-path vital cast", now, log);
|
||||
_spellId = 0;
|
||||
}
|
||||
|
||||
/// <summary>A "You're too busy!" line while <paramref name="pendingSpellId"/> (a vital of ours) waited for its result.</summary>
|
||||
public void TooBusyLineVital(int pendingSpellId, DateTime now, Action<string> log)
|
||||
{
|
||||
if (pendingSpellId == 0 || pendingSpellId != _spellId || !_wasVital) return;
|
||||
TooBusyLines++;
|
||||
log($"[BuffChain] refusal (too-busy line) while vital '{_name}' was pending{(_wasFast ? " (sent on the fast path)" : "")}" +
|
||||
$" - totals client {ClientRefusals}, server {ServerRefusals}, too-busy lines {TooBusyLines}");
|
||||
if (_wasFast) VitalOff("a fast-path vital cast drew 'You're too busy!'", now, log);
|
||||
}
|
||||
|
||||
private void VitalOff(string why, DateTime now, Action<string> log)
|
||||
{
|
||||
_vitalOffUntil = now.AddMilliseconds(VitalOffMs);
|
||||
VitalSwitchOffs++;
|
||||
log($"[BuffChain] {why}: vital casts wait for the animation again for {VitalOffMs / 1000:0} s");
|
||||
}
|
||||
|
||||
/// <summary>The client refused a buff cast (CastSpell returned false: nothing went out).</summary>
|
||||
public void ClientRefused(int spellId, string name, bool fast, Action<string> log)
|
||||
{
|
||||
|
|
@ -148,10 +218,14 @@ internal sealed class BuffCastChain
|
|||
if (next && lastErr != 0)
|
||||
{
|
||||
ServerRefusals++;
|
||||
_passServer++;
|
||||
log($"[BuffChain] refusal (server): UseDone error 0x{lastErr:X} for '{_name}'{(_wasFast ? " on the fast path" : "")}" +
|
||||
if (!_wasVital) _passServer++;
|
||||
log($"[BuffChain] refusal (server): UseDone error 0x{lastErr:X} for {(_wasVital ? "vital " : "")}'{_name}'{(_wasFast ? " on the fast path" : "")}" +
|
||||
$" - totals client {ClientRefusals}, server {ServerRefusals}, too-busy lines {TooBusyLines}");
|
||||
if (_wasFast) SwitchOff($"the server refused a fast-path cast (0x{lastErr:X})", log);
|
||||
if (_wasFast)
|
||||
{
|
||||
if (_wasVital) VitalOff($"the server refused a fast-path vital cast (0x{lastErr:X})", now, log);
|
||||
else SwitchOff($"the server refused a fast-path cast (0x{lastErr:X})", log);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -184,6 +258,25 @@ internal sealed class BuffCastChain
|
|||
/// The caller has checked the setting, the pacing and the vitals.
|
||||
/// </summary>
|
||||
public bool Eligible(long started, long attacks, long moves, bool hasLast, int lastSeq, uint lastErr, int seqNow, DateTime now, out string why)
|
||||
{
|
||||
why = "";
|
||||
if (_wasVital) return false; // a buff never chains on a vital's UseDone (unchanged buff behaviour)
|
||||
return EligibleCore(started, attacks, moves, hasLast, lastSeq, lastErr, seqNow, now, out why);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// May the next VITAL cast skip the animation gate? Only right after our own vital cast's UseDone(0),
|
||||
/// with every condition of <see cref="Eligible"/>, and not within VitalOffMs of a refused fast vital.
|
||||
/// The caller has checked the setting, the pacing, the stance and that no monster is within range.
|
||||
/// </summary>
|
||||
public bool EligibleVital(long started, long attacks, long moves, bool hasLast, int lastSeq, uint lastErr, int seqNow, DateTime now, out string why)
|
||||
{
|
||||
why = "";
|
||||
if (!_wasVital || now < _vitalOffUntil) return false;
|
||||
return EligibleCore(started, attacks, moves, hasLast, lastSeq, lastErr, seqNow, now, out why);
|
||||
}
|
||||
|
||||
private bool EligibleCore(long started, long attacks, long moves, bool hasLast, int lastSeq, uint lastErr, int seqNow, DateTime now, out string why)
|
||||
{
|
||||
why = "";
|
||||
if (_offThisPass || _heldForAnimation || _spellId == 0 || !_answerSeen || !_answerOk) return false;
|
||||
|
|
@ -202,5 +295,6 @@ internal sealed class BuffCastChain
|
|||
|
||||
public string Describe() =>
|
||||
$"Buff chain: {FastCasts} of {BuffCasts} buff casts on the fast path; refusals client {ClientRefusals}, " +
|
||||
$"server {ServerRefusals}, too-busy lines {TooBusyLines}; passes switched off {PassesSwitchedOff}; movement waits {MovementWaits}";
|
||||
$"server {ServerRefusals}, too-busy lines {TooBusyLines}; passes switched off {PassesSwitchedOff}; movement waits {MovementWaits}; " +
|
||||
$"vital casts {VitalFastCasts} of {VitalCasts} on the fast path, vital switch-offs {VitalSwitchOffs}";
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,71 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - Combat/BuffManager.HealAnimationCap.cs
|
||||
// A heal under a heal line waits on the character's animation for HealAnimationCapMs at most.
|
||||
//
|
||||
// The vitals step waits while the client's motion queue reads busy (ActionPacer.GestureHolds) and
|
||||
// while the engine's cast gate is closed (CastGateWatchdog). Both limits (4 s, 1.5 s at Emergency
|
||||
// Heal At) count one unbroken busy spell. A monster hitting the character plays a recoil on every
|
||||
// hit, so the queue reads busy, clear for a moment, busy again: every spell starts the count from
|
||||
// 0 and the limit never comes, while a tick that happens to read busy holds the heal each time.
|
||||
//
|
||||
// Here the time a heal is held by the animation counts all told, across those clear moments, from
|
||||
// the first such hold until the vitals step is reached (a gate let it through) or health is over
|
||||
// every heal line. Past HealAnimationCapMs the heal skips both animation gates (logged once per
|
||||
// hold). Every other gate keeps its rules: an unanswered action of ours, the busy count, a cast in
|
||||
// flight, the player's turn.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
public partial class BuffManager
|
||||
{
|
||||
/// <summary>The longest a heal under a heal line waits on the character's animation, all told.</summary>
|
||||
internal const double HealAnimationCapMs = 1000;
|
||||
|
||||
private DateTime _healAnimHeldSince = DateTime.MinValue;
|
||||
private bool _healAnimCapLogged;
|
||||
|
||||
/// <summary>Times a heal went on without the animation gates (tests, status).</summary>
|
||||
internal int HealAnimationCaps { get; private set; }
|
||||
|
||||
/// <summary>The pacer's hold reasons that are the character's animation (ActionPacer.GestureHolds / SwingHolds).</summary>
|
||||
internal static bool IsAnimationHold(string why) =>
|
||||
why.StartsWith("the character is still animating", StringComparison.Ordinal)
|
||||
|| why.StartsWith("a swing sent", StringComparison.Ordinal);
|
||||
|
||||
/// <summary>True when a heal is due and the animation has held it HealAnimationCapMs or more.</summary>
|
||||
private bool HealAnimationCapReached()
|
||||
{
|
||||
if (HealNeedNow() == HealNeed.None) { EndHealAnimationHold(); return false; }
|
||||
if (_healAnimHeldSince == DateTime.MinValue) return false;
|
||||
double ms = (RynthClock.Now - _healAnimHeldSince).TotalMilliseconds;
|
||||
if (ms < HealAnimationCapMs) return false;
|
||||
if (!_healAnimCapLogged)
|
||||
{
|
||||
_healAnimCapLogged = true;
|
||||
HealAnimationCaps++;
|
||||
string line = ActiveHealLine(_vitals.HealthPct, _vitals.StaminaPct, out int value, out _);
|
||||
_host.Log($"[RynthAi] Vitals: the heal has waited {ms:0} ms on the character's animation " +
|
||||
$"(health {_vitals.HealthPct}% under {line} {value}%): it goes on without the animation gate.");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The vitals step was held this tick; <paramref name="animation"/>: by the character's animation.</summary>
|
||||
private void NoteHealAnimationHold(bool animation)
|
||||
{
|
||||
if (!animation || _healAnimHeldSince != DateTime.MinValue) return;
|
||||
if (HealNeedNow() == HealNeed.None) return;
|
||||
_healAnimHeldSince = RynthClock.Now;
|
||||
}
|
||||
|
||||
/// <summary>The vitals step was reached, or no heal is due: the count starts again at the next hold.</summary>
|
||||
private void EndHealAnimationHold()
|
||||
{
|
||||
_healAnimHeldSince = DateTime.MinValue;
|
||||
_healAnimCapLogged = false;
|
||||
}
|
||||
}
|
||||
|
|
@ -260,7 +260,7 @@ public partial class BuffManager
|
|||
private void StartFailsafeRecall(DateTime now, int hp, double failedSec)
|
||||
{
|
||||
HpFailsafeRecalls++;
|
||||
_settings.IsMacroRunning = false;
|
||||
_settings.SetMacroRunning(false, "the HP failsafe (heals failing at Emergency Heal At: a recall)");
|
||||
_macroStoppedByFailsafe = true;
|
||||
MacroStopForRecall?.Invoke();
|
||||
// The heal the jump broke is not waited on, here or by the pacer: a stuck cast may never be
|
||||
|
|
@ -319,7 +319,7 @@ public partial class BuffManager
|
|||
else if (MayRestartMacro != null && !MayRestartMacro()) what = "the macro stays off (VTank yield)";
|
||||
else
|
||||
{
|
||||
_settings.IsMacroRunning = true; // the heals and kits run again; the failsafe re-arms
|
||||
_settings.SetMacroRunning(true, "the HP failsafe after its recall"); // the heals and kits run again; the failsafe re-arms
|
||||
what = "macro back on to keep healing";
|
||||
}
|
||||
_macroStoppedByFailsafe = false;
|
||||
|
|
|
|||
|
|
@ -8,8 +8,8 @@
|
|||
//
|
||||
// Kit picks read the client's live pack walk (ConsumableLookup.Resolve, BestPackHealingKit,
|
||||
// BestPackStaminaKit: WorldObjectCache.GetDirectInventory), which drops a removed kit, but a walk is
|
||||
// reused for up to a second (DirectInventoryCooldownMs) and the next kit goes out KitLandGraceMs
|
||||
// (700 ms) after the line, inside that reuse. An engine without GetContainerContents has no walk at
|
||||
// reused for up to a second (DirectInventoryCooldownMs) and the next kit goes out at most
|
||||
// KitVitalsCatchUpMs (300 ms; 700 ms before 2026-11-20) after the line, inside that reuse. An engine without GetContainerContents has no walk at
|
||||
// all: its inventory view is the object cache, which can keep a removed kit for good.
|
||||
//
|
||||
// So: the line names the kit in flight -> every kit pick skips that kit. With the live walk the skip
|
||||
|
|
|
|||
|
|
@ -108,7 +108,7 @@ public partial class BuffManager
|
|||
|
||||
if (IsWieldedLive(bowId))
|
||||
{
|
||||
int openPack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: 1);
|
||||
int openPack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: 1, new[] { bowId });
|
||||
if (openPack == 0 || _bowDequipAttempts >= BowDequipMaxAttempts)
|
||||
{
|
||||
// No verified-open pack to receive the bow, or repeated dequip
|
||||
|
|
|
|||
|
|
@ -19,6 +19,9 @@
|
|||
// chance, and refusing the spell there killed Drakkon; the surest heal goes;
|
||||
// - Stamina to Mana never swaps in a fight (InCombatNow), potion or not; out of a fight it may, even
|
||||
// with a mana potion carried (buffing is about to swap to the wand anyway).
|
||||
// - out of a fight (2026-11-20), a healing kit under Kit Min Success % (KitChanceOk, the weapon-out
|
||||
// bar included) doesn't refuse Heal Self's swap: the between-fights top-off otherwise sent a 3-19%
|
||||
// kit again and again (3.1 s a try) as the last resort.
|
||||
// Buffing (EnsureMagicMode forBuff) is not gated and still swaps, and so does the HP failsafe's
|
||||
// Lifestone Recall (it calls EnsureMagicMode itself, with the macro off).
|
||||
//
|
||||
|
|
@ -90,6 +93,15 @@ public partial class BuffManager
|
|||
// means "this is my emergency heal", kit or no kit.
|
||||
allowed = $"health {_vitals.HealthPct}% at or under Stamina To Health At {_settings.StaminaToHealthAt}%";
|
||||
}
|
||||
else if (label == LabelHealing && !InCombatNow() && HealthKitUnderMinSuccess(out string kitName))
|
||||
{
|
||||
// The between-fights top-off (2026-11-20): with no monster within Monster Range the shield
|
||||
// argument is gone, and a kit under Kit Min Success % (the weapon-out bar, 30%, from melee)
|
||||
// fails most uses: an Eternal Health Kit at 3-19% on 317-346 missing, each try 3.1 s,
|
||||
// was the "kit despite Kit Min Success" last resort until health crept up. As for stamina
|
||||
// kits (2026-11-13), the % is respected: the wand comes out for Heal Self. In a fight, unchanged.
|
||||
allowed = $"out of a fight, {kitName} is under Kit Min Success %";
|
||||
}
|
||||
else
|
||||
{
|
||||
bool stamina = label == LabelStamina;
|
||||
|
|
@ -192,6 +204,30 @@ public partial class BuffManager
|
|||
return HasPackKit("Healing Kit");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The healing kit AttemptHealthKitUse would pick (the first listed one, else the pack's best) is under
|
||||
/// Kit Min Success % for what is missing now (KitChanceOk, the weapon-out bar included). No kit: false.
|
||||
/// </summary>
|
||||
private bool HealthKitUnderMinSuccess(out string kitName)
|
||||
{
|
||||
kitName = "";
|
||||
if (_worldObjectCache == null) return false;
|
||||
WorldObject? kit = null;
|
||||
foreach (var r in _settings.ConsumableRules)
|
||||
if (r.Type.Equals("HealthKit", StringComparison.OrdinalIgnoreCase)
|
||||
&& !(r.Name ?? "").Contains("Stamina Kit", StringComparison.OrdinalIgnoreCase)
|
||||
&& ConsumableLookup.Resolve(_worldObjectCache, r, KitOutForGate) is WorldObject wo
|
||||
&& IsUseOnSelfKit(wo)) { kit = wo; break; }
|
||||
kit ??= BestPackHealingKit();
|
||||
if (kit == null || KitOutForGate(kit.Id)) return false;
|
||||
uint missing = _vitals.MaxHealth > _vitals.CurrentHealth ? _vitals.MaxHealth - _vitals.CurrentHealth : 0;
|
||||
if (KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits && !_vitalsNoPeaceSwitch,
|
||||
_settings.KitMinSuccessPct, log: false))
|
||||
return false;
|
||||
kitName = kit.Name ?? "the healing kit";
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>A stamina kit AttemptStaminaKitUse could pick.</summary>
|
||||
// Only one Stamina Kit Min Success % lets through (2026-11-13): a kit under it is never used, so it
|
||||
// must not refuse Revitalize's swap either (that left a melee character with no stamina source, and
|
||||
|
|
|
|||
|
|
@ -293,6 +293,9 @@ public partial class BuffManager : IDisposable
|
|||
internal BuffCastChain Chain => _chain;
|
||||
/// <summary>This tick skipped the animation gate (the fast path): only a buff cast may go out.</summary>
|
||||
private bool _fastChainTick;
|
||||
/// <summary>This tick skipped the animation gate for a vital cast in the between-fights top-off
|
||||
/// (FastVitalChainNow): only a vital spell cast may go out; a kit, potion or buff waits a tick.</summary>
|
||||
private bool _fastVitalTick;
|
||||
private string _fastChainWhy = "";
|
||||
|
||||
// Held-cast nudge (2026-10-05): a cast the server holds open (incantation, no result) is
|
||||
|
|
@ -375,33 +378,68 @@ public partial class BuffManager : IDisposable
|
|||
return _healthFellAt != DateTime.MinValue && (now - _healthFellAt).TotalMilliseconds < HealthFellCountsMs;
|
||||
}
|
||||
|
||||
// ── Buffs wait while hurt in a fight (2026-11-07) ──
|
||||
// Drakkon cast four weapon auras (2.4 s each) one after another with a golem's Force Bolts hitting him
|
||||
// and his health under Heal At; the emergency heal then waited for the last aura's cast and he died.
|
||||
// Under Heal At in a fight no new buff cast starts (one already sent finishes) and the arbiter doesn't
|
||||
// give Buffing the tick for buffs: the heals (vital recharge keeps its slot) and combat go first. The
|
||||
// buffs carry on once health is back over Heal At or the fight is over.
|
||||
private bool _buffHurtWaitOn;
|
||||
// ── Buffs wait for the fight (2026-11-07, every buff since 2026-11-20) ──
|
||||
// 2026-11-07: a character cast four weapon auras (2.4 s each) one after another with a golem's Force Bolts
|
||||
// hitting him and his health under Heal At; the emergency heal then waited for the last aura's cast and
|
||||
// he died. Then only health under Heal At held the buffs back.
|
||||
// 2026-11-20, DreamWeave Thread 0x5C47: a Virindi dispelled Robustify and Executor's Blessing in the
|
||||
// middle of a fight. RynthAi put his hand wraps away for the staff and cast them with a Rager on him and
|
||||
// five monsters in range, and he died 4 s later. The owner: "dispel makes sense... but i think we should
|
||||
// clear the mobs nearby before we rebuff". So in a fight (a monster within Monster Range, or health
|
||||
// falling: InCombatNow) no new buff cast starts, whatever the health; one already sent finishes. The
|
||||
// arbiter doesn't give Buffing the tick for buffs, so combat goes first, and the heals (a vital recharge
|
||||
// keeps its slot). A rebuff run under way stops between two casts and carries on once the fight is over.
|
||||
// The same for a dispelled buff and one at Rebuff With. A Force Rebuff the player asked for still goes in a
|
||||
// fight (their own ask), except under Heal At, as before.
|
||||
private bool _buffFightWaitOn; // a wait with buffs to cast was logged
|
||||
private DateTime _buffFightWaitSince = DateTime.MinValue;
|
||||
private DateTime _buffFightNeedCheckedAt = DateTime.MinValue;
|
||||
|
||||
/// <summary>True while health is under Heal At in a fight: no new buff cast. Logs the start and end of each wait.</summary>
|
||||
public bool BuffsWaitForHealth()
|
||||
/// <summary>True in a fight: no new buff cast. A Force Rebuff the player asked for waits only while health
|
||||
/// is under Heal At. Logs the start (when there are buffs to cast) and the end of each wait.</summary>
|
||||
public bool BuffsWaitForFight()
|
||||
{
|
||||
bool wait = _settings.HealAt > 0 && _vitals.HealthPct > 0 && _vitals.HealthPct < _settings.HealAt && InCombatNow();
|
||||
if (wait != _buffHurtWaitOn)
|
||||
bool fight = InCombatNow();
|
||||
bool hurt = _settings.HealAt > 0 && _vitals.HealthPct > 0 && _vitals.HealthPct < _settings.HealAt;
|
||||
bool playersOwn = _isForceRebuffing && !_isAutoBatchRebuff;
|
||||
bool wait = fight && (!playersOwn || hurt);
|
||||
DateTime now = RynthClock.Now;
|
||||
if (!wait)
|
||||
{
|
||||
_host.Log(wait
|
||||
? $"[Buff] buffs wait: health {_vitals.HealthPct}% is under Heal At {_settings.HealAt}% in a fight; heals and combat go first."
|
||||
: $"[Buff] buffs go on: health {_vitals.HealthPct}%, {(InCombatNow() ? "back over Heal At" : "the fight is over")}.");
|
||||
_buffHurtWaitOn = wait;
|
||||
if (_buffFightWaitOn)
|
||||
_host.Log($"[Buff] buffs go on: {(fight ? $"health {_vitals.HealthPct}%, back over Heal At, for the Force Rebuff you asked for" : "the fight is over")} (they waited {(now - _buffFightWaitSince).TotalSeconds:0} s).");
|
||||
_buffFightWaitOn = false;
|
||||
return false;
|
||||
}
|
||||
return wait;
|
||||
// Logged only when something is held back (a fight with every buff up isn't a wait); asked once a second.
|
||||
if (!_buffFightWaitOn && (now - _buffFightNeedCheckedAt).TotalMilliseconds >= 1000)
|
||||
{
|
||||
_buffFightNeedCheckedAt = now;
|
||||
if (NeedsAnyBuff())
|
||||
{
|
||||
_buffFightWaitOn = true;
|
||||
_buffFightWaitSince = now;
|
||||
_host.Log($"[Buff] buffs wait: {FightWhy(hurt)}; they go on once the fight is over (combat and the heals first).");
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private string FightWhy(bool hurt)
|
||||
{
|
||||
string why = InCombatOverride != null ? "a fight"
|
||||
: _combatManager?.HasCloseThreat(System.Math.Max(1, _settings.MonsterRange)) == true
|
||||
? $"a monster within Monster Range ({_settings.MonsterRange} yd)"
|
||||
: "health falling (something is hitting you)";
|
||||
return hurt ? $"{why}, health {_vitals.HealthPct}% under Heal At {_settings.HealAt}%" : why;
|
||||
}
|
||||
|
||||
// ── Rebuff When Idle (RebuffWhenIdle + RebuffIdleMarginMinutes; VTank's "idlebufftopoff") ──
|
||||
// The checkbox was saved and shown since the first version but nothing read it (a player asked,
|
||||
// 2026-10-30, whether "buff only when idle" was implemented). What it means (the owner): an earlier
|
||||
// timer for idle moments. The regular rebuff is unchanged: a buff at or under Rebuff With
|
||||
// (RebuffSecondsRemaining), or dispelled, is recast as always, in a fight or not. With the option
|
||||
// (RebuffSecondsRemaining), or dispelled, is recast as always, once a fight is over (BuffsWaitForFight,
|
||||
// since 2026-11-20; before that in a fight too). With the option
|
||||
// on and the bot idle (IdleForTopOff: no fight target, no monster within Monster Range, no corpse
|
||||
// to loot, no salvage), a rebuff run also starts once a buff is at or under Rebuff With plus the
|
||||
// margin (default 2 minutes). Such an early run never starts in a fight, and one under way stops
|
||||
|
|
@ -1266,11 +1304,29 @@ public partial class BuffManager : IDisposable
|
|||
value = 0;
|
||||
if (_settings.EmergencyHealAt > 0 && hp <= _settings.EmergencyHealAt) { value = _settings.EmergencyHealAt; return "Emergency Heal At"; }
|
||||
if (StaminaToHealthAllowed(_settings, hp, stamPct)) { value = _settings.StaminaToHealthAt; return "Stamina To Health At"; }
|
||||
value = inCombat ? _settings.HealAt : _settings.TopOffHP;
|
||||
if (hp < value) return inCombat ? "Heal At" : "Top Off HP";
|
||||
bool fightLines = FightHealthLine(inCombat);
|
||||
value = fightLines ? _settings.HealAt : _settings.TopOffHP;
|
||||
if (hp < value) return fightLines ? "Heal At" : "Top Off HP";
|
||||
return "";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The vital lines a fight uses (Heal At, Re-stam At, Get Mana At) apply during a buff run too, not
|
||||
/// only with a monster in range: the Top Off lines are for between fights and buff runs, and the
|
||||
/// top-off follows the run (R-20261120-181322-b31b, 2026.11.19.1). With Top Mana 95 and Get Mana
|
||||
/// At 20 a run cast Stamina to Mana ten times at 77-100% mana, then kits to win the stamina back.
|
||||
/// </summary>
|
||||
private bool UseFightVitalLines(bool inCombat) => inCombat || _isForceRebuffing;
|
||||
|
||||
/// <summary>
|
||||
/// Heal At (the fight line) or Top Off HP for health. The fight line is for a fight RynthAi is
|
||||
/// fighting (and a buff run, UseFightVitalLines): with Combat off nothing of ours fights back, so a
|
||||
/// monster near or hitting must not lower the line. Top Off HP applies then (2026-11-22: Combat off,
|
||||
/// Heal At 0, a monster hitting; every hit made it "a fight", Heal At 0 healed nothing, and the
|
||||
/// character stood until it died).
|
||||
/// </summary>
|
||||
private bool FightHealthLine(bool inCombat) => UseFightVitalLines(inCombat && _settings.EnableCombat);
|
||||
|
||||
// ── What the activity display says while the arbiter's slot is "Buffing" ──
|
||||
// BotAction stays "Buffing" for every vitals job: it is a control string (CombatManager's
|
||||
// canRun and CorpseOpenController read it). The dashboard and the phone showed it as is, so a
|
||||
|
|
@ -1407,6 +1463,7 @@ public partial class BuffManager : IDisposable
|
|||
string line = ActiveHealLine(_vitals.HealthPct, _vitals.StaminaPct, out int lineValue, out bool inCombat);
|
||||
_healLatency.Observe(Now, _vitals.HealthPct, line, lineValue, inCombat, HealInFlight());
|
||||
}
|
||||
else if (!_settings.IsMacroRunning) _healLatency.MacroOff(Now, _vitals.HealthPct); // no episode spans a stop
|
||||
try { HeartbeatCore(); }
|
||||
finally
|
||||
{
|
||||
|
|
@ -1464,6 +1521,7 @@ public partial class BuffManager : IDisposable
|
|||
PollCastTracker();
|
||||
ObserveBuffChain();
|
||||
_fastChainTick = false;
|
||||
_fastVitalTick = false;
|
||||
|
||||
// Heals failing at Emergency Heal At: break the cast, then recall (BuffManager.HpFailsafe.cs).
|
||||
TickHpFailsafe();
|
||||
|
|
@ -1792,8 +1850,14 @@ public partial class BuffManager : IDisposable
|
|||
// buff, the next buff skips the animation gate only (the pacer's gesture hold and the
|
||||
// engine's cast gate below). Every other gate stays.
|
||||
_fastChainTick = FastChainNow();
|
||||
if (!PacerAllows(out string paceWhy, gestureGate: !_fastChainTick))
|
||||
// The same for a vital cast after our own vital cast in the between-fights top-off (FastVitalChainNow).
|
||||
_fastVitalTick = !_fastChainTick && FastVitalChainNow();
|
||||
// A heal held by the character's animation past HealAnimationCapMs (all told, across the short
|
||||
// clear moments between hit recoils) skips the animation gates (BuffManager.HealAnimationCap.cs).
|
||||
bool healAnimCap = HealAnimationCapReached();
|
||||
if (!PacerAllows(out string paceWhy, gestureGate: !_fastChainTick && !_fastVitalTick && !healAnimCap))
|
||||
{
|
||||
NoteHealAnimationHold(IsAnimationHold(paceWhy));
|
||||
LastBuffSkipReason = "server answering the last action: " + paceWhy;
|
||||
Hold("server answering the last action", paceWhy);
|
||||
return;
|
||||
|
|
@ -1815,23 +1879,33 @@ public partial class BuffManager : IDisposable
|
|||
// NeedsAnyBuff and is the sole writer of the "Buffing" string.
|
||||
// A heal goes ahead of a busy count the server has already finished (BusyHoldsHeal);
|
||||
// everything else still waits for the count to drop.
|
||||
bool gateOpen = _fastChainTick || CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s));
|
||||
bool gateOpen = _fastChainTick || _fastVitalTick || healAnimCap || CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s));
|
||||
bool busyHolds = BusyCount > 0
|
||||
&& !_pacerLetHealAhead // the pacing let this heal go ahead of an unanswered corpse use (its rules)
|
||||
&& (ActiveHealLine(_vitals.HealthPct, _vitals.StaminaPct, out _, out _).Length == 0 || BusyHoldsHeal());
|
||||
if (!gateOpen || busyHolds)
|
||||
{
|
||||
NoteHealAnimationHold(!gateOpen);
|
||||
LastBuffSkipReason = busyHolds ? "busy (BusyCount>0)" : "cast gate closed (CanCastNow=false / gesture animating)";
|
||||
if (!gateOpen) Hold("cast gate (a gesture is animating)");
|
||||
else Hold("busy count", $"busy {BusyCount}");
|
||||
return;
|
||||
}
|
||||
|
||||
EndHealAnimationHold(); // the vitals step is reached: the heal is not held by the animation
|
||||
if (CheckVitals())
|
||||
{
|
||||
if (_healHold.Length == 0) Hold(_healWaitKind.Length > 0 ? _healWaitKind : "vitals step busy", _vitalWhy);
|
||||
return;
|
||||
}
|
||||
// The animation gate was skipped for a vital cast only: nothing else goes this tick, and the
|
||||
// next tick waits for the animation as usual (what goes then is no vital cast of this chain).
|
||||
if (_fastVitalTick)
|
||||
{
|
||||
_chain.HoldForAnimation();
|
||||
Hold("cast gate (a gesture is animating)");
|
||||
return;
|
||||
}
|
||||
|
||||
// /ra swaptest: the wand swap and one cast, timed (BuffManager.SwapTest.cs). After the vitals.
|
||||
if (TickSwapTest())
|
||||
|
|
@ -1877,8 +1951,9 @@ public partial class BuffManager : IDisposable
|
|||
if (manaFloor > 0 && _vitals.MaxMana > 0 && _vitals.ManaPct < manaFloor)
|
||||
{
|
||||
// The floor refills on its own: Stamina to Mana (or a potion) right here, then buffing
|
||||
// carries on. CheckVitals only refills below Top Off Mana out of combat, so a Top Off
|
||||
// Mana under Get Mana At left buffing waiting on natural regen - one buff every 1-2
|
||||
// carries on. CheckVitals refilled only below Top Off Mana out of combat (a buff run uses
|
||||
// Get Mana At there too since 2026-11-20), so a Top Off Mana under Get Mana At left
|
||||
// buffing waiting on natural regen - one buff every 1-2
|
||||
// minutes (tester, 10-01: 85 minutes of "buffing waits", Stamina to Mana never cast).
|
||||
// A low stamina is topped up first (kit, Revitalize, potion) so Stamina to Mana can run.
|
||||
// Each source's reason, for the log line below: it used to show only the last one tried
|
||||
|
|
@ -1986,8 +2061,8 @@ public partial class BuffManager : IDisposable
|
|||
|
||||
if (_settings.EnableBuffing)
|
||||
{
|
||||
if (BuffsWaitForHealth())
|
||||
return; // hurt in a fight: no new buff cast (a run in progress resumes after)
|
||||
if (BuffsWaitForFight())
|
||||
return; // in a fight: no new buff cast (a run in progress resumes after)
|
||||
if (CheckAndCastSelfBuffs())
|
||||
return;
|
||||
|
||||
|
|
@ -2161,10 +2236,14 @@ public partial class BuffManager : IDisposable
|
|||
// Otherwise idle → top up to the HIGH (TopOffHP / TopOffStam /
|
||||
// TopOffMana) thresholds so we re-engage at full. Thresholds are
|
||||
// strict "<": set a value to 0 to disable that vital in that mode.
|
||||
// A buff run uses the fight's lines too (UseFightVitalLines); the top-off comes after it.
|
||||
bool inCombat = InCombatNow();
|
||||
int hpThreshold = inCombat ? _settings.HealAt : _settings.TopOffHP;
|
||||
int manaThreshold = inCombat ? _settings.GetManaAt : _settings.TopOffMana;
|
||||
int stamThreshold = StaminaLine(inCombat, curStamPct, _settings, ref _restamRun, ref _restamRunCasts);
|
||||
bool fightLines = UseFightVitalLines(inCombat);
|
||||
bool fightHpLine = FightHealthLine(inCombat); // Combat off: Top Off HP even while hit
|
||||
int hpThreshold = fightHpLine ? _settings.HealAt : _settings.TopOffHP;
|
||||
if (fightHpLine) WarnNoFightHealLine(curHealthPct);
|
||||
int manaThreshold = fightLines ? _settings.GetManaAt : _settings.TopOffMana;
|
||||
int stamThreshold = StaminaLine(fightLines, curStamPct, _settings, ref _restamRun, ref _restamRunCasts);
|
||||
|
||||
// A flag is set only when something was actually done about the vital.
|
||||
// WantsVitalRecharge holds the arbiter on Buffing, above combat and nav, so
|
||||
|
|
@ -2192,10 +2271,10 @@ public partial class BuffManager : IDisposable
|
|||
}
|
||||
_healUnavailableUntil = RynthClock.Now.AddMilliseconds(HealUnavailableMs);
|
||||
Hold("nothing could heal", $"kit: {Why(kitWhy)}; Heal Self: {Why(spellWhy)}; potion: {Why(potionWhy)}");
|
||||
LogNoHeal($"health {curHealthPct}% < {(inCombat ? "Heal At" : "Top Off HP")} {hpThreshold}% but nothing healed: " +
|
||||
LogNoHeal($"health {curHealthPct}% < {(fightHpLine ? "Heal At" : "Top Off HP")} {hpThreshold}% but nothing healed: " +
|
||||
$"kit: {Why(kitWhy)}; Heal Self: {Why(spellWhy)}; potion: {Why(potionWhy)}");
|
||||
}
|
||||
else if (!inCombat && curHealthPct < _settings.HealAt)
|
||||
else if (!fightLines && curHealthPct < _settings.HealAt)
|
||||
{
|
||||
LogNoHeal($"health {curHealthPct}% < Heal At {_settings.HealAt}% but no monster within MonsterRange " +
|
||||
$"{_settings.MonsterRange} yd, so the idle Top Off HP {hpThreshold}% applies");
|
||||
|
|
@ -2208,7 +2287,7 @@ public partial class BuffManager : IDisposable
|
|||
|
||||
// Mana: under Get Mana At / Top Off Mana, or (a caster) under the reserve kept for Stamina
|
||||
// to Mana (ManaUnderLine; see "Mana reserve" at the top).
|
||||
bool manaLow = curManaPct < manaThreshold || ManaUnderLine(inCombat, out _);
|
||||
bool manaLow = curManaPct < manaThreshold || ManaUnderLine(fightLines, out _);
|
||||
if (manaLow)
|
||||
{
|
||||
// Stamina too low for Stamina to Mana: the refill starts with a stamina use, so a falling
|
||||
|
|
@ -2285,6 +2364,31 @@ public partial class BuffManager : IDisposable
|
|||
}
|
||||
|
||||
private DateTime _staminaNoSwapLoggedAt = DateTime.MinValue;
|
||||
private DateTime _noFightLineLoggedAt = DateTime.MinValue;
|
||||
private DateTime _noFightLineChatAt = DateTime.MinValue;
|
||||
|
||||
/// <summary>
|
||||
/// Heal At 0 switches healing off in a fight; with Emergency Heal At and Stamina To Health At 0 as
|
||||
/// well, nothing heals in a fight at any health (2026-11-22: eight deaths in a row with no heal sent
|
||||
/// in the minutes before each, Heal At and Emergency Heal At both 0). Said in the log (each minute)
|
||||
/// and in chat (each 5 minutes) while health is under Top Off HP in a fight; nothing else changes.
|
||||
/// </summary>
|
||||
private void WarnNoFightHealLine(int hp)
|
||||
{
|
||||
if (_settings.HealAt > 0 || _settings.EmergencyHealAt > 0 || _settings.StaminaToHealthAt > 0) return;
|
||||
if (hp <= 0 || hp >= Math.Max(1, _settings.TopOffHP)) return;
|
||||
var now = RynthClock.Now;
|
||||
if ((now - _noFightLineLoggedAt).TotalSeconds < 60) return;
|
||||
_noFightLineLoggedAt = now;
|
||||
string text = $"health {hp}% in a fight and no heal line covers fights (Heal At 0, Emergency Heal At 0, " +
|
||||
$"Stamina To Health At 0): nothing heals until the fight ends. Set Heal At or Emergency Heal At (Advanced settings, Recharge).";
|
||||
_host.Log("[RynthAi] Vitals: " + text);
|
||||
if ((now - _noFightLineChatAt).TotalMinutes >= 5)
|
||||
{
|
||||
_noFightLineChatAt = now;
|
||||
_host.WriteToChat("[RynthAi] " + char.ToUpperInvariant(text[0]) + text[1..], 2);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The heal chain of the vitals step (CheckVitals, and the one-touch heal): a kit, Heal Self and a
|
||||
|
|
@ -2586,14 +2690,23 @@ public partial class BuffManager : IDisposable
|
|||
_pendingVitalSpellId = spellId; // instant: confirmed by chat, never by the registry
|
||||
_pendingVitalLabel = label;
|
||||
_pendingVitalBase = what;
|
||||
bool castOk = _host.CastSpellFor(targetId, spellId, "Buff",
|
||||
SpellTableStub.GetById(spellId)?.Name ?? what);
|
||||
string castName = SpellTableStub.GetById(spellId)?.Name ?? what;
|
||||
bool fast = _fastVitalTick;
|
||||
if (fast)
|
||||
_host.Log($"[BuffChain] vital '{castName}' goes without waiting for the animation: {_fastChainWhy}");
|
||||
// Recorded for the vital fast path only out of a fight: in one, the chain's state stays as it was.
|
||||
bool chainIt = !InCombatNow();
|
||||
int seqAtSend = UseDoneSeqNow();
|
||||
bool castOk = _host.CastSpellFor(targetId, spellId, "Buff", castName);
|
||||
_lastCastAttempt = RynthClock.Now;
|
||||
if (!castOk)
|
||||
{
|
||||
_pendingSpellId = 0;
|
||||
if (chainIt) _chain.VitalClientRefused(spellId, castName, fast, Now, s => _host.Log(s));
|
||||
return VitalNo($"the client refused the cast (spell {spellId})");
|
||||
}
|
||||
if (chainIt)
|
||||
_chain.SentVital(spellId, castName, seqAtSend, ActionPacer.Started, ActionPacer.AttacksSent, MoveAudit.MovementSends, fast);
|
||||
sent = true;
|
||||
_vitalActionsSent++;
|
||||
_lastVitalCastAt = RynthClock.Now;
|
||||
|
|
@ -2663,6 +2776,7 @@ public partial class BuffManager : IDisposable
|
|||
if (ConsumableLookup.Resolve(_worldObjectCache, rule) is not WorldObject potion) continue;
|
||||
if (IsKitName(potion.Name)) continue;
|
||||
if (Array.FindIndex(types, t => t.Equals(DrinkType(rule, potion), StringComparison.OrdinalIgnoreCase)) < 0) continue;
|
||||
if (_fastVitalTick) return FastTickItemWait("the potion");
|
||||
if (HeldCastBlocksItemUse(out string heldWhy)) return VitalNo(heldWhy);
|
||||
_host.Log($"[RynthAi] Vitals: drinking {rule.Name} ({rule.Type})" + (potion.Id != rule.Id ? " from a new stack." : "."));
|
||||
_host.UseFor(unchecked((uint)potion.Id), "Buff", $"vitals: drink {rule.Name} ({rule.Type}) from the Items list");
|
||||
|
|
@ -2680,6 +2794,7 @@ public partial class BuffManager : IDisposable
|
|||
string? kind = RynthCore.Plugin.RynthAi.LegacyUi.LegacyWeaponsUi.PotionType(wo);
|
||||
if (kind == null || Array.FindIndex(types, t => t.Equals(kind, StringComparison.OrdinalIgnoreCase)) < 0) continue;
|
||||
if (IsKitName(wo.Name)) continue;
|
||||
if (_fastVitalTick) return FastTickItemWait("the potion");
|
||||
if (HeldCastBlocksItemUse(out string heldWhy)) return VitalNo(heldWhy);
|
||||
_host.Log($"[RynthAi] Vitals: using {wo.Name} from the pack ({kind}).");
|
||||
_host.UseFor(unchecked((uint)wo.Id), "Buff", $"vitals: {kind} potion from the pack");
|
||||
|
|
@ -2774,6 +2889,7 @@ public partial class BuffManager : IDisposable
|
|||
uint missing = _vitals.MaxHealth > _vitals.CurrentHealth ? _vitals.MaxHealth - _vitals.CurrentHealth : 0;
|
||||
// Combat has the tick (BuffManager.HealHold.cs): no peace switch goes out, so the chance is the stance it is in.
|
||||
if (!ignoreMinSuccess && !KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits && !_vitalsNoPeaceSwitch, _settings.KitMinSuccessPct)) return VitalNo($"{kit.Name} under Kit Min Success %");
|
||||
if (_fastVitalTick) return FastTickItemWait("the healing kit");
|
||||
if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode && _vitalsNoPeaceSwitch)
|
||||
NoteHealHoldRefusal(peace: true, "the healing kit");
|
||||
if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode && !_vitalsNoPeaceSwitch)
|
||||
|
|
@ -2825,6 +2941,7 @@ public partial class BuffManager : IDisposable
|
|||
underMinSuccess = true;
|
||||
return false;
|
||||
}
|
||||
if (_fastVitalTick) return FastTickItemWait("the stamina kit");
|
||||
if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode && _vitalsNoPeaceSwitch)
|
||||
NoteHealHoldRefusal(peace: true, "the stamina kit");
|
||||
if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode && !_vitalsNoPeaceSwitch)
|
||||
|
|
@ -2867,22 +2984,35 @@ public partial class BuffManager : IDisposable
|
|||
private bool _kitSawAnimating; // the motion queue read busy since the send
|
||||
// 3.5 s: the longest healthy kit answer is 2.5 s (ActionPacer's time limits). Stamina kits share it.
|
||||
internal const double KitResultTimeoutMs = 3500;
|
||||
private const double KitLandGraceMs = 700;
|
||||
// A UseDone(0) for the kit with no line: how long to wait for a line after all.
|
||||
internal const double KitLandGraceMs = 700;
|
||||
// After the kit's result line (2026-11-20): the next kit waited KitLandGraceMs (700 ms) after every
|
||||
// line for the vitals to catch up, sized on 10-03 when the vitals were read every 30th tick (1-3 s).
|
||||
// Since 10-05 they are read every 100 ms (RynthAiPlugin.VitalsPollMs) from the engine's snapshot,
|
||||
// which ACE's vital update (sent before the line, Healer.DoHealing) has already reached when the
|
||||
// line arrives. The wait now ends as soon as the vitals show the healed amount the line names
|
||||
// (KitVitalsCaughtUp), or KitVitalsCatchUpMs after the line (a failed kit names none): 3 vitals reads.
|
||||
// Stamina kits chained 3.1 s apart in the logs (16:46:45.572 line, next kit 46.302); now ~2.5 s.
|
||||
internal const double KitVitalsCatchUpMs = 300;
|
||||
/// <summary>Kits let go with no result line (heal grace or the time limit) (tests, status).</summary>
|
||||
internal int KitRetries { get; private set; }
|
||||
// The kit's vital (health, or stamina for a stamina kit) when it went out, and what its line said it healed (0 = none named).
|
||||
private uint _kitVitalAtUse;
|
||||
private int _kitLineAmount;
|
||||
|
||||
internal enum KitWaitEnd { Waiting, Landed, Answered, NotTaken, TimedOut }
|
||||
|
||||
/// <summary>
|
||||
/// The kit wait, from what has been seen since the send (pure; a ms value below 0 = not seen): the
|
||||
/// result line plus KitLandGraceMs; the kit's UseDone(0) with no line plus KitLandGraceMs, with no
|
||||
/// motion playing; nothing at all from the server (<paramref name="serverTookIt"/> false) and no
|
||||
/// motion playing after ActionPacer.HealGraceMs; or KitResultTimeoutMs whatever happened.
|
||||
/// result line, then the vitals showing its heal (<paramref name="vitalsCaughtUp"/>) or KitVitalsCatchUpMs;
|
||||
/// the kit's UseDone(0) with no line plus KitLandGraceMs, with no motion playing; nothing at all from
|
||||
/// the server (<paramref name="serverTookIt"/> false) and no motion playing after ActionPacer.HealGraceMs;
|
||||
/// or KitResultTimeoutMs whatever happened.
|
||||
/// </summary>
|
||||
internal static KitWaitEnd KitWaitVerdict(double msSinceUse, double msSinceLanded, double msSinceAnswered,
|
||||
bool serverTookIt, bool animatingNow)
|
||||
bool serverTookIt, bool animatingNow, bool vitalsCaughtUp = false)
|
||||
{
|
||||
if (msSinceLanded >= 0) return msSinceLanded >= KitLandGraceMs ? KitWaitEnd.Landed : KitWaitEnd.Waiting;
|
||||
if (msSinceLanded >= 0) return vitalsCaughtUp || msSinceLanded >= KitVitalsCatchUpMs ? KitWaitEnd.Landed : KitWaitEnd.Waiting;
|
||||
if (msSinceAnswered >= KitLandGraceMs && !animatingNow) return KitWaitEnd.Answered;
|
||||
if (!serverTookIt && !animatingNow && msSinceUse >= ActionPacer.HealGraceMs) return KitWaitEnd.NotTaken;
|
||||
if (msSinceUse >= KitResultTimeoutMs) return KitWaitEnd.TimedOut;
|
||||
|
|
@ -2912,6 +3042,30 @@ public partial class BuffManager : IDisposable
|
|||
_kitSawAnimating = false;
|
||||
_kitIsStamina = stamina;
|
||||
_kitSeqAtUse = UseDoneSeqNow();
|
||||
_kitVitalAtUse = stamina ? _vitals.CurrentStamina : _vitals.CurrentHealth;
|
||||
_kitLineAmount = 0;
|
||||
}
|
||||
|
||||
private static readonly System.Text.RegularExpressions.Regex KitAmountRx =
|
||||
new(@"heal yourself for ([\d,]+) (health|stamina) point", System.Text.RegularExpressions.RegexOptions.CultureInvariant);
|
||||
|
||||
/// <summary>The amount a kit's result line says it healed ("You heal yourself for 52 Health points."), 0 if none.</summary>
|
||||
internal static int KitLineAmount(string lower)
|
||||
{
|
||||
var m = KitAmountRx.Match(lower);
|
||||
return m.Success && int.TryParse(m.Groups[1].Value.Replace(",", ""), out int n) ? n : 0;
|
||||
}
|
||||
|
||||
/// <summary>The vitals already show the heal the kit's line named: its vital at or over what it was
|
||||
/// at the use plus that amount (capped at the maximum). Nothing named (a failed kit): false.</summary>
|
||||
private bool KitVitalsCaughtUp()
|
||||
{
|
||||
if (_kitLandedAt == DateTime.MinValue || _kitLineAmount <= 0) return false;
|
||||
uint cur = _kitIsStamina ? _vitals.CurrentStamina : _vitals.CurrentHealth;
|
||||
uint max = _kitIsStamina ? _vitals.MaxStamina : _vitals.MaxHealth;
|
||||
if (max == 0) return false;
|
||||
uint want = Math.Min(max, _kitVitalAtUse + (uint)_kitLineAmount);
|
||||
return cur >= want;
|
||||
}
|
||||
|
||||
private bool MotionQueueBusy => _host.HasGetCastBusyState && !_host.CanCastNow;
|
||||
|
|
@ -2954,7 +3108,7 @@ public partial class BuffManager : IDisposable
|
|||
var end = KitWaitVerdict(sinceUse,
|
||||
_kitLandedAt != DateTime.MinValue ? (now - _kitLandedAt).TotalMilliseconds : -1,
|
||||
_kitAnsweredAt != DateTime.MinValue ? (now - _kitAnsweredAt).TotalMilliseconds : -1,
|
||||
KitServerTookIt(), MotionQueueBusy);
|
||||
KitServerTookIt(), MotionQueueBusy, KitVitalsCaughtUp());
|
||||
if (end == KitWaitEnd.Waiting) return true;
|
||||
if (end != KitWaitEnd.Landed)
|
||||
{
|
||||
|
|
@ -3026,6 +3180,17 @@ public partial class BuffManager : IDisposable
|
|||
/// <summary>Kit Min Success % with a melee or missile weapon out, when Kit Min Success is higher.</summary>
|
||||
internal const int WeaponOutKitMinPct = 30;
|
||||
|
||||
/// <summary>A vital spell now would need a wand swap first: a melee or missile stance, or out of Magic
|
||||
/// stance with a wand to swap to that is not in hand (peace with the weapon still wielded).</summary>
|
||||
private bool SpellNeedsWandSwap()
|
||||
{
|
||||
int mode = CurrentCombatMode;
|
||||
if (mode == CombatMode.Melee || mode == CombatMode.Missile) return true;
|
||||
if (mode == CombatMode.Magic) return false;
|
||||
int wand = FindWandInItems();
|
||||
return wand != 0 && !IsBuffWandWielded(wand);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when a kit may be used: <paramref name="minPct"/> (Kit Min Success % for healing kits,
|
||||
/// Stamina Kit Min Success % for stamina kits) is 0, or the kit's chance of working on
|
||||
|
|
@ -3040,7 +3205,9 @@ public partial class BuffManager : IDisposable
|
|||
// (2026-11-13): low stamina doesn't kill, and the bar hid Stamina Kit Min Success % (50 read
|
||||
// as 30, a 16% Greater Stamina Kit every 3 s).
|
||||
bool staminaKit = kitName.EndsWith("Stamina Kit", StringComparison.OrdinalIgnoreCase);
|
||||
if (!staminaKit && (CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile))
|
||||
// Peace with the weapon still in hand is the same swap (2026-11-22: a 53% kit skipped in peace
|
||||
// with hand wraps wielded; the wand swap, the stance and a fizzle took 9 s for one +115 heal).
|
||||
if (!staminaKit && SpellNeedsWandSwap())
|
||||
minPct = Math.Min(minPct, WeaponOutKitMinPct);
|
||||
if (minPct <= 0 || _charSkills == null) return true;
|
||||
|
||||
|
|
@ -3143,6 +3310,35 @@ public partial class BuffManager : IDisposable
|
|||
return ShieldBuffBelowThreshold(desiredBuffs, thresholdSec);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// How many buffs a rebuff with <paramref name="thresholdSec"/> as its line would cast: the character's own,
|
||||
/// the item spells (weapon auras, armor banes) and the shield's; a missing or dispelled one counts, a parked
|
||||
/// one doesn't (as AnyBuffBelowThreshold). -1 with buffing off. For scripts, through rabuffsdue[seconds]
|
||||
/// (2026-11-20): a script that reads only the character's enchantments, so before a Thread it never saw
|
||||
/// thirteen item spells with 14 minutes left, and RynthAi recast them in the Thread.
|
||||
/// </summary>
|
||||
public int CountBuffsDue(int thresholdSec)
|
||||
{
|
||||
if (!_settings.EnableBuffing) return -1;
|
||||
var desiredBuffs = BuildDynamicBuffList();
|
||||
int sec = Math.Max(0, thresholdSec);
|
||||
int due = 0;
|
||||
DateTime now = RynthClock.Now;
|
||||
foreach (string buffBaseName in desiredBuffs)
|
||||
{
|
||||
AcSkillType castSkill = SkillFor(buffBaseName);
|
||||
if (!IsSkillUsable(castSkill)) continue;
|
||||
int spellId = FindBestSpellId(buffBaseName, castSkill);
|
||||
if (spellId == 0) continue;
|
||||
int family = SpellTableStub.GetById(spellId)?.Family ?? 0;
|
||||
if (family != 0 && _buffFailCooldownUntil.TryGetValue(family, out DateTime coolUntil) && now < coolUntil)
|
||||
continue;
|
||||
if (!IsBuffActive(spellId, sec)) due++;
|
||||
}
|
||||
if (ShieldBuffBelowThreshold(desiredBuffs, sec)) due++;
|
||||
return due;
|
||||
}
|
||||
|
||||
// "[FR] skip ..." lines while a rebuff runs: the selector runs every tick (~30 ms), and a
|
||||
// parked buff logged on each one - 47,000 lines in 10 minutes on 2026-10-11, so the log
|
||||
// rotated every few minutes and held nothing from before. Once per buff and reason a minute.
|
||||
|
|
@ -4713,6 +4909,7 @@ public partial class BuffManager : IDisposable
|
|||
if (_kitUsedAt != DateTime.MinValue && _kitLandedAt == DateTime.MinValue && IsKitResultLine(lower))
|
||||
{
|
||||
_kitLandedAt = RynthClock.Now;
|
||||
_kitLineAmount = KitLineAmount(lower);
|
||||
NoteKitResultLine(text, lower); // "... is used up." naming it: kit picks skip it (BuffManager.KitUsedUp.cs)
|
||||
ClearKitRefusedStreaks(); // a kit landed: the refusal streaks end (BuffManager.VitalWandGate.cs)
|
||||
}
|
||||
|
|
@ -4781,6 +4978,8 @@ public partial class BuffManager : IDisposable
|
|||
_host.Log($"[BuffChat] PARKED pending={_pendingSpellId}{(PendingIsShield ? " (on the shield)" : "")} — AC too busy (cast gesture in progress); throttle kept, backing off before re-issue.");
|
||||
if (_pendingSpellId != _pendingVitalSpellId)
|
||||
_chain.TooBusyLine(_pendingSpellId, s => _host.Log(s));
|
||||
else
|
||||
_chain.TooBusyLineVital(_pendingSpellId, Now, s => _host.Log(s));
|
||||
}
|
||||
if (!pendingRunning) _pendingSpellId = 0;
|
||||
|
||||
|
|
@ -5144,6 +5343,35 @@ public partial class BuffManager : IDisposable
|
|||
_host.GetUseDoneSeq(), Now, out _fastChainWhy);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The vital fast path for this tick (BuffCastChain, "Vital casts in the between-fights top-off"):
|
||||
/// the setting and the pacing are on, the character is in Magic stance, no monster is within
|
||||
/// Monster Range and health isn't falling (InCombatNow: in a fight nothing changes), a vital is
|
||||
/// under a line (else the buff chain's own rules), no kit is in flight, no held stop, and the last
|
||||
/// action was our own vital cast answered by UseDone(0) moments ago. Only a vital cast rides it.
|
||||
/// </summary>
|
||||
private bool FastVitalChainNow()
|
||||
{
|
||||
if (!_settings.FastBuffChain || !ActionPacer.Enabled) return false;
|
||||
if (!_host.HasUseDoneSeq || CurrentCombatMode != CombatMode.Magic) return false;
|
||||
if (_vitals.MaxHealth == 0 || KitPending() || VitalsClearOfEveryLine()) return false;
|
||||
if (InCombatNow()) return false;
|
||||
if (MoveAudit.HasPendingStop) return false;
|
||||
bool hasLast = _host.TryGetLastUseDone(out int lastSeq, out uint lastErr);
|
||||
return _chain.EligibleVital(ActionPacer.Started, ActionPacer.AttacksSent, MoveAudit.MovementSends, hasLast, lastSeq, lastErr,
|
||||
_host.GetUseDoneSeq(), Now, out _fastChainWhy);
|
||||
}
|
||||
|
||||
/// <summary>A kit, potion or peace switch on a vital fast-path tick: not sent (the animation gate was
|
||||
/// skipped for a cast only); handled, so nothing else stands in for it, and it goes next tick.</summary>
|
||||
private bool FastTickItemWait(string what)
|
||||
{
|
||||
_chain.HoldForAnimation(); // no fast path again until the next cast: the kit goes once the animation ends
|
||||
_vitalWhy = $"{what} waits for the animation (this tick only lets a vital cast go)";
|
||||
_healWaitKind = "cast gate (a gesture is animating)";
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>True when health, stamina and mana are at or over every line the vitals step acts on
|
||||
/// (combat and idle, emergency included), and no kit or stamina run is in progress.</summary>
|
||||
private bool VitalsClearOfEveryLine()
|
||||
|
|
@ -5528,7 +5756,8 @@ public partial class BuffManager : IDisposable
|
|||
private bool HealIsUrgent(int hp, int stamPct)
|
||||
{
|
||||
string line = ActiveHealLine(hp, stamPct, out _, out bool inCombat);
|
||||
return line is "Emergency Heal At" or "Stamina To Health At" || (line == "Heal At" && inCombat);
|
||||
// Top Off HP while being hit with Combat off (FightHealthLine) is as urgent as Heal At in a fight.
|
||||
return line is "Emergency Heal At" or "Stamina To Health At" || (line is "Heal At" or "Top Off HP" && inCombat);
|
||||
}
|
||||
|
||||
private bool EnsureMagicMode(bool forBuff = false, bool urgentHeal = false)
|
||||
|
|
@ -5745,7 +5974,7 @@ public partial class BuffManager : IDisposable
|
|||
// one of these two branches fires per call — no same-tick wield/unwield race.
|
||||
if (wandId != 0 && IsWieldedLive(wandId))
|
||||
{
|
||||
int openPack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: 1);
|
||||
int openPack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: 1, new[] { wandId });
|
||||
if (openPack != 0) _host.MoveItemInternal((uint)wandId, (uint)openPack, 0, 1);
|
||||
}
|
||||
else if (bowId != 0 && !IsWieldedLive(bowId))
|
||||
|
|
@ -5838,7 +6067,7 @@ public partial class BuffManager : IDisposable
|
|||
|
||||
case HandSwapSequence.Act.MoveToPack:
|
||||
{
|
||||
int pack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: 1);
|
||||
int pack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: 1, new[] { step.Id });
|
||||
if (pack == 0)
|
||||
{
|
||||
WorldObjectCache.WarnPackFull(_host, "can't put the weapon away to switch to the wand, so buffs and spell heals can't cast");
|
||||
|
|
@ -5966,7 +6195,7 @@ public partial class BuffManager : IDisposable
|
|||
if ((now - _modeChangedAt).TotalMilliseconds < BurstQuietMs) return 0;
|
||||
var moves = _wandSwap.Blockers(hands);
|
||||
if (moves.Count == 0 || moves.Count > 2) return 0;
|
||||
int pack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: moves.Count);
|
||||
int pack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: moves.Count, moves);
|
||||
if (pack == 0) return 0;
|
||||
if (!_host.ChangeCombatModeFor(CombatMode.NonCombat, "Buff", "wand swap burst: peace, the hands and the wand at once")) return 1;
|
||||
foreach (int id in moves)
|
||||
|
|
|
|||
|
|
@ -324,6 +324,43 @@ public partial class CombatManager
|
|||
|
||||
private static string LabelOf(AmmoCandidate a) => a.Untyped ? "ammo" : MissileAmmo.Label(a.AmmoType);
|
||||
|
||||
// ── Ammo by element (R-20261121-163725-da49, 2026.11.19.1) ────────────────────────────────────
|
||||
// "Bows will swap correctly but not ammo": the ammo step chose a stack only for an empty slot or
|
||||
// ammo of another type, so after a bow-to-bow swap for a monster weak to Fire, the Cold arrows
|
||||
// the last bow shot stayed on. Now, with ammo the launcher can shoot already on, the stack
|
||||
// MissileAmmo.Choose would pick for this target is wielded instead when its element ranks
|
||||
// strictly better (the Monsters rule's damage type, then the target's weaknesses). Choose's own
|
||||
// order still comes first (the listed ammo, then infinite ammo), so this only moves between
|
||||
// stacks the player would be given anyway. At most one such swap per launcher every
|
||||
// AmmoElementSwapRestSec, so a target with two equal weaknesses can't flip it back and forth.
|
||||
internal const double AmmoElementSwapRestSec = 15;
|
||||
private readonly Dictionary<int, DateTime> _ammoElementSwapAt = new();
|
||||
|
||||
/// <summary>The stack to put on instead of <paramref name="wielded"/> for <paramref name="target"/>, or null.</summary>
|
||||
private AmmoCandidate? BetterAmmoFor(int launcherId, WorldObject wo, int lt, IReadOnlyList<AmmoCandidate> pack,
|
||||
AmmoCandidate wielded, WorldObject? target, MonsterRule? rule, DateTime now)
|
||||
{
|
||||
if (target == null || AmmoTracker.PendingId != 0 || _ammoDequipPendingId != 0) return null;
|
||||
if (_ammoElementSwapAt.TryGetValue(launcherId, out var last) && (now - last).TotalSeconds < AmmoElementSwapRestSec) return null;
|
||||
var rank = AmmoRank(RuleElementOf(rule), WeaknessFor(target));
|
||||
string launcherElement = LauncherElement(launcherId, wo);
|
||||
var usable = pack.Where(a => a.Id == wielded.Id || !AmmoTracker.Resting(a.Id, now)).ToList();
|
||||
var pick = MissileAmmo.Choose(lt, launcherElement, usable, rank);
|
||||
if (pick == null || pick.Id == wielded.Id) return null;
|
||||
if (rank(ElementOrPierce(pick, launcherElement)) >= rank(ElementOrPierce(wielded, launcherElement))) return null;
|
||||
_ammoElementSwapAt[launcherId] = now;
|
||||
_host.Log($"[EquipDiag] ammo by element: '{target.Name}' takes {ElementOrPierce(pick, launcherElement)} better than " +
|
||||
$"{ElementOrPierce(wielded, launcherElement)}: 0x{(uint)wielded.Id:X8} '{wielded.Name}' -> 0x{(uint)pick.Id:X8} '{pick.Name}' " +
|
||||
$"for 0x{(uint)launcherId:X8} '{wo.Name}'");
|
||||
return pick;
|
||||
}
|
||||
|
||||
private static string ElementOrPierce(AmmoCandidate a, string launcherElement)
|
||||
{
|
||||
string e = MissileAmmo.EffectiveElement(a, launcherElement);
|
||||
return e.Length > 0 ? e : "Pierce";
|
||||
}
|
||||
|
||||
private void ArmAmmoFollowUp(int launcherId, DateTime now)
|
||||
{
|
||||
if (_ammoFollowUpFor == launcherId && now < _ammoFollowUpUntil) return;
|
||||
|
|
@ -390,6 +427,14 @@ public partial class CombatManager
|
|||
EndAmmoFollowUp();
|
||||
ClearAmmoDequip();
|
||||
_noAmmoSaid.Remove(launcherId);
|
||||
// A stack with a better element for this target (CombatManager.Ammo.cs, "Ammo by element"):
|
||||
// this one goes into the pack, and the empty slot's step below wields that one.
|
||||
if (BetterAmmoFor(launcherId, wo, lt, pack, wielded, target, rule, now) is { } better)
|
||||
{
|
||||
var prep = PutAmmoAway(wielded, launcherId,
|
||||
$"for '{better.Name}' ({ElementOrPierce(better, LauncherElement(launcherId, wo))}, a better element for '{target.Name}')", now);
|
||||
if (prep != AmmoPrep.Blocked) return true; // the slot empties, then the better stack goes on
|
||||
}
|
||||
canShoot = true;
|
||||
return false;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,202 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - Combat/CombatManager.DebuffPass.cs
|
||||
// "Debuff every monster in range before attacking" (2026-11-22, setting
|
||||
// DebuffAllBeforeAttacking, off by default; /ra debuffall [on|off]). With
|
||||
// several monsters in Monster Range, each one's own debuffs (its Monsters
|
||||
// rule: Imperil, vulns, Void debuffs, typed-in ones) are cast on all of them,
|
||||
// nearest first, before anything is attacked, so pets and the attack spells
|
||||
// that follow land on debuffed monsters. The order and the caps are
|
||||
// DebuffPass's (pure, tested); this file feeds it the scan, casts what it
|
||||
// picks and holds the pet summon while the pass runs.
|
||||
//
|
||||
// Debuffs go out through the same cast path as the fight target's own: one
|
||||
// at a time, its result read from chat (landed, resisted, fizzled, refused).
|
||||
// Melee and missile with a weapon in hand cast no debuffs at all (the wand
|
||||
// swap doesn't work there), so the pass doesn't run in those modes.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
public partial class CombatManager
|
||||
{
|
||||
private DebuffPass? _passState;
|
||||
private readonly List<int> _passCandidates = new();
|
||||
private readonly List<int> _passInRange = new();
|
||||
private bool _pendingDebuffFromPass;
|
||||
private bool _petHoldLogged;
|
||||
|
||||
// A monster's melee hits on the character, by name (the hit lines name it, not its object).
|
||||
private readonly Dictionary<string, DateTime> _hitOnMeAt = new(StringComparer.OrdinalIgnoreCase);
|
||||
/// <summary>A monster this close that hit the character this recently is "on you".</summary>
|
||||
internal const double OnYouYards = 6.0;
|
||||
internal const double OnYouSeconds = 4.0;
|
||||
|
||||
/// <summary>The pass's state (tests read it).</summary>
|
||||
internal DebuffPass DebuffPassState => _passState ??= new DebuffPass
|
||||
{
|
||||
Log = s => _host.Log(s),
|
||||
NameOf = id => _worldFilter[id]?.Name ?? "",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The pet summon waits while the first pass runs (PetManager), so the pet's first hits land on
|
||||
/// debuffed monsters. Bounded by the pass's time cap; never while a monster is on you.
|
||||
/// </summary>
|
||||
internal bool DebuffPassHoldsPets
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!_settings.DebuffAllBeforeAttacking || !_settings.EnableCombat || _passState == null) return false;
|
||||
bool hold = _passState.Holding(RynthClock.Now);
|
||||
// Before the fight's first cast: only when the pass can run (no melee or missile weapon
|
||||
// out, nothing hitting you) and some monster in range has a debuff to get.
|
||||
if (hold && _passState.Phase == DebuffPass.Stage.Idle)
|
||||
{
|
||||
int mode = CurrentCombatMode;
|
||||
hold = mode != CombatMode.Melee && mode != CombatMode.Missile && !MonsterOnYou() && AnyInRangeNeedsDebuff();
|
||||
}
|
||||
if (hold && !_petHoldLogged) _host.Log("[DebuffPass] the pet summon waits for the debuff pass");
|
||||
_petHoldLogged = hold;
|
||||
return hold;
|
||||
}
|
||||
}
|
||||
|
||||
private bool AnyInRangeNeedsDebuff()
|
||||
{
|
||||
FillPassCandidates();
|
||||
for (int i = 0; i < _passCandidates.Count; i++)
|
||||
if (PassDebuffFor(_passCandidates[i], out _, out _, out _, out _)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private void FillPassCandidates()
|
||||
{
|
||||
_passCandidates.Clear();
|
||||
double range = Math.Max(1, _settings.MonsterRange);
|
||||
for (int i = 0; i < _scannedTargets.Count; i++) // sorted nearest first
|
||||
if (_scannedTargets[i].Distance <= range) _passCandidates.Add(_scannedTargets[i].Id);
|
||||
}
|
||||
|
||||
/// <summary>AttackWithMagic, before the fight target's own debuffs: the fight's first cast begins the pass.</summary>
|
||||
private void BeginDebuffPass()
|
||||
{
|
||||
if (!_settings.DebuffAllBeforeAttacking || _spellManager == null) return;
|
||||
if (_passState != null && _passState.Phase != DebuffPass.Stage.Idle) return;
|
||||
FillPassCandidates();
|
||||
DebuffPassState.Begin(_passCandidates, RynthClock.Now);
|
||||
}
|
||||
|
||||
/// <summary>ScanNearbyTargets, after the sort: the pass sees who is in range.</summary>
|
||||
private void ObserveDebuffPass()
|
||||
{
|
||||
if (!_settings.DebuffAllBeforeAttacking)
|
||||
{
|
||||
if (_passState != null && _passState.Phase != DebuffPass.Stage.Idle) _passState.Reset();
|
||||
return;
|
||||
}
|
||||
_passInRange.Clear();
|
||||
double range = Math.Max(1, _settings.MonsterRange);
|
||||
for (int i = 0; i < _scannedTargets.Count; i++)
|
||||
if (_scannedTargets[i].Distance <= range) _passInRange.Add(_scannedTargets[i].Id);
|
||||
DebuffPassState.Observe(_passInRange, activeTargetId != 0, RynthClock.Now);
|
||||
}
|
||||
|
||||
/// <summary>LearnFromCombatChat: a monster's hit on the character.</summary>
|
||||
private void NoteHitOnMe(string name)
|
||||
{
|
||||
if (string.IsNullOrEmpty(name)) return;
|
||||
if (_hitOnMeAt.Count >= 64 && !_hitOnMeAt.ContainsKey(name)) _hitOnMeAt.Clear();
|
||||
_hitOnMeAt[name] = RynthClock.Now;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A monster is hitting the character in melee: one within <see cref="OnYouYards"/> whose name
|
||||
/// hit us in the last <see cref="OnYouSeconds"/>.
|
||||
/// </summary>
|
||||
internal bool MonsterOnYou()
|
||||
{
|
||||
if (_hitOnMeAt.Count == 0) return false;
|
||||
DateTime now = RynthClock.Now;
|
||||
for (int i = 0; i < _scannedTargets.Count; i++)
|
||||
{
|
||||
var t = _scannedTargets[i];
|
||||
if (t.Distance > OnYouYards) continue;
|
||||
string name = t.Name ?? _worldFilter[t.Id]?.Name ?? "";
|
||||
if (name.Length > 0 && _hitOnMeAt.TryGetValue(name, out DateTime at) && (now - at).TotalSeconds <= OnYouSeconds)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Tests: a hit line from <paramref name="name"/> just now.</summary>
|
||||
internal void NoteHitOnMeForTests(string name) => NoteHitOnMe(name);
|
||||
|
||||
/// <summary>The rule's next debuff for this monster (not on it, castable), or false.</summary>
|
||||
private bool PassDebuffFor(int id, out string key, out int spellId, out int tier, out bool renewal)
|
||||
{
|
||||
key = ""; spellId = 0; tier = 0; renewal = false;
|
||||
if (!IsLiveMonster(id)) return false;
|
||||
if (_host.HasObjectIsAttackable && !_host.ObjectIsAttackable((uint)id)) return false;
|
||||
var wo = _worldFilter[id];
|
||||
if (wo == null) return false;
|
||||
var rule = GetRuleForTarget(wo);
|
||||
if (rule == null) return false;
|
||||
string element = GetPreferredElement(wo, rule);
|
||||
return NextDebuffFor(id, rule, element, RynthClock.Now, out key, out spellId, out tier, out renewal);
|
||||
}
|
||||
|
||||
/// <summary>The monster the pass would debuff now, or 0 (attack). Setting off: 0.</summary>
|
||||
private int PassPick()
|
||||
{
|
||||
if (!_settings.DebuffAllBeforeAttacking || _spellManager == null) return 0;
|
||||
FillPassCandidates();
|
||||
return DebuffPassState.Next(_passCandidates, activeTargetId,
|
||||
id => PassDebuffFor(id, out _, out _, out _, out _), MonsterOnYou(), RynthClock.Now);
|
||||
}
|
||||
|
||||
/// <summary>The pass has a debuff to cast before the next attack.</summary>
|
||||
private bool PassWantsDebuff() => PassPick() != 0;
|
||||
|
||||
/// <summary>
|
||||
/// AttackWithMagic, after the fight target's own debuffs: cast the pass's next debuff (at another
|
||||
/// monster) instead of attacking. True when a debuff went out or it waits for mana.
|
||||
/// </summary>
|
||||
private bool TryDebuffPassCast()
|
||||
{
|
||||
int id = PassPick();
|
||||
if (id == 0) return false;
|
||||
if (!PassDebuffFor(id, out string key, out int spellId, out int tier, out bool renewal)) return false;
|
||||
if (ManaHoldsCast(spellId)) return true; // mana reserve: Stamina to Mana first, or regenerate
|
||||
var wo = _worldFilter[id];
|
||||
double dist = DistanceInScan(id);
|
||||
_host.Log($"[DebuffPass] {(renewal ? "renewing" : "casting")} {key} (T{tier}) on 0x{(uint)id:X8} '{wo?.Name}' at {dist:0.0} yd" +
|
||||
(DebuffPassState.Phase == DebuffPass.Stage.Attacking ? " (came into range mid-fight)" : "") +
|
||||
$", the fight target 0x{(uint)activeTargetId:X8} waits");
|
||||
if (!CastDebuffAt(id, wo?.Name ?? "", key, spellId, tier, renewal)) return false;
|
||||
_pendingDebuffFromPass = true;
|
||||
DebuffPassState.NoteCast(id, RynthClock.Now);
|
||||
LastCombatSkipReason = "debuff-pass"; // D4 record-only
|
||||
return true;
|
||||
}
|
||||
|
||||
private double DistanceInScan(int id)
|
||||
{
|
||||
for (int i = 0; i < _scannedTargets.Count; i++)
|
||||
if (_scannedTargets[i].Id == id) return _scannedTargets[i].Distance;
|
||||
return double.NaN;
|
||||
}
|
||||
|
||||
/// <summary>An attack went out at the fight target: an arrival may get the next debuff.</summary>
|
||||
private void NotePassAttack() => _passState?.NoteAttack();
|
||||
|
||||
/// <summary>The pending debuff's result: the pass counts failures on its own monsters.</summary>
|
||||
private void NotePassDebuffResult(bool failed)
|
||||
{
|
||||
if (!_pendingDebuffFromPass) return;
|
||||
_pendingDebuffFromPass = false;
|
||||
if (failed) _passState?.NoteFailed(_pendingDebuffTargetId);
|
||||
}
|
||||
}
|
||||
|
|
@ -337,7 +337,7 @@ public partial class CombatManager
|
|||
_host.Log($"[EquipDiag] off hand 0x{(uint)offId:X8} '{name}' didn't come off after {OffDequipMaxTries} tries — leaving the hands as they are for 2 min");
|
||||
return OffPrep.Blocked;
|
||||
}
|
||||
int packId = OpenPackOverride?.Invoke() ?? WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: 1);
|
||||
int packId = OpenPackOverride?.Invoke() ?? WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: 1, new[] { offId });
|
||||
if (packId == 0 || !_host.HasMoveItemInternal)
|
||||
{
|
||||
if (packId == 0) WorldObjectCache.WarnPackFull(_host, "can't put the shield away to change weapons");
|
||||
|
|
|
|||
|
|
@ -50,6 +50,7 @@ public partial class CombatManager
|
|||
internal const double PassedOverBeyondRangeM = 15.0;
|
||||
|
||||
internal const string PassedOverLos = "line of sight blocked";
|
||||
internal const string PassedOverWindow = "in a building (or outside it) seen through a window: melee goes in by a door";
|
||||
internal const string PassedOverOtherLevel = "too far above or below for melee";
|
||||
internal const string PassedOverBlacklisted = "blacklisted";
|
||||
internal const string PassedOverNeverAttack = "on the never-attack list";
|
||||
|
|
|
|||
|
|
@ -309,11 +309,19 @@ public partial class CombatManager : IDisposable
|
|||
/// <summary>
|
||||
/// True = don't lock a new target yet. RynthAi answers true with Boost Loot Priority on while
|
||||
/// our kill's corpse forms or is looted (RynthAiPlugin.BoostLootHoldsNewTarget): one kill, one
|
||||
/// loot. A monster within CloseAttackYards is still fought at once. Null = never hold.
|
||||
/// loot. A monster within CloseAttackYards, or one in the scan hitting us, is still fought at
|
||||
/// once. Null = never hold.
|
||||
/// </summary>
|
||||
public Func<bool>? HoldNewTarget { get; set; }
|
||||
/// <summary>Why HoldNewTarget holds, for its one log line (null: Boost Loot Priority's words).</summary>
|
||||
public Func<string>? HoldNewTargetWhy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// True = leave this monster (its id) out of the scan. The hunt fence answers true for a monster
|
||||
/// outside its circle (RynthAiPlugin.FenceSkipsTarget). The target being fought and a forced one
|
||||
/// are never asked. Null = never skip.
|
||||
/// </summary>
|
||||
public Func<int, bool>? SkipTarget { get; set; }
|
||||
private bool _newTargetHeldLogged;
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -901,16 +909,95 @@ public partial class CombatManager : IDisposable
|
|||
/// scan always runs and has no side effects, so a close-range scanned mob
|
||||
/// is the non-circular signal.
|
||||
/// </summary>
|
||||
public bool IsUnderCloseAttack => IsActivelyEngaged || HasCloseThreat(CloseAttackYards);
|
||||
public bool IsUnderCloseAttack => IsActivelyEngaged || HasCloseThreat(CloseAttackYards) || IsBeingHitByScanned;
|
||||
|
||||
/// <summary>
|
||||
/// HoldNewTarget says wait (Boost Loot Priority, a kill's corpse to loot) and no monster is
|
||||
/// within CloseAttackYards. One log line per hold.
|
||||
/// A monster in the scan (inside Monster Range, in sight, attackable) hit us, or swung and
|
||||
/// missed, within HitTakenRecentMs (2026-11-22). "On top of me" was distance only: a monster
|
||||
/// beyond CloseAttackYards that is hitting the character (an archer, a caster, a big monster
|
||||
/// whose middle stands more than 5 yd off) counted as no fight, so with Boost Loot Priority the
|
||||
/// looter kept the tick and combat locked nothing while it hit (#rynthsuite 11-15: "a mob
|
||||
/// spawns and approaches me ... I just stand there and take hits"). A hit line names the monster,
|
||||
/// not its object: any scanned monster of that name counts. No side effects (the arbiter's path).
|
||||
/// </summary>
|
||||
public bool IsBeingHitByScanned
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_hitTakenAt.Count == 0 || _scannedTargets.Count == 0) return false;
|
||||
DateTime now = TargetClock();
|
||||
for (int i = 0; i < _scannedTargets.Count; i++)
|
||||
{
|
||||
string? name = _scannedTargets[i].Name;
|
||||
if (!string.IsNullOrEmpty(name) && _hitTakenAt.TryGetValue(name, out DateTime at)
|
||||
&& (now - at).TotalMilliseconds <= HitTakenRecentMs)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A monster's hit or miss on us counts as "on me" this long (a swing every 1-3 s; a
|
||||
/// bow or a spell a little slower).</summary>
|
||||
internal const double HitTakenRecentMs = 4000;
|
||||
|
||||
// Monster name -> when its last hit or miss on us came (NoteHitTaken). Names are the hit lines'.
|
||||
private readonly Dictionary<string, DateTime> _hitTakenAt = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
// "You evaded Olthoi Warrior!": the monster swung at us and missed.
|
||||
private static readonly System.Text.RegularExpressions.Regex EvadedIncoming = new(
|
||||
@"^You evaded (?:the )?(?<name>.+?)!",
|
||||
System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.CultureInvariant);
|
||||
|
||||
/// <summary>A combat chat line: a monster's hit on us ("X slashes your leg for N points of ...")
|
||||
/// or its miss ("You evaded X!") is noted for <see cref="IsBeingHitByScanned"/>.</summary>
|
||||
internal void NoteHitTaken(string text)
|
||||
{
|
||||
string? name = null;
|
||||
if (text.StartsWith("You ", StringComparison.Ordinal))
|
||||
{
|
||||
var e = EvadedIncoming.Match(text);
|
||||
if (e.Success) name = e.Groups["name"].Value.Trim();
|
||||
}
|
||||
else
|
||||
{
|
||||
var m = IncomingDamage.Match(text);
|
||||
if (m.Success) name = m.Groups["name"].Value.Trim();
|
||||
}
|
||||
if (string.IsNullOrEmpty(name)) return;
|
||||
DateTime now = TargetClock();
|
||||
if (_hitTakenAt.Count >= 64)
|
||||
{
|
||||
_hitTakenPruneScratch.Clear();
|
||||
foreach (var kv in _hitTakenAt)
|
||||
if ((now - kv.Value).TotalMilliseconds > HitTakenRecentMs) _hitTakenPruneScratch.Add(kv.Key);
|
||||
foreach (string k in _hitTakenPruneScratch) _hitTakenAt.Remove(k);
|
||||
}
|
||||
_hitTakenAt[name] = now;
|
||||
}
|
||||
private readonly List<string> _hitTakenPruneScratch = new();
|
||||
|
||||
/// <summary>
|
||||
/// Boost Loot Priority's "corpses first" (2026-11-22, RynthAiPlugin.BoostLootFirst.cs): true while the
|
||||
/// hold below applies with a monster within CloseAttackYards too. Null or false: the old rule (a close
|
||||
/// monster is fought at once).
|
||||
/// </summary>
|
||||
public Func<bool>? HoldNewTargetThroughThreat { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// HoldNewTarget says wait (Boost Loot Priority, a kill's corpse to loot), no monster is
|
||||
/// within CloseAttackYards and none in the scan is hitting us (IsBeingHitByScanned). One log
|
||||
/// line per hold.
|
||||
/// HoldNewTargetThroughThreat (Boost Loot Priority, corpses first) holds it through both.
|
||||
/// </summary>
|
||||
private bool NewTargetHeldForLoot()
|
||||
{
|
||||
bool held;
|
||||
try { held = HoldNewTarget?.Invoke() == true && !HasCloseThreat(CloseAttackYards); }
|
||||
try
|
||||
{
|
||||
held = HoldNewTarget?.Invoke() == true
|
||||
&& ((!HasCloseThreat(CloseAttackYards) && !IsBeingHitByScanned) || HoldNewTargetThroughThreat?.Invoke() == true);
|
||||
}
|
||||
catch { held = false; }
|
||||
if (!held)
|
||||
{
|
||||
|
|
@ -1198,6 +1285,9 @@ public partial class CombatManager : IDisposable
|
|||
_beyondRange.Add(new PassedOverMonster { Id = wo.Id, Distance = dist, Why = "" });
|
||||
continue;
|
||||
}
|
||||
// The hunt fence (RynthAiPlugin.HuntFence.cs): a monster outside it is left alone. The one
|
||||
// being fought is kept.
|
||||
if (!isEngaged && !isForced && SkipTarget != null && SkipTarget(wo.Id)) continue;
|
||||
// Left out below for a reason that can hide a monster worth fighting: noted for the
|
||||
// lock line's "passed over" (CombatManager.PassedOver.cs). In range, not the target.
|
||||
bool notePassed = !isEngaged && dist <= maxDist;
|
||||
|
|
@ -1303,6 +1393,17 @@ public partial class CombatManager : IDisposable
|
|||
losBlocked = false;
|
||||
}
|
||||
|
||||
// Through a window (2026-11-17: "it tries to run through windows as if they are openings"): one of
|
||||
// the two in a building's rooms and the other outside, the line clear (a window, an opening the raycast
|
||||
// sees through) and farther than melee reaches across a doorway: melee ran straight at the wall under the
|
||||
// window. Left to the hunt, which walks in by a door; not counted as out of sight (the walk isn't held).
|
||||
if (!losBlocked && hasPlayerPos && dist > MeleeAcrossDoorwayM && MeleeIsTheAttackOn(wo, attackType)
|
||||
&& AcrossBuildingWall(meCell, (uint)wo.Id))
|
||||
{
|
||||
if (notePassed) NotePassedOver(wo.Id, dist, PassedOverWindow);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Don't blacklist from scan — just exclude from this result.
|
||||
// Blacklisting only happens when an active target fails LOS during attack.
|
||||
if (losBlocked)
|
||||
|
|
@ -1342,6 +1443,8 @@ public partial class CombatManager : IDisposable
|
|||
LastScanInRing = scanRing;
|
||||
LastScanPossible = _scannedTargets.Count;
|
||||
LastScanLosBlocked = _nearbyNoLos;
|
||||
|
||||
ObserveDebuffPass(); // who is in range, for "Debuff every monster in range before attacking"
|
||||
}
|
||||
|
||||
public CombatManager(RynthCoreHost host, LegacyUiSettings settings, WorldObjectCache worldFilter, SpellManager? spellManager = null)
|
||||
|
|
@ -1394,6 +1497,7 @@ public partial class CombatManager : IDisposable
|
|||
_pendingDebuffTargetId = 0;
|
||||
}
|
||||
_debuffs.Forget(id);
|
||||
_passState?.Forget(id);
|
||||
}
|
||||
public void SetPlayerId(uint playerId)
|
||||
{
|
||||
|
|
@ -1729,6 +1833,7 @@ public partial class CombatManager : IDisposable
|
|||
var m = IncomingDamage.Match(text);
|
||||
if (!m.Success) return;
|
||||
string name = m.Groups["name"].Value.Trim();
|
||||
NoteHitOnMe(name); // "on you" for the debuff pass
|
||||
uint src = WcidForName(name);
|
||||
if (src == 0) return;
|
||||
if (int.TryParse(m.Groups["n"].Value, out int amount))
|
||||
|
|
@ -1751,6 +1856,7 @@ public partial class CombatManager : IDisposable
|
|||
if (text.IndexOf(" evaded your attack", StringComparison.OrdinalIgnoreCase) > 0)
|
||||
NoteSwingEvidence("miss");
|
||||
NoteAttackReachedFromChat(text);
|
||||
try { NoteHitTaken(text); } catch { } // a monster hitting us is a fight (IsBeingHitByScanned)
|
||||
if (_damageStore == null) return;
|
||||
try { LearnFromCombatChat(text); } catch { }
|
||||
|
||||
|
|
@ -2125,6 +2231,7 @@ public partial class CombatManager : IDisposable
|
|||
/// </summary>
|
||||
private void NoteDebuffFailed(string what)
|
||||
{
|
||||
NotePassDebuffResult(failed: true); // the debuff pass's own count (CombatManager.DebuffPass.cs)
|
||||
if (_debuffs.Failed(_pendingDebuffTargetId, _pendingDebuffKey ?? "")) // skip it for this target
|
||||
{
|
||||
_host.WriteToChat($"[RynthAi] {what}: {_pendingDebuffKey} — {DebuffTimers.MaxFailures} tries on this target, skipping it", 2);
|
||||
|
|
@ -2145,6 +2252,7 @@ public partial class CombatManager : IDisposable
|
|||
/// </summary>
|
||||
private void NoteDebuffLanded()
|
||||
{
|
||||
NotePassDebuffResult(failed: false);
|
||||
int seconds = SpellDatabase.DurationSeconds(_pendingDebuffSpellId);
|
||||
_debuffs.Landed(_pendingDebuffTargetId, _pendingDebuffKey ?? "", seconds, RynthClock.Now);
|
||||
if (seconds > 0)
|
||||
|
|
@ -4215,7 +4323,8 @@ public partial class CombatManager : IDisposable
|
|||
{
|
||||
var rule2 = GetRuleForTarget(targetObj);
|
||||
string elem2 = GetPreferredElement(targetObj, rule2);
|
||||
if (rule2 != null && !HasPendingDebuffs(rule2, elem2))
|
||||
// The debuff pass (DebuffAllBeforeAttacking) keeps the wand out until it is done too.
|
||||
if (rule2 != null && !HasPendingDebuffs(rule2, elem2) && !PassWantsDebuff())
|
||||
{
|
||||
_returnToPhysicalCombat = false;
|
||||
if (_savedWeaponId != 0
|
||||
|
|
@ -4235,7 +4344,8 @@ public partial class CombatManager : IDisposable
|
|||
if (rule != null && _spellManager != null && !_returnToPhysicalCombat)
|
||||
{
|
||||
string elem = GetPreferredElement(targetObj, rule);
|
||||
if (HasPendingDebuffs(rule, elem))
|
||||
bool ownPending = HasPendingDebuffs(rule, elem);
|
||||
if (ownPending || _settings.DebuffAllBeforeAttacking)
|
||||
{
|
||||
int wandId = FindWandInItems();
|
||||
// This quick swap (UseObject wand + Magic in one go) can't work with a
|
||||
|
|
@ -4245,16 +4355,19 @@ public partial class CombatManager : IDisposable
|
|||
// It only cost each new target a refused swap, a lost attack cycle and
|
||||
// the swap gate. Skip it then; it still runs when the hands are empty.
|
||||
// A shield or an off-hand weapon blocks the wand the same way (ACE refuses a caster beside it).
|
||||
if (wandId != 0 && (FindWieldedNonWandWeapon(wandId) != 0 || OffhandInSlot() != 0))
|
||||
// The debuff pass (DebuffAllBeforeAttacking) only takes the wand when the hands
|
||||
// are free; with a weapon in hand it doesn't run (no debuffs are cast there).
|
||||
bool handsBlocked = wandId != 0 && (FindWieldedNonWandWeapon(wandId) != 0 || OffhandInSlot() != 0);
|
||||
if (handsBlocked)
|
||||
{
|
||||
if (!_physicalDebuffSkipWarned)
|
||||
if (ownPending && !_physicalDebuffSkipWarned)
|
||||
{
|
||||
_physicalDebuffSkipWarned = true;
|
||||
_host.Log($"[CombatCast] debuffs for '{rule.Name}' skipped in {CombatModeName(CurrentCombatMode)} mode — can't swap to the wand with a weapon in hand");
|
||||
_host.WriteToChat($"[RynthAi] Debuffs aren't cast in melee/missile mode with a weapon in hand (the wand swap doesn't work there). Fighting without them.", 2);
|
||||
}
|
||||
}
|
||||
else if (wandId != 0
|
||||
else if (wandId != 0 && (ownPending || PassWantsDebuff())
|
||||
&& (_weaponSwapGate == null || _weaponSwapGate.TryBeginSwap("combat-debuff-wand")))
|
||||
{
|
||||
// TODO: Save current equipped weapon when inventory API is available.
|
||||
|
|
@ -4275,7 +4388,7 @@ public partial class CombatManager : IDisposable
|
|||
// Physical combat always attacks — spell shape flags (UseArc/Bolt/Ring/Streak)
|
||||
// are only relevant in magic mode and must not gate melee/missile attacks.
|
||||
physicalSent = AttackTarget();
|
||||
if (physicalSent) _attackedThisTick = true;
|
||||
if (physicalSent) { _attackedThisTick = true; NotePassAttack(); }
|
||||
}
|
||||
|
||||
// Ring spells hit an area — no per-target damage feedback is generated,
|
||||
|
|
@ -4666,7 +4779,7 @@ public partial class CombatManager : IDisposable
|
|||
}
|
||||
else
|
||||
{
|
||||
int pack = WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: 1);
|
||||
int pack = WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: 1, new[] { unchecked((int)wid) });
|
||||
if (pack == 0 || !_host.HasMoveItemInternal)
|
||||
{
|
||||
_host.Log($"{head} re-wield: skipped — no pack with room to put 0x{wid:X8} '{wo.Name}' in");
|
||||
|
|
@ -5066,31 +5179,41 @@ public partial class CombatManager : IDisposable
|
|||
{
|
||||
// Target Lock on: keep it until it is no longer valid. A higher priority it holds off is
|
||||
// logged once per pair, so a report shows the lock, not a priority ignored.
|
||||
// Closest is the one exception (2026-11-22): a monster on you takes the lock from one
|
||||
// that isn't (LockGivesWayToMonsterOnYou).
|
||||
if (_settings.TargetLock)
|
||||
{
|
||||
if (_lockedPriority < topPriority && best.Id != _lockedTargetId
|
||||
&& _lockHeldOverLogged != (_lockedTargetId, best.Id))
|
||||
string? onYou = LockGivesWayToMonsterOnYou(scheme, inc, incInScan != null, best);
|
||||
if (onYou == null)
|
||||
{
|
||||
_lockHeldOverLogged = (_lockedTargetId, best.Id);
|
||||
_host.Log($"[CombatTarget] Target Lock keeps 0x{_lockedTargetId:X8} '{_worldFilter[_lockedTargetId]?.Name}' priority {_lockedPriority} " +
|
||||
$"over 0x{best.Id:X8} '{_worldFilter[best.Id]?.Name}' priority {PriorityOf(best.Id)} (it holds until the target dies or leaves Monster Range)");
|
||||
if (_lockedPriority < topPriority && best.Id != _lockedTargetId
|
||||
&& _lockHeldOverLogged != (_lockedTargetId, best.Id))
|
||||
{
|
||||
_lockHeldOverLogged = (_lockedTargetId, best.Id);
|
||||
_host.Log($"[CombatTarget] Target Lock keeps 0x{_lockedTargetId:X8} '{_worldFilter[_lockedTargetId]?.Name}' priority {_lockedPriority} " +
|
||||
$"over 0x{best.Id:X8} '{_worldFilter[best.Id]?.Name}' priority {PriorityOf(best.Id)} (it holds until the target dies or leaves Monster Range)");
|
||||
}
|
||||
return;
|
||||
}
|
||||
return;
|
||||
switchWhy = onYou;
|
||||
}
|
||||
if (best.Id == _lockedTargetId) return;
|
||||
else
|
||||
{
|
||||
if (best.Id == _lockedTargetId) return;
|
||||
|
||||
// Target Lock off: switch only to a clearly better one, and never with an attack
|
||||
// at the incumbent still on its way.
|
||||
// Not while the incumbent is out of this tick's scan (inside the scan grace): its
|
||||
// values are the last ones seen, and judging fresh candidates against them switched
|
||||
// away from a monster closing in. R-20261031-201214-8be7: a Brier Wasp Swarm last
|
||||
// scanned at 4.3 m, live at 1.9 m, lost to a wasp at 2.4 m as "clearly better",
|
||||
// 124 ms after a bolt went out at it.
|
||||
if (incInScan == null) return;
|
||||
double incKey = SchemeKey(scheme, inc);
|
||||
if (incKey - bestKey < SchemeMargin(scheme)) return;
|
||||
if (AttackInFlightAtLocked(now)) return;
|
||||
switchWhy = $"{SchemeName(scheme)}: {DescribeSchemeValue(scheme, inc)}, another is clearly better";
|
||||
// Target Lock off: switch only to a clearly better one, and never with an attack
|
||||
// at the incumbent still on its way.
|
||||
// Not while the incumbent is out of this tick's scan (inside the scan grace): its
|
||||
// values are the last ones seen, and judging fresh candidates against them switched
|
||||
// away from a monster closing in. R-20261031-201214-8be7: a Brier Wasp Swarm last
|
||||
// scanned at 4.3 m, live at 1.9 m, lost to a wasp at 2.4 m as "clearly better",
|
||||
// 124 ms after a bolt went out at it.
|
||||
if (incInScan == null) return;
|
||||
double incKey = SchemeKey(scheme, inc);
|
||||
if (incKey - bestKey < SchemeMargin(scheme)) return;
|
||||
if (AttackInFlightAtLocked(now)) return;
|
||||
switchWhy = $"{SchemeName(scheme)}: {DescribeSchemeValue(scheme, inc)}, another is clearly better";
|
||||
}
|
||||
}
|
||||
else if (_lockedTargetId != 0)
|
||||
{
|
||||
|
|
@ -5105,6 +5228,30 @@ public partial class CombatManager : IDisposable
|
|||
LockTarget(best, bestPriority, $"{SchemeName(scheme)}: {DescribeSchemeValue(scheme, best)}, priority {bestPriority}, {DescribeTargetPos(best.Id)}", switchWhy);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Target Lock with Targeting "Closest" (2026-11-22, #rynthsuite 11-15: "surrounded by mobs and
|
||||
/// watched it target mobs 40 yds out"). The lock held a far monster while others walked up and
|
||||
/// hit the character: on the PC (pid 1792, 11-20 19:41:45) a missile character locked an Obsidian
|
||||
/// Hurler at 24.5 m, the only one in sight; an Obsidian Gigas came up and landed 16 hits for 476
|
||||
/// damage in 32 s, and the bot kept shooting the Hurler for 59 s, locking the Gigas (1.6 m) only
|
||||
/// when the Hurler died. Now a candidate within CloseAttackYards (on you) takes the lock from a
|
||||
/// target more than LockYieldFarM off. The other schemes keep the lock as before (Farthest picks
|
||||
/// far ones on purpose), and so does a lock the player picked. Returns the switch's reason, or
|
||||
/// null to keep the lock.
|
||||
/// </summary>
|
||||
private string? LockGivesWayToMonsterOnYou(TargetScheme scheme, in ScannedTarget inc, bool incFresh, in ScannedTarget best)
|
||||
{
|
||||
if (scheme != TargetScheme.Closest || _lockByPlayer || !incFresh) return null;
|
||||
if (best.Id == 0 || best.Id == _lockedTargetId) return null;
|
||||
if (best.Distance > CloseAttackYards || inc.Distance <= LockYieldFarM) return null;
|
||||
return $"Target Lock: a monster is on you at {best.Distance:0.0} m and the target is {inc.Distance:0.0} m off";
|
||||
}
|
||||
|
||||
/// <summary>A locked target farther than this gives way to a monster within CloseAttackYards
|
||||
/// (Target Lock, Closest). The 1.5 m over CloseAttackYards keeps two monsters near you from
|
||||
/// trading the lock.</summary>
|
||||
private const double LockYieldFarM = CloseAttackYards + CloserFartherMarginM;
|
||||
|
||||
/// <summary>Makes <paramref name="best"/> the fight target (one log line; the switch says why).</summary>
|
||||
private void LockTarget(ScannedTarget best, int bestPriority, string picked, string? switchWhy)
|
||||
{
|
||||
|
|
@ -5840,7 +5987,7 @@ public partial class CombatManager : IDisposable
|
|||
|
||||
case HandSwapSequence.Act.MoveToPack:
|
||||
{
|
||||
int pack = OpenPackOverride?.Invoke() ?? WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: 1);
|
||||
int pack = OpenPackOverride?.Invoke() ?? WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: 1, new[] { step.Id });
|
||||
if (pack == 0)
|
||||
{
|
||||
WorldObjectCache.WarnPackFull(_host, "can't put the wand away to put the weapons back");
|
||||
|
|
@ -5946,7 +6093,7 @@ public partial class CombatManager : IDisposable
|
|||
int pack = 0;
|
||||
if (moves.Count > 0)
|
||||
{
|
||||
pack = OpenPackOverride?.Invoke() ?? WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: moves.Count);
|
||||
pack = OpenPackOverride?.Invoke() ?? WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: moves.Count, moves);
|
||||
if (pack == 0) return 0;
|
||||
}
|
||||
if (!_host.ChangeCombatModeFor(CombatMode.NonCombat, "Combat", $"{HandsSwapLabel} burst: peace, the wand out and the weapons on at once")) return 1;
|
||||
|
|
@ -6998,7 +7145,7 @@ public partial class CombatManager : IDisposable
|
|||
|
||||
if (IsWieldedLive(bowId))
|
||||
{
|
||||
int openPack = OpenPackOverride?.Invoke() ?? WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: 1);
|
||||
int openPack = OpenPackOverride?.Invoke() ?? WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: 1, new[] { bowId });
|
||||
if (openPack == 0 || _combatBowDequipAttempts >= CombatBowDequipMaxAttempts)
|
||||
{
|
||||
// No verified-open pack to receive the bow, or repeated failures — the swap
|
||||
|
|
@ -7168,6 +7315,10 @@ public partial class CombatManager : IDisposable
|
|||
/// <summary>The line-of-sight check is skipped for melee within this (same units as Monster Range).</summary>
|
||||
internal const double MeleeIgnoresLosWithin = 4.0;
|
||||
|
||||
/// <summary>Melee hits across a doorway this far (one inside a building, the other on the step outside); farther,
|
||||
/// across the building's wall, it goes in by a door (the hunt's walk), not at the wall under a window.</summary>
|
||||
internal const double MeleeAcrossDoorwayM = 3.5;
|
||||
|
||||
/// <summary>Melee leaves out a monster more than this above or below the character...</summary>
|
||||
internal const double MeleeMaxRiseM = 3.0;
|
||||
/// <summary>...when it is also this steep from here (rise over run, about 37 degrees): a monster up a ramp
|
||||
|
|
@ -7896,49 +8047,19 @@ public partial class CombatManager : IDisposable
|
|||
var rule = GetRuleForTarget(target);
|
||||
string element = GetPreferredElement(target, rule);
|
||||
|
||||
if (rule != null)
|
||||
BeginDebuffPass(); // Debuff every monster in range before attacking: the fight's first cast begins it
|
||||
if (rule != null
|
||||
&& NextDebuffFor(activeTargetId, rule, element, RynthClock.Now, out string debuffKey, out int debuffSpellId, out int castTier, out bool renewal))
|
||||
{
|
||||
var pendingDebuffs = BuildDebuffList(rule, element);
|
||||
DateTime now = RynthClock.Now;
|
||||
foreach (var debuffKey in pendingDebuffs)
|
||||
{
|
||||
if (_debuffs.IsOn(activeTargetId, debuffKey, now)) continue;
|
||||
bool renewal = _debuffs.RenewAt(activeTargetId, debuffKey) != null;
|
||||
|
||||
int spellId = 0;
|
||||
int castTier = 0;
|
||||
if (debuffKey.StartsWith("Vuln:"))
|
||||
spellId = FindBestVulnSpellWithTier(debuffKey.Substring(5), out castTier);
|
||||
else if (debuffKey.StartsWith("Custom:"))
|
||||
spellId = FindBestCustomDebuffWithTier(debuffKey.Substring(7), out castTier);
|
||||
else if (debuffKey.StartsWith("Void:"))
|
||||
spellId = FindBestVoidDebuffWithTier(debuffKey.Substring(5), out castTier);
|
||||
else
|
||||
spellId = FindBestDebuffSpellWithTier(debuffKey, out castTier);
|
||||
|
||||
if (spellId == 0) continue;
|
||||
if (ManaHoldsCast(spellId)) return; // mana reserve: Stamina to Mana first, or regenerate
|
||||
|
||||
try
|
||||
{
|
||||
_host.CastSpellFor((uint)activeTargetId, spellId, "Combat", SpellTableStub.GetById(spellId)?.Name ?? $"spell {spellId}");
|
||||
MarkCombatCastIssued();
|
||||
StartCastChatTrace(spellId, activeTargetId);
|
||||
_lastSpellCast = RynthClock.Now;
|
||||
_lastCastWasRing = false;
|
||||
_pendingDebuffKey = debuffKey;
|
||||
_pendingDebuffTargetId = activeTargetId;
|
||||
_pendingDebuffSpellId = spellId;
|
||||
_pendingDebuffTier = castTier;
|
||||
_waitingForDebuffResult = true;
|
||||
_pendingDebuffCastTime = RynthClock.Now;
|
||||
_host.WriteToChat($"[RynthAi] {(renewal ? "Renewing" : "Casting")}: {debuffKey} (T{castTier}) on {target.Name}", 5);
|
||||
}
|
||||
catch { }
|
||||
return;
|
||||
}
|
||||
if (ManaHoldsCast(debuffSpellId)) return; // mana reserve: Stamina to Mana first, or regenerate
|
||||
CastDebuffAt(activeTargetId, target.Name, debuffKey, debuffSpellId, castTier, renewal);
|
||||
return;
|
||||
}
|
||||
|
||||
// Debuff every monster in range before attacking (CombatManager.DebuffPass.cs): the next
|
||||
// monster's debuff instead of the attack, while the pass has one.
|
||||
if (_settings.DebuffAllBeforeAttacking && TryDebuffPassCast()) return;
|
||||
|
||||
// A rule with no attack shape on means no offensive cast at this monster: a script's choice
|
||||
// is no exception (it used to be asked first, and cast at a monster the owner turned casting off for).
|
||||
if (rule != null && PickBaseShape(rule) < 0)
|
||||
|
|
@ -8008,6 +8129,7 @@ public partial class CombatManager : IDisposable
|
|||
MarkCombatCastIssued();
|
||||
StartCastChatTrace(offensiveSpellId, activeTargetId);
|
||||
SessionAttackCasts++; // D6: offensive attack-cast tally for the casts-per-kill signal
|
||||
NotePassAttack(); // the debuff pass: an arrival may get the next cast
|
||||
CastsSinceLastKill++; // reset in OnKillNotification when a kill lands
|
||||
_lastSpellCast = RynthClock.Now;
|
||||
_lastCastWasRing = multiTarget; // walls too: area casts (2026-10-08)
|
||||
|
|
@ -8166,6 +8288,60 @@ public partial class CombatManager : IDisposable
|
|||
return FindBestShapedSpell(element, rule, out _) != 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The first of the rule's debuffs that isn't on <paramref name="targetId"/> and that this
|
||||
/// character can cast (a debuff with no castable spell is passed over), or false.
|
||||
/// </summary>
|
||||
private bool NextDebuffFor(int targetId, MonsterRule rule, string element, DateTime now,
|
||||
out string key, out int spellId, out int tier, out bool renewal)
|
||||
{
|
||||
foreach (var debuffKey in BuildDebuffList(rule, element))
|
||||
{
|
||||
if (_debuffs.IsOn(targetId, debuffKey, now)) continue;
|
||||
int id;
|
||||
int castTier;
|
||||
if (debuffKey.StartsWith("Vuln:"))
|
||||
id = FindBestVulnSpellWithTier(debuffKey.Substring(5), out castTier);
|
||||
else if (debuffKey.StartsWith("Custom:"))
|
||||
id = FindBestCustomDebuffWithTier(debuffKey.Substring(7), out castTier);
|
||||
else if (debuffKey.StartsWith("Void:"))
|
||||
id = FindBestVoidDebuffWithTier(debuffKey.Substring(5), out castTier);
|
||||
else
|
||||
id = FindBestDebuffSpellWithTier(debuffKey, out castTier);
|
||||
if (id == 0) continue;
|
||||
key = debuffKey;
|
||||
spellId = id;
|
||||
tier = castTier;
|
||||
renewal = _debuffs.RenewAt(targetId, debuffKey) != null;
|
||||
return true;
|
||||
}
|
||||
key = ""; spellId = 0; tier = 0; renewal = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>One debuff cast at <paramref name="targetId"/>; its result is read from chat (HandleChatForDebuffs).</summary>
|
||||
private bool CastDebuffAt(int targetId, string targetName, string debuffKey, int spellId, int castTier, bool renewal)
|
||||
{
|
||||
try
|
||||
{
|
||||
_host.CastSpellFor((uint)targetId, spellId, "Combat", SpellTableStub.GetById(spellId)?.Name ?? $"spell {spellId}");
|
||||
MarkCombatCastIssued();
|
||||
StartCastChatTrace(spellId, targetId);
|
||||
_lastSpellCast = RynthClock.Now;
|
||||
_lastCastWasRing = false;
|
||||
_pendingDebuffKey = debuffKey;
|
||||
_pendingDebuffTargetId = targetId;
|
||||
_pendingDebuffSpellId = spellId;
|
||||
_pendingDebuffTier = castTier;
|
||||
_pendingDebuffFromPass = false;
|
||||
_waitingForDebuffResult = true;
|
||||
_pendingDebuffCastTime = RynthClock.Now;
|
||||
_host.WriteToChat($"[RynthAi] {(renewal ? "Renewing" : "Casting")}: {debuffKey} (T{castTier}) on {targetName}", 5);
|
||||
return true;
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
private bool HasPendingDebuffs(MonsterRule rule, string element)
|
||||
{
|
||||
if (rule == null) return false;
|
||||
|
|
@ -8693,6 +8869,7 @@ public partial class CombatManager : IDisposable
|
|||
/// <summary>"ceiling 2.1 m out", "wall in the straight line": why an arc verdict is blocked.</summary>
|
||||
internal static string DescribeArcBlock(in TargetingFSM.LosDetail d)
|
||||
{
|
||||
if (d.TerrainBlocked) return $"a hill {d.TerrainAlong:0} m out";
|
||||
if (d.LineBlocked) return "wall in the straight line";
|
||||
if (d.Arc.OutOfReach) return "out of reach";
|
||||
if (d.Arc.Blocked)
|
||||
|
|
|
|||
285
Plugins/RynthCore.Plugin.RynthAi/Combat/DebuffPass.cs
Normal file
285
Plugins/RynthCore.Plugin.RynthAi/Combat/DebuffPass.cs
Normal file
|
|
@ -0,0 +1,285 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
/// <summary>
|
||||
/// "Debuff every monster in range before attacking" (setting DebuffAllBeforeAttacking, off by
|
||||
/// default). Which monster gets the next debuff cast, and when attacking may start. Pure state, no
|
||||
/// host calls; CombatManager feeds it the scan (nearest first) and says which monsters still need a
|
||||
/// debuff (the monster's own rule: Imperil, vulns, Void ones, typed-in ones, not on it and castable).
|
||||
///
|
||||
/// * A fight starts with the pass: the monsters in Monster Range that need a debuff get them,
|
||||
/// nearest first, one cast at a time. Nothing is attacked until every one has them, or has
|
||||
/// <see cref="MaxFailsPerMonster"/> failed tries (resists, fizzles, refusals) or
|
||||
/// <see cref="MaxTriesPerMonster"/> casts in all, or the pass has run <see cref="PassSeconds"/>.
|
||||
/// The fight target's own debuffs are cast by the usual per-target code just before this.
|
||||
/// * A monster hitting the character in melee ("on you") stops the pass while it does: the fight
|
||||
/// goes on as without the setting (the fight target's own debuffs, then the attack), and the pass
|
||||
/// picks up again once nothing is on you (while its time lasts). No arrival is debuffed meanwhile.
|
||||
/// * Once attacking has started, a monster that comes into range later (an arrival) gets its debuffs
|
||||
/// too, one cast between two attacks on the fight target, for <see cref="ArrivalSeconds"/> after it
|
||||
/// came. The fight target is never changed for it. Monsters of the first pass aren't renewed here
|
||||
/// (the fight target's own code renews the target's).
|
||||
/// * The pet summon waits while the pass runs (<see cref="Holding"/>), and for at most
|
||||
/// <see cref="IdleHoldSeconds"/> before the fight's first cast begins it.
|
||||
/// * The fight ends when nothing has been in range and nothing engaged for
|
||||
/// <see cref="FightOverSeconds"/>: everything starts over for the next one.
|
||||
/// </summary>
|
||||
internal sealed class DebuffPass
|
||||
{
|
||||
public const int MaxFailsPerMonster = 3;
|
||||
public const int MaxTriesPerMonster = 8;
|
||||
public const double PassSeconds = 30.0;
|
||||
public const double ArrivalSeconds = 30.0;
|
||||
public const double FightOverSeconds = 3.0;
|
||||
/// <summary>The pet summon's wait before the pass has begun (the fight's first cast is coming).</summary>
|
||||
public const double IdleHoldSeconds = 5.0;
|
||||
private const int MaxMonsters = 256;
|
||||
|
||||
public enum Stage { Idle, Debuffing, Attacking }
|
||||
|
||||
private sealed class Mon
|
||||
{
|
||||
public DateTime FirstSeen;
|
||||
public DateTime LastSeen;
|
||||
public bool Arrival;
|
||||
public int Tries;
|
||||
public int Fails;
|
||||
public bool GaveUp;
|
||||
}
|
||||
|
||||
private readonly Dictionary<int, Mon> _mons = new();
|
||||
private DateTime _emptySince = DateTime.MinValue;
|
||||
private bool _castSinceAttack;
|
||||
private bool _onYouLogged;
|
||||
|
||||
public Stage Phase { get; private set; } = Stage.Idle;
|
||||
public DateTime StartedAt { get; private set; } = DateTime.MinValue;
|
||||
public DateTime EndedAt { get; private set; } = DateTime.MinValue;
|
||||
/// <summary>Why the last pass ended ("" while none has).</summary>
|
||||
public string EndReason { get; private set; } = "";
|
||||
/// <summary>Debuff casts the pass (or an arrival) sent this fight.</summary>
|
||||
public int Casts { get; private set; }
|
||||
|
||||
/// <summary>One [DebuffPass] line (CombatManager: the RynthAi log).</summary>
|
||||
public Action<string>? Log { get; set; }
|
||||
/// <summary>A monster's name for the log lines.</summary>
|
||||
public Func<int, string>? NameOf { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Every scan: the monsters in Monster Range that passed the scan's filters, and whether a target
|
||||
/// is engaged. New ones are noted (an arrival once attacking has started); a fight with nothing in
|
||||
/// range and nothing engaged for <see cref="FightOverSeconds"/> is over.
|
||||
/// </summary>
|
||||
public void Observe(IReadOnlyList<int> inRange, bool engaged, DateTime now)
|
||||
{
|
||||
InRange = inRange.Count;
|
||||
if (inRange.Count > 0 && FightSeenAt == DateTime.MinValue) FightSeenAt = now;
|
||||
if (inRange.Count == 0 && !engaged)
|
||||
{
|
||||
if (Phase == Stage.Idle && _mons.Count == 0) return;
|
||||
if (_emptySince == DateTime.MinValue) _emptySince = now;
|
||||
else if ((now - _emptySince).TotalSeconds >= FightOverSeconds)
|
||||
{
|
||||
if (Phase != Stage.Idle)
|
||||
Log?.Invoke($"[DebuffPass] fight over: {Casts} debuff casts; the next fight starts a new pass");
|
||||
Reset();
|
||||
}
|
||||
return;
|
||||
}
|
||||
_emptySince = DateTime.MinValue;
|
||||
for (int i = 0; i < inRange.Count; i++)
|
||||
{
|
||||
int id = inRange[i];
|
||||
if (_mons.TryGetValue(id, out Mon? m)) { m.LastSeen = now; continue; }
|
||||
if (_mons.Count >= MaxMonsters) Prune(now);
|
||||
_mons[id] = new Mon { FirstSeen = now, LastSeen = now, Arrival = Phase == Stage.Attacking };
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The monster to debuff now, or 0 to attack (or when there is nothing to do). Starts the pass at
|
||||
/// a fight's first call and ends it when every monster has its debuffs, is given up on, or time is
|
||||
/// up. <paramref name="nearestFirst"/>: the scan's monsters in Monster Range, nearest first;
|
||||
/// <paramref name="needsDebuff"/>: one of its debuffs isn't on it and this character can cast it.
|
||||
/// </summary>
|
||||
public int Next(IReadOnlyList<int> nearestFirst, int fightTarget, Func<int, bool> needsDebuff, bool monsterOnYou, DateTime now)
|
||||
{
|
||||
Begin(nearestFirst, now);
|
||||
if (Phase == Stage.Idle) return 0;
|
||||
|
||||
if (Phase == Stage.Debuffing)
|
||||
{
|
||||
if (monsterOnYou)
|
||||
{
|
||||
if (!_onYouLogged)
|
||||
{
|
||||
_onYouLogged = true;
|
||||
Log?.Invoke("[DebuffPass] a monster is hitting you in melee: the fight target is debuffed and attacked first; the pass waits");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if (_onYouLogged)
|
||||
{
|
||||
_onYouLogged = false;
|
||||
Log?.Invoke("[DebuffPass] nothing on you now: the pass goes on");
|
||||
}
|
||||
if ((now - StartedAt).TotalSeconds >= PassSeconds)
|
||||
{
|
||||
End(now, $"time cap ({PassSeconds:0} s)");
|
||||
return 0;
|
||||
}
|
||||
foreach (int id in nearestFirst)
|
||||
{
|
||||
if (id == fightTarget || !Eligible(id)) continue;
|
||||
if (needsDebuff(id)) return id;
|
||||
}
|
||||
End(now, "every monster in range has its debuffs or was given up on");
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Attacking: newcomers only, one debuff between two attacks on the fight target; none while
|
||||
// something is hitting you.
|
||||
if (_castSinceAttack || monsterOnYou) return 0;
|
||||
foreach (int id in nearestFirst)
|
||||
{
|
||||
if (id == fightTarget || !Eligible(id)) continue;
|
||||
Mon m = _mons[id];
|
||||
if (!m.Arrival || (now - m.FirstSeen).TotalSeconds > ArrivalSeconds) continue;
|
||||
if (needsDebuff(id)) return id;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A fight's first attack decision (Magic mode): two or more monsters in range start the pass
|
||||
/// (logged); one alone starts the fight attacking (a later one is an arrival). Nothing otherwise.
|
||||
/// </summary>
|
||||
public void Begin(IReadOnlyList<int> nearestFirst, DateTime now)
|
||||
{
|
||||
if (Phase != Stage.Idle || nearestFirst.Count == 0) return;
|
||||
foreach (int id in nearestFirst)
|
||||
if (!_mons.ContainsKey(id)) _mons[id] = new Mon { FirstSeen = now, LastSeen = now };
|
||||
foreach (var m in _mons.Values) m.Arrival = false;
|
||||
StartedAt = now;
|
||||
EndReason = "";
|
||||
Casts = 0;
|
||||
if (nearestFirst.Count < 2)
|
||||
{
|
||||
// One monster: nothing to wait for (its own debuffs come first as always).
|
||||
Phase = Stage.Attacking;
|
||||
EndedAt = now;
|
||||
EndReason = "one monster";
|
||||
return;
|
||||
}
|
||||
Phase = Stage.Debuffing;
|
||||
Log?.Invoke($"[DebuffPass] start: {nearestFirst.Count} monsters in range, debuffing each before attacking");
|
||||
}
|
||||
|
||||
private bool Eligible(int id)
|
||||
{
|
||||
if (!_mons.TryGetValue(id, out Mon? m))
|
||||
{
|
||||
// Not observed yet (the caller's list is newer than the last scan): treat it as seen now.
|
||||
_mons[id] = m = new Mon { FirstSeen = DateTime.MinValue, LastSeen = DateTime.MinValue, Arrival = false };
|
||||
}
|
||||
return !m.GaveUp;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True while the pass holds the pet summon: debuffing, inside its time, nothing on you; or, before
|
||||
/// the fight's first attack decision, for <see cref="IdleHoldSeconds"/> after two or more monsters
|
||||
/// came into range (the caller checks the pass can run at all).
|
||||
/// </summary>
|
||||
public bool Holding(DateTime now) => Phase switch
|
||||
{
|
||||
Stage.Debuffing => (now - StartedAt).TotalSeconds < PassSeconds && !_onYouLogged,
|
||||
Stage.Idle => InRange >= 2 && FightSeenAt != DateTime.MinValue && (now - FightSeenAt).TotalSeconds < IdleHoldSeconds,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
/// <summary>Monsters in range at the last <see cref="Observe"/>.</summary>
|
||||
public int InRange { get; private set; }
|
||||
/// <summary>When this fight's first monster came into range (MinValue between fights).</summary>
|
||||
public DateTime FightSeenAt { get; private set; } = DateTime.MinValue;
|
||||
|
||||
/// <summary>A pass debuff went out at <paramref name="id"/>.</summary>
|
||||
public void NoteCast(int id, DateTime now)
|
||||
{
|
||||
Casts++;
|
||||
if (Phase == Stage.Attacking) _castSinceAttack = true;
|
||||
if (!_mons.TryGetValue(id, out Mon? m)) _mons[id] = m = new Mon { FirstSeen = now, LastSeen = now };
|
||||
if (++m.Tries >= MaxTriesPerMonster && !m.GaveUp)
|
||||
{
|
||||
m.GaveUp = true;
|
||||
Log?.Invoke($"[DebuffPass] 0x{(uint)id:X8} '{Name(id)}': {MaxTriesPerMonster} debuff casts this fight, no more from the pass");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A pass debuff at <paramref name="id"/> was resisted, fizzled or refused. True when that gave it up.</summary>
|
||||
public bool NoteFailed(int id)
|
||||
{
|
||||
if (!_mons.TryGetValue(id, out Mon? m)) return false;
|
||||
if (m.GaveUp || ++m.Fails < MaxFailsPerMonster) return false;
|
||||
m.GaveUp = true;
|
||||
Log?.Invoke($"[DebuffPass] 0x{(uint)id:X8} '{Name(id)}': {MaxFailsPerMonster} failed tries, skipped (the pass doesn't wait on it)");
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>An attack (war/void cast, swing or shot) went out at the fight target.</summary>
|
||||
public void NoteAttack() => _castSinceAttack = false;
|
||||
|
||||
/// <summary>The monster died or went away.</summary>
|
||||
public void Forget(int id) => _mons.Remove(id);
|
||||
|
||||
public bool GaveUp(int id) => _mons.TryGetValue(id, out Mon? m) && m.GaveUp;
|
||||
public int Tries(int id) => _mons.TryGetValue(id, out Mon? m) ? m.Tries : 0;
|
||||
public bool IsArrival(int id) => _mons.TryGetValue(id, out Mon? m) && m.Arrival;
|
||||
public int Known => _mons.Count;
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
_mons.Clear();
|
||||
Phase = Stage.Idle;
|
||||
_emptySince = DateTime.MinValue;
|
||||
_castSinceAttack = false;
|
||||
_onYouLogged = false;
|
||||
StartedAt = DateTime.MinValue;
|
||||
FightSeenAt = DateTime.MinValue;
|
||||
InRange = 0;
|
||||
Casts = 0;
|
||||
}
|
||||
|
||||
private void End(DateTime now, string why)
|
||||
{
|
||||
Phase = Stage.Attacking;
|
||||
EndedAt = now;
|
||||
EndReason = why;
|
||||
int gaveUp = 0;
|
||||
foreach (var m in _mons.Values) if (m.GaveUp) gaveUp++;
|
||||
Log?.Invoke($"[DebuffPass] done after {(now - StartedAt).TotalSeconds:0.0} s ({why}): {Casts} debuff casts" +
|
||||
(gaveUp > 0 ? $", {gaveUp} monster{(gaveUp == 1 ? "" : "s")} skipped" : "") + "; attacking now");
|
||||
}
|
||||
|
||||
private string Name(int id)
|
||||
{
|
||||
try { return NameOf?.Invoke(id) ?? ""; } catch { return ""; }
|
||||
}
|
||||
|
||||
private void Prune(DateTime now)
|
||||
{
|
||||
List<int>? drop = null;
|
||||
foreach (var kv in _mons)
|
||||
if ((now - kv.Value.LastSeen).TotalSeconds > 60) (drop ??= new()).Add(kv.Key);
|
||||
if (drop != null) foreach (int id in drop) _mons.Remove(id);
|
||||
while (_mons.Count >= MaxMonsters)
|
||||
{
|
||||
int oldest = 0;
|
||||
DateTime best = DateTime.MaxValue;
|
||||
foreach (var kv in _mons)
|
||||
if (kv.Value.LastSeen < best) { best = kv.Value.LastSeen; oldest = kv.Key; }
|
||||
_mons.Remove(oldest);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -51,8 +51,18 @@ internal static class DirtyFightingHeights
|
|||
|
||||
public const string DefaultOrder = "HML";
|
||||
|
||||
/// <summary>Every order the setting can hold, in the order the UI lists them.</summary>
|
||||
public static readonly string[] OrderChoices = { "HML", "HLM", "MHL", "MLH", "LHM", "LMH" };
|
||||
/// <summary>
|
||||
/// Every order the setting can hold, in the order the UI lists them: all three heights, then two,
|
||||
/// then one (R-20261120-014055-59be: "pick just 1 or 2 heights"). A height left out is never aimed
|
||||
/// at for its effect; the Then attack height still applies once the chosen ones are on. The engine's
|
||||
/// Settings window lists the same (SettingsData.DfOrders).
|
||||
/// </summary>
|
||||
public static readonly string[] OrderChoices =
|
||||
{
|
||||
"HML", "HLM", "MHL", "MLH", "LHM", "LMH",
|
||||
"HM", "HL", "MH", "ML", "LH", "LM",
|
||||
"H", "M", "L",
|
||||
};
|
||||
|
||||
public static readonly string[] HeightNames = { "Low", "Medium", "High" };
|
||||
|
||||
|
|
@ -70,7 +80,7 @@ internal static class DirtyFightingHeights
|
|||
public static string HeightName(int height) =>
|
||||
height >= 0 && height < HeightNames.Length ? HeightNames[height] : "?";
|
||||
|
||||
/// <summary>A valid order ("HML" and the like: H, M and L once each), else <see cref="DefaultOrder"/>.</summary>
|
||||
/// <summary>A valid order ("HML", "HM", "L" and the like: one to three of H, M and L, each at most once), else <see cref="DefaultOrder"/>.</summary>
|
||||
public static string NormalizeOrder(string? order)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(order)) return DefaultOrder;
|
||||
|
|
@ -84,17 +94,17 @@ internal static class DirtyFightingHeights
|
|||
public static int[] ParseOrder(string? order)
|
||||
{
|
||||
string o = NormalizeOrder(order);
|
||||
var heights = new int[3];
|
||||
for (int i = 0; i < 3; i++)
|
||||
var heights = new int[o.Length];
|
||||
for (int i = 0; i < o.Length; i++)
|
||||
heights[i] = o[i] switch { 'H' => High, 'M' => Medium, _ => Low };
|
||||
return heights;
|
||||
}
|
||||
|
||||
/// <summary>"High, Medium, Low".</summary>
|
||||
/// <summary>"High, Medium, Low"; "High, Medium"; "Low only".</summary>
|
||||
public static string OrderLabel(string? order)
|
||||
{
|
||||
int[] h = ParseOrder(order);
|
||||
return $"{HeightName(h[0])}, {HeightName(h[1])}, {HeightName(h[2])}";
|
||||
return h.Length == 1 ? HeightName(h[0]) + " only" : string.Join(", ", Array.ConvertAll(h, HeightName));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -147,7 +157,7 @@ internal static class DirtyFightingHeights
|
|||
/// The height for the next attack. The fixed height (the Melee/Missile Attack Height setting)
|
||||
/// when the rotation is off or Dirty Fighting isn't trained. Otherwise the first height in
|
||||
/// <paramref name="order"/> whose effect is missing or due to run out within
|
||||
/// <see cref="RenewLeadSeconds"/>; with all three on, <paramref name="defaultHeight"/>
|
||||
/// <see cref="RenewLeadSeconds"/>; with every height in the order on, <paramref name="defaultHeight"/>
|
||||
/// (<see cref="DefaultIsFixedHeight"/> = the fixed height).
|
||||
/// <paramref name="effects"/> may be null (nothing known about this target: a fresh one).
|
||||
/// </summary>
|
||||
|
|
|
|||
|
|
@ -107,6 +107,28 @@ internal sealed class HealLatencyTracker
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The macro is off: an open episode ends here, said once when it lasted NoHealLogMs or more. It
|
||||
/// used to stay open, and the heal after a restart counted the whole stop (2026-11-22: "13871 ms",
|
||||
/// of which 12 s with the macro off).
|
||||
/// </summary>
|
||||
public void MacroOff(DateTime now, int hp)
|
||||
{
|
||||
if (_open && !_healed)
|
||||
{
|
||||
double ms = (now - _start).TotalMilliseconds;
|
||||
if (ms >= NoHealLogMs)
|
||||
{
|
||||
_noHeal++;
|
||||
_log($"[HealLatency] no heal in {ms:0} ms: health {_startHp}% under {_line} {_lineValue}%{Where(_inCombat)}{(_followUp ? " (follow-up)" : "")}, " +
|
||||
$"then the macro stopped at {hp}%; held by: {Held()}{Arb()}");
|
||||
}
|
||||
}
|
||||
_open = false;
|
||||
_healed = false;
|
||||
_followUp = false;
|
||||
}
|
||||
|
||||
/// <summary>Once per heartbeat, after the tick's work: why no heal went out this tick.</summary>
|
||||
public void EndTick(DateTime now, string heldBy, string detail, string arbiterActivity)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -10,9 +10,12 @@ namespace RynthCore.Plugin.RynthAi;
|
|||
/// Which combat pet to summon for a monster. The Damage panel stores a choice per
|
||||
/// monster (wcid): Auto (""), an element ("E:Cold"), or a specific essence
|
||||
/// ("I:<id>"). Auto picks an element from, in order: the Monsters-tab rule
|
||||
/// (Pet damage, else damage type), the monster's learned resists, then the
|
||||
/// element that has done best on it in the Damage tab; with none of those the
|
||||
/// Items-panel order is kept. Combat pets can't be swapped while one is out
|
||||
/// (Pet damage, else damage type), the Summons settings' Pet element (2026-11-22;
|
||||
/// "" = Any, the default, skips it), the Default row's pet damage, the monster's
|
||||
/// learned resists, then the element that has done best on it in the Damage tab;
|
||||
/// with none of those the Items-panel order is kept. An item whose pets deal more
|
||||
/// than one element (a server's holder of two summons, PetElements) fits an element
|
||||
/// by <see cref="Rank"/>: all its pets first, then its first pet, then a later one. Combat pets can't be swapped while one is out
|
||||
/// (ACE: "already active"), so the choice is made at each summon.
|
||||
/// </summary>
|
||||
internal static class PetChoice
|
||||
|
|
@ -21,25 +24,40 @@ internal static class PetChoice
|
|||
public static readonly string[] Elements =
|
||||
{ "Fire", "Cold", "Lightning", "Acid", "Nether", "Slash", "Pierce", "Bludgeon" };
|
||||
|
||||
/// <summary>The Summons settings' Pet element choices: "Any" (stored as "") then every element.</summary>
|
||||
public static readonly string[] SettingChoices =
|
||||
{ "Any", "Fire", "Cold", "Acid", "Lightning", "Nether", "Slash", "Pierce", "Bludgeon" };
|
||||
|
||||
/// <summary>The tooltip both Pet element controls show.</summary>
|
||||
public const string SettingTooltip =
|
||||
"The element combat pets are summoned for. Any: each monster's own choice (a Damage-panel pick,\n" +
|
||||
"its Monsters rule, then the element it is weakest to). Another element: an essence of it is\n" +
|
||||
"summoned first, unless the monster has a Damage-panel pick or a Monsters rule of its own.\n" +
|
||||
"A summon that holds two (two pets, two elements) counts when either of its pets deals it.";
|
||||
|
||||
/// <summary>The index of a stored Pet element in <see cref="SettingChoices"/> (0 = Any).</summary>
|
||||
public static int SettingIndex(string? stored)
|
||||
{
|
||||
string e = NormalizeElement(stored);
|
||||
int i = e.Length == 0 ? 0 : Array.IndexOf(SettingChoices, e);
|
||||
return i < 0 ? 0 : i;
|
||||
}
|
||||
|
||||
/// <summary>The stored Pet element for a <see cref="SettingChoices"/> index ("" = Any).</summary>
|
||||
public static string SettingValue(int index)
|
||||
=> index <= 0 || index >= SettingChoices.Length ? "" : SettingChoices[index];
|
||||
|
||||
/// <summary>
|
||||
/// A summoning essence's element. From UiEffects (int 18), which essences carry
|
||||
/// in their public data (Fire K'nath 32, Frost 128, Acid 256 ...), else from
|
||||
/// words in the name. "" if unknown.
|
||||
/// A summoning essence's element: its first pet's (<see cref="PetElements.Describe(RynthCoreHost, uint, string?)"/>).
|
||||
/// From UiEffects (int 18), which essences carry in their public data (Fire K'nath 32, Frost 128,
|
||||
/// Acid 256 ...), else from words in the name. "" if unknown.
|
||||
/// </summary>
|
||||
public static string ElementOf(RynthCoreHost host, uint deviceId, string name)
|
||||
{
|
||||
if (host.HasGetObjectIntProperty && host.TryGetObjectIntProperty(deviceId, 18, out int fx) && fx != 0)
|
||||
{
|
||||
if ((fx & 0x0020) != 0) return "Fire";
|
||||
if ((fx & 0x0040) != 0) return "Lightning";
|
||||
if ((fx & 0x0080) != 0) return "Cold";
|
||||
if ((fx & 0x0100) != 0) return "Acid";
|
||||
if ((fx & 0x1000) != 0) return "Nether";
|
||||
if ((fx & 0x0200) != 0) return "Bludgeon";
|
||||
if ((fx & 0x0400) != 0) return "Slash";
|
||||
if ((fx & 0x0800) != 0) return "Pierce";
|
||||
}
|
||||
return ElementFromName(name);
|
||||
var info = PetElements.Describe(host, deviceId, name);
|
||||
foreach (string e in info.Elements)
|
||||
if (e.Length > 0) return e;
|
||||
return "";
|
||||
}
|
||||
|
||||
public static string ElementFromName(string name)
|
||||
|
|
@ -73,12 +91,45 @@ internal static class PetChoice
|
|||
/// Orders <paramref name="devices"/> (id, name) for summoning against a monster:
|
||||
/// the chosen essence first, or the chosen element's essences first, or (Auto) the
|
||||
/// element the monster takes most damage from. Stable, so ties keep the Items-panel order.
|
||||
/// <paramref name="preferElement"/> is the Summons settings' Pet element ("" = Any);
|
||||
/// <paramref name="defaultElement"/> the Monsters tab Default row's pet damage, for a monster
|
||||
/// with no rule of its own (or one left on Auto).
|
||||
/// </summary>
|
||||
public static List<(int Id, string Name, string Element)> Order(
|
||||
RynthCoreHost host, IEnumerable<(int Id, string Name)> devices, string choice,
|
||||
CreatureData.CreatureWeakness.Ranking? weakness, out string reason, string ruleElement = "")
|
||||
CreatureData.CreatureWeakness.Ranking? weakness, out string reason, string ruleElement = "",
|
||||
string preferElement = "", string defaultElement = "")
|
||||
{
|
||||
var list = devices.Select(d => (d.Id, d.Name, Element: ElementOf(host, unchecked((uint)d.Id), d.Name))).ToList();
|
||||
var list = devices.Select(d => (d.Id, d.Name, Info: PetElements.Describe(host, unchecked((uint)d.Id), d.Name))).ToList();
|
||||
return Order(list, choice, weakness, out reason, ruleElement, preferElement, defaultElement);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// How well an item's pets fit <paramref name="element"/>: 0 every pet deals it (a plain essence of
|
||||
/// it), 1 its first pet does (a holder's first held summon), 2 a later pet does (a holder's second,
|
||||
/// out only when the character can have two pets), 3 none does or none is known.
|
||||
/// </summary>
|
||||
public static int Rank(PetDeviceInfo info, string element)
|
||||
{
|
||||
var e = info.Elements;
|
||||
if (e.Count == 0 || element.Length == 0) return 3;
|
||||
bool first = e[0].Equals(element, StringComparison.OrdinalIgnoreCase);
|
||||
bool all = true;
|
||||
foreach (string x in e)
|
||||
if (!x.Equals(element, StringComparison.OrdinalIgnoreCase)) { all = false; break; }
|
||||
if (all) return 0;
|
||||
if (first) return 1;
|
||||
return info.Has(element) ? 2 : 3;
|
||||
}
|
||||
|
||||
/// <summary>PURE. <see cref="Order(RynthCoreHost, IEnumerable{ValueTuple{int, string}}, string, CreatureData.CreatureWeakness.Ranking?, out string, string, string, string)"/> on described items.</summary>
|
||||
public static List<(int Id, string Name, string Element)> Order(
|
||||
List<(int Id, string Name, PetDeviceInfo Info)> list, string choice,
|
||||
CreatureData.CreatureWeakness.Ranking? weakness, out string reason, string ruleElement = "",
|
||||
string preferElement = "", string defaultElement = "")
|
||||
{
|
||||
static List<(int Id, string Name, string Element)> Out(IEnumerable<(int Id, string Name, PetDeviceInfo Info)> l)
|
||||
=> l.Select(d => (d.Id, d.Name, d.Info.ElementText)).ToList();
|
||||
choice ??= "";
|
||||
|
||||
if (choice.StartsWith("I:", StringComparison.Ordinal)
|
||||
|
|
@ -91,9 +142,10 @@ internal static class PetChoice
|
|||
if (idx >= 0)
|
||||
{
|
||||
var pick = list[idx];
|
||||
list.RemoveAt(idx);
|
||||
list.Insert(0, pick);
|
||||
return list;
|
||||
var rest = new List<(int Id, string Name, PetDeviceInfo Info)>(list);
|
||||
rest.RemoveAt(idx);
|
||||
rest.Insert(0, pick);
|
||||
return Out(rest);
|
||||
}
|
||||
choice = "";
|
||||
}
|
||||
|
|
@ -101,22 +153,35 @@ internal static class PetChoice
|
|||
if (choice.StartsWith("E:", StringComparison.Ordinal))
|
||||
{
|
||||
string want = choice.Substring(2);
|
||||
var ordered = list.OrderBy(d => d.Element.Equals(want, StringComparison.OrdinalIgnoreCase) ? 0 : 1).ToList();
|
||||
reason = ordered.Count > 0 && ordered[0].Element.Equals(want, StringComparison.OrdinalIgnoreCase)
|
||||
var ordered = list.OrderBy(d => Rank(d.Info, want)).ToList();
|
||||
reason = ordered.Count > 0 && Rank(ordered[0].Info, want) < 3
|
||||
? $"{want} chosen" : $"{want} chosen, but no {want} essence; using the first";
|
||||
return ordered;
|
||||
return Out(ordered);
|
||||
}
|
||||
|
||||
// Auto. 1) the Monsters-tab rule's pet damage / damage type for this monster;
|
||||
// 2) the owned element the monster takes most damage from: server data, else
|
||||
// 2) the Summons settings' Pet element; 3) the Default row's pet damage;
|
||||
// 4) the owned element the monster takes most damage from: server data, else
|
||||
// what the Damage tab learned, else its creature type (CreatureWeakness). The
|
||||
// old step read resists ACE never sends and took the lowest, the element the
|
||||
// monster resists most (2026-09-29). Without any of these the Items order stands.
|
||||
var have = new HashSet<string>(list.Where(d => d.Element.Length > 0).Select(d => d.Element), StringComparer.OrdinalIgnoreCase);
|
||||
var have = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var d in list)
|
||||
foreach (string e in d.Info.Elements)
|
||||
if (e.Length > 0) have.Add(e);
|
||||
string autoElem = "";
|
||||
string why = "";
|
||||
string note = "";
|
||||
string re = NormalizeElement(ruleElement);
|
||||
if (re.Length > 0 && have.Contains(re)) { autoElem = re; why = "Monsters rule"; }
|
||||
string pe = NormalizeElement(preferElement);
|
||||
if (autoElem.Length == 0 && pe.Length > 0)
|
||||
{
|
||||
if (have.Contains(pe)) { autoElem = pe; why = "Pet element setting"; }
|
||||
else note = $"Pet element {pe}, but no {pe} essence; ";
|
||||
}
|
||||
string de = NormalizeElement(defaultElement);
|
||||
if (autoElem.Length == 0 && de.Length > 0 && have.Contains(de)) { autoElem = de; why = "Monsters rule"; }
|
||||
if (autoElem.Length == 0 && weakness != null)
|
||||
foreach (var (elem, mult) in weakness.Order)
|
||||
{
|
||||
|
|
@ -128,10 +193,10 @@ internal static class PetChoice
|
|||
|
||||
if (autoElem.Length == 0)
|
||||
{
|
||||
reason = "Auto: no element data for this monster, using Items order";
|
||||
return list;
|
||||
reason = note + "Auto: no element data for this monster, using Items order";
|
||||
return Out(list);
|
||||
}
|
||||
reason = $"Auto: {autoElem} ({why})";
|
||||
return list.OrderBy(d => d.Element.Equals(autoElem, StringComparison.OrdinalIgnoreCase) ? 0 : 1).ToList();
|
||||
reason = $"{note}Auto: {autoElem} ({why})";
|
||||
return Out(list.OrderBy(d => Rank(d.Info, autoElem)));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -44,6 +44,10 @@ internal static class PetDeviceKind
|
|||
{
|
||||
if (host.HasGetObjectWcid && host.TryGetObjectWcid(id, out uint w) && w is >= 787801001 and <= 787801072)
|
||||
return Verdict.Combat; // ACECustom combat essence block
|
||||
// A server's holder of combat summons (PetElements, the server plugin's "summons" rows): a
|
||||
// combat pet device even before it holds anything (the summoner skips it until it is full).
|
||||
if (PetElements.IsHolder(host, id, null))
|
||||
return Verdict.Combat;
|
||||
if (host.HasGetObjectIntProperty)
|
||||
{
|
||||
if (host.TryGetObjectIntProperty(id, IntStructure, out _) || host.TryGetObjectIntProperty(id, IntMaxStructure, out _))
|
||||
|
|
|
|||
186
Plugins/RynthCore.Plugin.RynthAi/Combat/PetElements.cs
Normal file
186
Plugins/RynthCore.Plugin.RynthAi/Combat/PetElements.cs
Normal file
|
|
@ -0,0 +1,186 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
/// <summary>
|
||||
/// What a summoning item brings out, for the combat summoner's element pick: the element of each pet
|
||||
/// one use can bring, in summon order, and whether the item can summon at all.
|
||||
/// </summary>
|
||||
/// <param name="Elements">The element of each pet, in summon order ("" where it isn't known).</param>
|
||||
/// <param name="Held">For a holder: the held items' names, in summon order (empty for a plain essence).</param>
|
||||
/// <param name="IsHolder">The item holds other summoning items (a server's own summon item, ServerSummonView).</param>
|
||||
/// <param name="Ready">The item can summon: a plain essence always; a holder once it holds <paramref name="Slots"/> items.</param>
|
||||
/// <param name="Slots">The items a holder needs before it summons (1 for a plain essence).</param>
|
||||
internal sealed record PetDeviceInfo(IReadOnlyList<string> Elements, IReadOnlyList<string> Held, bool IsHolder, bool Ready, int Slots)
|
||||
{
|
||||
/// <summary>The known elements, joined: "Fire", "Fire+Cold"; "" when none is known.</summary>
|
||||
public string ElementText
|
||||
{
|
||||
get
|
||||
{
|
||||
var known = new List<string>();
|
||||
foreach (string e in Elements)
|
||||
if (e.Length > 0 && !known.Contains(e)) known.Add(e);
|
||||
return string.Join("+", known);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True when one of its pets deals <paramref name="element"/>.</summary>
|
||||
public bool Has(string element)
|
||||
{
|
||||
foreach (string e in Elements)
|
||||
if (e.Length > 0 && e.Equals(element, StringComparison.OrdinalIgnoreCase)) return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a summoning item's elements (<see cref="PetDeviceInfo"/>). A plain essence has one: its
|
||||
/// UiEffects element bits, else words in its name (<see cref="PetChoice.ElementFromName"/>).
|
||||
///
|
||||
/// A "holder" is a server's own summon item that holds other summoning items, named by the active
|
||||
/// server plugin's profile ("summons", <see cref="ServerSummonView"/>; RynthAi names no server). Its
|
||||
/// appraisal description lists the held items ("Summon 1: Fire Moar Essence (180)"); one use brings
|
||||
/// out the first held item's pet, and the next ones' too when the character can have more pets out.
|
||||
/// Each held item's element is read from its name; with "elementIsLast" the item's own UiEffects is
|
||||
/// the last held item's element (the server writes it there). Until it holds every slot it summons
|
||||
/// nothing (<see cref="PetDeviceInfo.Ready"/> false), and the summoner skips it.
|
||||
/// </summary>
|
||||
internal static class PetElements
|
||||
{
|
||||
private const uint IntUiEffects = 18;
|
||||
private const uint IntMaxStructure = 91;
|
||||
private const uint IntStructure = 92;
|
||||
private const uint StringLongDesc = 16;
|
||||
|
||||
private static volatile IReadOnlyList<ServerSummonView> _serverSummons = Array.Empty<ServerSummonView>();
|
||||
|
||||
/// <summary>
|
||||
/// The active server plugin's holder rows (its profile's "summons"; empty without one). Set by the
|
||||
/// Mini Remote's server poll (MiniRemoteContext.PollServer), and by the tests. Any thread.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<ServerSummonView> ServerSummons
|
||||
{
|
||||
get => _serverSummons;
|
||||
set => _serverSummons = value ?? Array.Empty<ServerSummonView>();
|
||||
}
|
||||
|
||||
/// <summary>The element of a UiEffects value's element bits ("" for none).</summary>
|
||||
public static string FromUiEffects(int fx)
|
||||
{
|
||||
if (fx == 0) return "";
|
||||
if ((fx & 0x0020) != 0) return "Fire";
|
||||
if ((fx & 0x0040) != 0) return "Lightning";
|
||||
if ((fx & 0x0080) != 0) return "Cold";
|
||||
if ((fx & 0x0100) != 0) return "Acid";
|
||||
if ((fx & 0x1000) != 0) return "Nether";
|
||||
if ((fx & 0x0200) != 0) return "Bludgeon";
|
||||
if ((fx & 0x0400) != 0) return "Slash";
|
||||
if ((fx & 0x0800) != 0) return "Pierce";
|
||||
return "";
|
||||
}
|
||||
|
||||
/// <summary>The holder row for an item, or null (a plain essence, or no server rows).</summary>
|
||||
public static ServerSummonView? HolderRule(uint wcid, string? name, IReadOnlyList<ServerSummonView>? rules)
|
||||
{
|
||||
if (rules == null) return null;
|
||||
foreach (var r in rules)
|
||||
if (r.Matches(wcid, name)) return r;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The held items' names from a holder's description: each line that starts with
|
||||
/// <paramref name="prefix"/>, a number and ":" ("Summon 2: Frost K'nath Essence (180)"), in order.
|
||||
/// </summary>
|
||||
public static List<string> HeldItems(string? longDesc, string prefix)
|
||||
{
|
||||
var held = new List<string>();
|
||||
if (string.IsNullOrEmpty(longDesc) || string.IsNullOrWhiteSpace(prefix)) return held;
|
||||
foreach (string raw in longDesc.Split('\n'))
|
||||
{
|
||||
string line = raw.Trim();
|
||||
if (!line.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
int i = prefix.Length;
|
||||
while (i < line.Length && line[i] == ' ') i++;
|
||||
int digits = i;
|
||||
while (i < line.Length && char.IsDigit(line[i])) i++;
|
||||
if (i == digits || i >= line.Length || line[i] != ':') continue;
|
||||
string name = line[(i + 1)..].Trim();
|
||||
if (name.Length > 0) held.Add(name);
|
||||
}
|
||||
return held;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// PURE. What an item brings out, from what the client knows of it: its name, wcid (0 = not known),
|
||||
/// UiEffects (0 = none), appraisal description (null = not appraised yet) and whether it carries a
|
||||
/// charge count; <paramref name="rules"/> are the server's holder rows.
|
||||
/// </summary>
|
||||
public static PetDeviceInfo Describe(string? name, uint wcid, int uiEffects, string? longDesc, bool hasCharges,
|
||||
IReadOnlyList<ServerSummonView>? rules)
|
||||
{
|
||||
name ??= "";
|
||||
string own = FromUiEffects(uiEffects);
|
||||
var rule = HolderRule(wcid, name, rules);
|
||||
if (rule == null)
|
||||
{
|
||||
string e = own.Length > 0 ? own : PetChoice.ElementFromName(name);
|
||||
return new PetDeviceInfo(e.Length > 0 ? new[] { e } : Array.Empty<string>(), Array.Empty<string>(), false, true, 1);
|
||||
}
|
||||
|
||||
var held = HeldItems(longDesc, rule.SlotPrefix);
|
||||
var elements = new List<string>(Math.Max(held.Count, rule.Slots));
|
||||
for (int i = 0; i < held.Count; i++)
|
||||
{
|
||||
bool last = i == held.Count - 1 && held.Count >= rule.Slots;
|
||||
string e = last && rule.ElementIsLast && own.Length > 0 ? own : PetChoice.ElementFromName(held[i]);
|
||||
elements.Add(e);
|
||||
}
|
||||
// Not appraised yet (no description): a holder with charges is a full one (the server gives
|
||||
// charges only when it binds); its own element is the last slot's.
|
||||
bool undescribed = string.IsNullOrEmpty(longDesc);
|
||||
if (held.Count == 0 && undescribed && hasCharges)
|
||||
{
|
||||
for (int i = 0; i < rule.Slots; i++)
|
||||
elements.Add(i == rule.Slots - 1 && rule.ElementIsLast ? own : "");
|
||||
}
|
||||
bool ready = held.Count >= rule.Slots || (held.Count == 0 && undescribed && hasCharges);
|
||||
return new PetDeviceInfo(elements, held, true, ready, rule.Slots);
|
||||
}
|
||||
|
||||
/// <summary>What the item <paramref name="id"/> brings out, read from the client (see the pure overload).</summary>
|
||||
public static PetDeviceInfo Describe(RynthCoreHost host, uint id, string? name)
|
||||
{
|
||||
var rules = ServerSummons;
|
||||
uint wcid = 0;
|
||||
if (host.HasGetObjectWcid) host.TryGetObjectWcid(id, out wcid);
|
||||
int fx = 0;
|
||||
bool charges = false;
|
||||
if (host.HasGetObjectIntProperty)
|
||||
{
|
||||
if (!host.TryGetObjectIntProperty(id, IntUiEffects, out fx)) fx = 0;
|
||||
charges = (host.TryGetObjectIntProperty(id, IntMaxStructure, out int max) && max > 0)
|
||||
|| host.TryGetObjectIntProperty(id, IntStructure, out _);
|
||||
}
|
||||
string? desc = null;
|
||||
if (rules.Count > 0 && HolderRule(wcid, name, rules) != null && host.HasGetObjectStringProperty
|
||||
&& host.TryGetObjectStringProperty(id, StringLongDesc, out string d) && !string.IsNullOrWhiteSpace(d))
|
||||
desc = d;
|
||||
return Describe(name, wcid, fx, desc, charges, rules);
|
||||
}
|
||||
|
||||
/// <summary>True when the item is one of the active server's holders (cheap: no description read).</summary>
|
||||
public static bool IsHolder(RynthCoreHost host, uint id, string? name)
|
||||
{
|
||||
var rules = ServerSummons;
|
||||
if (rules.Count == 0) return false;
|
||||
uint wcid = 0;
|
||||
if (host.HasGetObjectWcid) host.TryGetObjectWcid(id, out wcid);
|
||||
if (name == null && host.TryGetObjectName(id, out string n)) name = n;
|
||||
return HolderRule(wcid, name, rules) != null;
|
||||
}
|
||||
}
|
||||
|
|
@ -193,6 +193,8 @@ internal sealed class PetManager
|
|||
private int _landedDeviceId;
|
||||
private long _landedCheckUntil;
|
||||
private readonly HashSet<int> _passivePets = new();
|
||||
// Holders (PetElements) skipped because they don't hold all their summons yet, each logged once.
|
||||
private readonly HashSet<int> _holderNotReadyLogged = new();
|
||||
/// <summary>A listed essence not appraised yet waits this long for its appraisal, once.</summary>
|
||||
private const long AppraisalWaitMs = 3_000;
|
||||
/// <summary>After a summon lands, its essence is judged again this long (its appraisal may still come).</summary>
|
||||
|
|
@ -254,8 +256,9 @@ internal sealed class PetManager
|
|||
// or the summoned creature is now visible in the cache.
|
||||
if (SummonLanded() || IsPetActive())
|
||||
{
|
||||
_summonElement = PetChoice.ElementOf(_host, unchecked((uint)_activeDeviceId),
|
||||
_objectCache[_activeDeviceId]?.Name ?? "");
|
||||
// "Fire", or "Fire+Cold" for a holder of two summons (PetElements).
|
||||
_summonElement = PetElements.Describe(_host, unchecked((uint)_activeDeviceId),
|
||||
_objectCache[_activeDeviceId]?.Name ?? "").ElementText;
|
||||
_summonCooldownUntil = _actionIssuedAt + DeviceUseCooldownMs; // every essence's, not only this one's
|
||||
AssumePetFor(now, AssumeActiveAfterSummonMs);
|
||||
// Judge the essence again now its pet is out: one used before its appraisal landed
|
||||
|
|
@ -472,6 +475,9 @@ internal sealed class PetManager
|
|||
return;
|
||||
}
|
||||
if (HoldSummons?.Invoke() == true) return;
|
||||
// Debuff every monster in range before attacking: the pet comes out once the pass is done, so
|
||||
// its first hits land on debuffed monsters (bounded by the pass's time cap; logged there).
|
||||
if (_combat?.DebuffPassHoldsPets == true) return;
|
||||
|
||||
// Only summon when mobs are near (the user's trigger).
|
||||
if (!MonstersNearby()) return;
|
||||
|
|
@ -836,14 +842,24 @@ internal sealed class PetManager
|
|||
{
|
||||
if (!rule.Type.Equals("Pet", StringComparison.OrdinalIgnoreCase) || string.IsNullOrWhiteSpace(rule.Name)) continue;
|
||||
if (PetDeviceKind.IsNotCombat(_host, unchecked((uint)rule.Id))) continue; // a passive pet's essence names no combat pet
|
||||
string n = rule.Name;
|
||||
int i = n.IndexOf(" Essence", StringComparison.OrdinalIgnoreCase);
|
||||
string b = (i > 0 ? n[..i] : n).Trim();
|
||||
if (b.Length >= 3 && petName.Contains(b, StringComparison.OrdinalIgnoreCase)) return true;
|
||||
if (NamedFor(petName, rule.Name)) return true;
|
||||
// A server's holder ("Duo Summon Gem") is no pet's name: its pets are named for the
|
||||
// summoning items it holds (PetElements), so a pet out after a reload still counts.
|
||||
if (PetElements.IsHolder(_host, unchecked((uint)rule.Id), rule.Name))
|
||||
foreach (string held in PetElements.Describe(_host, unchecked((uint)rule.Id), rule.Name).Held)
|
||||
if (NamedFor(petName, held)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>The pet is named for the essence: "<me>'s Fire Moar" for "Fire Moar Essence (50)".</summary>
|
||||
private static bool NamedFor(string petName, string essenceName)
|
||||
{
|
||||
int i = essenceName.IndexOf(" Essence", StringComparison.OrdinalIgnoreCase);
|
||||
string b = (i > 0 ? essenceName[..i] : essenceName).Trim();
|
||||
return b.Length >= 3 && petName.Contains(b, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// False for a pet the client no longer has (the cache missed its delete) or one the server
|
||||
/// has said nothing about for <see cref="PetGhostSilentMs"/> (a ghost: the client still shows
|
||||
|
|
@ -944,6 +960,21 @@ internal sealed class PetManager
|
|||
foreach (int id in ids)
|
||||
{
|
||||
uint uid = unchecked((uint)id);
|
||||
// A server's holder that doesn't hold all its summons yet summons nothing (the server
|
||||
// refuses it, and the 45 s park would follow): skipped, logged once until it is full.
|
||||
if (PetElements.IsHolder(_host, uid, _objectCache[id]?.Name))
|
||||
{
|
||||
var info = PetElements.Describe(_host, uid, _objectCache[id]?.Name);
|
||||
if (!info.Ready)
|
||||
{
|
||||
if (_holderNotReadyLogged.Count > 64) _holderNotReadyLogged.Clear();
|
||||
if (_holderNotReadyLogged.Add(id))
|
||||
_host.Log($"[RynthAi] Pet: '{_objectCache[id]?.Name ?? "?"}' (0x{uid:X8}) holds {info.Held.Count} of the {info.Slots} summons " +
|
||||
"it needs before it can summon; the combat summoner skips it until it holds them all.");
|
||||
continue;
|
||||
}
|
||||
_holderNotReadyLogged.Remove(id);
|
||||
}
|
||||
var v = PetDeviceKind.IsLearned(id) ? PetDeviceKind.Verdict.NotCombat : PetDeviceKind.Judge(_host, uid);
|
||||
if (v == PetDeviceKind.Verdict.NotCombat)
|
||||
{
|
||||
|
|
@ -1042,15 +1073,19 @@ internal sealed class PetManager
|
|||
// weapon damage type. Same name match combat uses.
|
||||
var rule = _settings.MonsterRules.Find(r => r.Name.Length > 0 && !r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)
|
||||
&& tname.IndexOf(r.Name, StringComparison.OrdinalIgnoreCase) >= 0);
|
||||
// No rule of its own, or one left on Auto: the Default row's pet damage, when it names one.
|
||||
var defaultRow = _settings.MonsterRules.Find(r => r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase));
|
||||
if ((rule == null || (PetChoice.NormalizeElement(rule.PetDamage).Length == 0 && PetChoice.NormalizeElement(rule.DamageType).Length == 0))
|
||||
&& defaultRow != null && PetChoice.NormalizeElement(defaultRow.PetDamage).Length > 0)
|
||||
rule = defaultRow;
|
||||
string ruleElem = rule == null ? "" :
|
||||
(PetChoice.NormalizeElement(rule.PetDamage).Length > 0 ? rule.PetDamage : rule.DamageType);
|
||||
// No rule of its own, or one left on Auto: the Summons settings' Pet element, then the Default
|
||||
// row's pet damage, when it names one (PetChoice.Order).
|
||||
string defaultElem = "";
|
||||
if (PetChoice.NormalizeElement(ruleElem).Length == 0)
|
||||
{
|
||||
ruleElem = "";
|
||||
var defaultRow = _settings.MonsterRules.Find(r => r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase));
|
||||
if (defaultRow != null) defaultElem = defaultRow.PetDamage;
|
||||
}
|
||||
var weak = _combat.WeaknessFor(wcid, tname, target);
|
||||
var ordered = PetChoice.Order(_host, raw, choice, weak, out string why, ruleElem);
|
||||
var ordered = PetChoice.Order(_host, raw, choice, weak, out string why, ruleElem, _settings.PetElement, defaultElem);
|
||||
if (target != _lastChoiceTarget || why != _lastChoiceReason)
|
||||
{
|
||||
_lastChoiceTarget = target;
|
||||
|
|
|
|||
|
|
@ -1505,11 +1505,17 @@ public class WorldObjectCache
|
|||
// buffing ignore it and try every other one. So only a side pack, or the main pack with
|
||||
// the item's own container field set and no wielder, means "in a pack". Buffing's wand
|
||||
// swap puts the weapons into a side pack (the stale-record case of 2026-10-17/18).
|
||||
if (containerId != playerId) _packWalkIds.Add(unchecked((int)itemId));
|
||||
bool inPack = false;
|
||||
if (containerId != playerId) inPack = true;
|
||||
else if (_host.HasGetObjectOwnershipInfo
|
||||
&& _host.TryGetObjectOwnershipInfo(itemId, out uint inContainer, out uint byWielder, out _)
|
||||
&& inContainer != 0 && byWielder == 0)
|
||||
inPack = true;
|
||||
if (inPack)
|
||||
{
|
||||
_packWalkIds.Add(unchecked((int)itemId));
|
||||
NoteHomePack(unchecked((int)itemId), unchecked((int)containerId));
|
||||
}
|
||||
|
||||
if (isContainer && seenContainers.Add(itemId))
|
||||
pendingContainers.Enqueue(itemId);
|
||||
|
|
@ -1553,6 +1559,80 @@ public class WorldObjectCache
|
|||
// both snapshot disciplines: the (cache) overload force-refreshes for the AV-
|
||||
// risky dequip paths (must not read stale); the (inv) overload reuses a caller-
|
||||
// supplied snapshot (AutoCram's single per-tick snapshot — no double BFS).
|
||||
// ── A weapon goes back where it came from (R-20261121-040524-f6ed) ──────────
|
||||
// The pack walk notes the pack each item was last seen in (the main pack = the player's id).
|
||||
// A wand swap put the weapons it took off into the side pack with the most free slots, which
|
||||
// changes as packs fill: "it randomly throws them into pack 1, 2 or 4". Now the swaps ask for
|
||||
// the pack the weapon came from first.
|
||||
private readonly Dictionary<int, int> _homePack = new();
|
||||
|
||||
private void NoteHomePack(int itemId, int containerId)
|
||||
{
|
||||
if (_homePack.Count >= 4096) _homePack.Clear(); // a bound, not a cut: inventories hold a few hundred
|
||||
_homePack[itemId] = containerId;
|
||||
}
|
||||
|
||||
/// <summary>The pack <paramref name="itemId"/> was last seen in (the player's id = the main pack), or 0.</summary>
|
||||
public int HomePackOf(int itemId)
|
||||
{
|
||||
lock (_gate) return _homePack.TryGetValue(itemId, out int p) ? p : 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// As <see cref="FindPackFor(RynthCoreHost, WorldObjectCache?, bool, int)"/>, for putting
|
||||
/// <paramref name="forItems"/> away: the pack they all came from when it still has
|
||||
/// <paramref name="requireFree"/> free slots (the main pack only with <paramref name="includeMainPack"/>),
|
||||
/// else the usual choice.
|
||||
/// </summary>
|
||||
public static int FindPackFor(RynthCoreHost host, WorldObjectCache? cache,
|
||||
bool includeMainPack, int requireFree, IReadOnlyList<int> forItems)
|
||||
{
|
||||
if (cache == null) return 0;
|
||||
int playerId = unchecked((int)host.GetPlayerId());
|
||||
if (playerId == 0) return 0;
|
||||
var inv = cache.GetDirectInventory(forceRefresh: true);
|
||||
int home = 0;
|
||||
foreach (int id in forItems)
|
||||
{
|
||||
int h = id == 0 ? 0 : cache.HomePackOf(id);
|
||||
if (h == 0 || (home != 0 && h != home)) { home = 0; break; }
|
||||
home = h;
|
||||
}
|
||||
if (home != 0 && (home != playerId || includeMainPack)
|
||||
&& FreeSlotsIn(inv, playerId, home, host) >= Math.Max(1, requireFree))
|
||||
return home;
|
||||
return FindPackFor(inv, playerId, includeMainPack, requireFree, host);
|
||||
}
|
||||
|
||||
/// <summary>Free item slots in one of the player's packs (the player's id = the main pack), or -1 when unknown.</summary>
|
||||
internal static int FreeSlotsIn(IReadOnlyList<WorldObject> inv, int playerId, int packId, RynthCoreHost? host)
|
||||
{
|
||||
if (packId == playerId)
|
||||
{
|
||||
int mainUsed = 0;
|
||||
foreach (var p in inv)
|
||||
{
|
||||
if (p.Container != playerId) continue;
|
||||
if (p.ObjectClass == AcObjectClass.Container || p.ObjectClass == AcObjectClass.Foci) continue;
|
||||
if (p.Values(LongValueKey.EquippedSlots, 0) != 0) continue;
|
||||
if (host.HasValue && IsWieldable(p) && IsWieldedByPlayer(host.Value, p)) continue;
|
||||
mainUsed++;
|
||||
}
|
||||
return 102 - mainUsed;
|
||||
}
|
||||
WorldObject? pack = null;
|
||||
foreach (var p in inv)
|
||||
if (p.Id == packId) { pack = p; break; }
|
||||
if (pack == null || pack.ObjectClass != AcObjectClass.Container || pack.Container != playerId) return -1;
|
||||
if (!string.IsNullOrEmpty(pack.Name) && pack.Name.IndexOf("Foci", StringComparison.OrdinalIgnoreCase) >= 0) return -1;
|
||||
int capacity = pack.Values(LongValueKey.ItemsCapacity, 0);
|
||||
if (capacity <= 0) return -1;
|
||||
int used = 0;
|
||||
foreach (var it in inv)
|
||||
if (it.Container == packId && it.ObjectClass != AcObjectClass.Container) used++;
|
||||
return capacity - used;
|
||||
}
|
||||
|
||||
public static int FindPackFor(RynthCoreHost host, WorldObjectCache? cache,
|
||||
bool includeMainPack, int requireFree)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -562,7 +562,7 @@ public sealed partial class RynthAiPlugin
|
|||
{
|
||||
_processedCorpseItems.Clear();
|
||||
_corpseItemAttempts.Clear();
|
||||
_pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear();
|
||||
_pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear(); _pendingPerDay.Clear();
|
||||
}
|
||||
LootDiag($"[RynthAi] Corpse loot: opened container 0x{objectId:X8}.");
|
||||
_consecutiveLootTimeouts = 0; // a successful open proves AC is responsive again
|
||||
|
|
@ -760,6 +760,7 @@ public sealed partial class RynthAiPlugin
|
|||
|
||||
SyncCorpseContainerState();
|
||||
WatchLateLandings(CorpseNowMs);
|
||||
PrunePerDay();
|
||||
TickDeferredClose(settings);
|
||||
TakeLootThisRequest(settings); // /ra lootthis (RynthAiPlugin.VTankHotkeys.cs)
|
||||
TakeChestKeyRequest(); // the Item Tool's chest looter (RynthAiPlugin.ItemTool.cs)
|
||||
|
|
@ -1226,6 +1227,8 @@ public sealed partial class RynthAiPlugin
|
|||
|
||||
_corpseCooldownUntil.Remove(candidate.Id);
|
||||
}
|
||||
if (StillBehindWall(candidate.Id, now)) // set aside behind a wall, and the wall is still there
|
||||
continue;
|
||||
|
||||
CorpseLootDecision decision = EvaluateCorpseLootDecision(candidate);
|
||||
if (!decision.ShouldLoot)
|
||||
|
|
@ -1387,6 +1390,23 @@ public sealed partial class RynthAiPlugin
|
|||
}
|
||||
}
|
||||
|
||||
// Loot Only Rare Corpses: only a corpse that generated a rare is opened (VTank's option). The
|
||||
// ownership rules below still apply to it.
|
||||
if (settings.LootOnlyRareCorpses && RareCorpseRefusal(longDesc) is { } notRare)
|
||||
{
|
||||
return new CorpseLootDecision
|
||||
{
|
||||
ShouldLoot = false,
|
||||
ModeName = modeName,
|
||||
Reason = notRare,
|
||||
KillerName = killerName,
|
||||
PlayerName = myName,
|
||||
LongDesc = longDesc,
|
||||
InFellowship = inFellowship,
|
||||
KillerIsFellow = killerIsFellow
|
||||
};
|
||||
}
|
||||
|
||||
if (lootOwnership >= 2)
|
||||
{
|
||||
return new CorpseLootDecision
|
||||
|
|
@ -1555,6 +1575,13 @@ public sealed partial class RynthAiPlugin
|
|||
int lineEnd = remainder.IndexOfAny(new[] { '\r', '\n' });
|
||||
if (lineEnd >= 0)
|
||||
remainder = remainder[..lineEnd];
|
||||
// A corpse that generated a rare reads "Killed by <name>. This corpse generated a rare item!"
|
||||
// (ACE appends the sentence on the same line). Read whole, the killer was "<name>. This corpse
|
||||
// generated a rare item!", so My Kills Only never matched the player and every rare corpse of
|
||||
// their own kills was left unopened (2026-11-22).
|
||||
int rare = remainder.IndexOf(RareCorpseText, StringComparison.OrdinalIgnoreCase);
|
||||
if (rare >= 0)
|
||||
remainder = remainder[..rare];
|
||||
remainder = remainder.Trim().TrimEnd('.').Trim();
|
||||
return remainder.Length == 0 ? null : remainder;
|
||||
}
|
||||
|
|
@ -2033,6 +2060,8 @@ public sealed partial class RynthAiPlugin
|
|||
// is in the pack. Noted on send for the same reason as salvage above.
|
||||
if (matchActionLabel == ScrollLearner.ReadAction)
|
||||
_scrollLearner?.NoteLooted(firstMatchId, matchItemName, fromProfile: matchRuleLabel != ScrollLearner.RuleLabel);
|
||||
// Keep # per day: on its way, so it counts until it lands (then it is recorded).
|
||||
NotePerDaySent(firstMatchId);
|
||||
_currentLootItemMovePending = true;
|
||||
_currentLootItemMoveRequestedAt = now;
|
||||
// A queued move that the client or server turned away (the client's one-request
|
||||
|
|
@ -2458,6 +2487,7 @@ public sealed partial class RynthAiPlugin
|
|||
{
|
||||
bool wasMarked = _packRefusals.IsRefused(container, now);
|
||||
_packRefusals.Accepted(container);
|
||||
NotePerDayPickedUp(kv.Key); // a Keep # per day item that landed late still counts
|
||||
LootDiag($"[RynthAi] {LootTag}: 0x{(uint)kv.Key:X8} landed in {LootPackName(container)} {now - kv.Value.SentAt} ms after its last send, after it was given up" +
|
||||
(wasMarked ? $"; {LootPackName(container)} has room after all and is no longer treated as full." : "."));
|
||||
(done ??= new()).Add(kv.Key);
|
||||
|
|
@ -3093,6 +3123,7 @@ public sealed partial class RynthAiPlugin
|
|||
if (answered) _currentLootItemDestsTried.Clear(); // landed: nothing to watch for (ResetCurrentLootItem)
|
||||
_processedCorpseItems.Add(_currentLootItemId);
|
||||
_corpseItemsLooted++;
|
||||
NotePerDayPickedUp(itemId); // Keep # per day: it left the corpse into the pack
|
||||
bool noMotion = answered && JumpPickupHadNoMotion();
|
||||
long jumpSentAt = _currentLootItemMoveRequestedAt;
|
||||
LootDiag($"[RynthAi] {LootTag}: pickup confirmed for 0x{(uint)_currentLootItemId:X8}; {reason}" +
|
||||
|
|
@ -3419,6 +3450,8 @@ public sealed partial class RynthAiPlugin
|
|||
continue;
|
||||
if (_corpseCooldownUntil.TryGetValue(candidate.Id, out long blockedUntil) && blockedUntil > now)
|
||||
continue;
|
||||
if (StillBehindWall(candidate.Id, now)) // set aside behind a wall, and the wall is still there
|
||||
continue;
|
||||
CorpseLootDecision decision = EvaluateCorpseLootDecision(candidate);
|
||||
if (!decision.ShouldLoot)
|
||||
continue;
|
||||
|
|
@ -3448,11 +3481,13 @@ public sealed partial class RynthAiPlugin
|
|||
/// <summary>
|
||||
/// The arbiter's LootStarved input: looting wants the tick, combat wants it too, a corpse
|
||||
/// has waited LootStarveMs (HasLootWork set _lootStarved this tick), and no monster is
|
||||
/// within LootStarveCloseYards. Melee fights keep combat in charge (the mob is on you).
|
||||
/// within LootStarveCloseYards. Melee fights keep combat in charge (the mob is on you), and so
|
||||
/// does a monster in the scan that is hitting us from farther off (2026-11-22, IsBeingHitByScanned).
|
||||
/// </summary>
|
||||
private bool IsLootStarvedTurn(bool wantLoot, bool wantCombat)
|
||||
=> wantLoot && wantCombat && _lootStarved
|
||||
&& _combatManager?.HasCloseThreat(LootStarveCloseYards) != true;
|
||||
&& _combatManager?.HasCloseThreat(LootStarveCloseYards) != true
|
||||
&& _combatManager?.IsBeingHitByScanned != true;
|
||||
|
||||
// -- Boost Loot Priority: one kill, one loot (2026-10-14) --------------------------------
|
||||
// Combat locked its next target a few ms after each kill, and ACE creates the corpse 1-3 s
|
||||
|
|
@ -3634,7 +3669,14 @@ public sealed partial class RynthAiPlugin
|
|||
if (nativeAction == LootAction.KeepUpTo)
|
||||
{
|
||||
var rule = nativeRule;
|
||||
if (!UnderKeepCap("n:" + ruleLabel, ruleLabel, item, rule.KeepCount,
|
||||
int perDay = LootPerDay.Clamp(rule.PerDayHours);
|
||||
if (perDay > 0)
|
||||
{
|
||||
// Keep # per day: counted by pickups in the window, not by the pack.
|
||||
if (!UnderDailyCap(LootPerDay.Key(rule.Name, nativeProfile.Rules.IndexOf(rule)), ruleLabel, item, rule.KeepCount, perDay, preview))
|
||||
return false;
|
||||
}
|
||||
else if (!UnderKeepCap("n:" + ruleLabel, ruleLabel, item, rule.KeepCount,
|
||||
inv => LootEvaluator.Matches(rule, inv, _charSkills), preview))
|
||||
return false;
|
||||
}
|
||||
|
|
@ -3670,7 +3712,14 @@ public sealed partial class RynthAiPlugin
|
|||
if (matchedRule.Action == VTankLootAction.KeepUpTo)
|
||||
{
|
||||
var rule = matchedRule;
|
||||
if (!UnderKeepCap("v:" + matchedRuleIndex + ":" + ruleLabel, ruleLabel, item, rule.KeepCount ?? 0,
|
||||
int perDay = LootPerDay.Clamp(rule.PerDayHours);
|
||||
if (perDay > 0)
|
||||
{
|
||||
// Keep # per day: counted by pickups in the window, not by the pack.
|
||||
if (!UnderDailyCap(LootPerDay.Key(rule.Name, matchedRuleIndex), ruleLabel, item, rule.KeepCount ?? 0, perDay, preview))
|
||||
return false;
|
||||
}
|
||||
else if (!UnderKeepCap("v:" + matchedRuleIndex + ":" + ruleLabel, ruleLabel, item, rule.KeepCount ?? 0,
|
||||
inv => VTankLootEvaluator.Match(rule, inv, lootCtx), preview))
|
||||
return false;
|
||||
}
|
||||
|
|
@ -4132,7 +4181,7 @@ public sealed partial class RynthAiPlugin
|
|||
_corpseItemAttempts.Clear();
|
||||
_corpseIdsRequested = false;
|
||||
_corpseItemIdReaskedAt.Clear();
|
||||
_pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear();
|
||||
_pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear(); _pendingPerDay.Clear();
|
||||
ResetCurrentLootItem();
|
||||
|
||||
// Close the loot window (CloseCorpseContainer: the client's own close packet, which
|
||||
|
|
@ -4317,6 +4366,9 @@ public sealed partial class RynthAiPlugin
|
|||
private bool AttemptOpenCorpse(int corpseId)
|
||||
{
|
||||
long now = CorpseNowMs;
|
||||
// A re-send for a corpse that didn't open, with a wall in the way: set aside (RynthAiPlugin.CorpseBehindWall.cs).
|
||||
if (SetAsideBehindWall(corpseId, now))
|
||||
return false;
|
||||
bool watch = Host.HasUseDoneSeq;
|
||||
if (watch)
|
||||
{
|
||||
|
|
@ -4592,7 +4644,7 @@ public sealed partial class RynthAiPlugin
|
|||
{
|
||||
_processedCorpseItems.Clear();
|
||||
_corpseItemAttempts.Clear();
|
||||
_pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear();
|
||||
_pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear(); _pendingPerDay.Clear();
|
||||
}
|
||||
|
||||
_targetCorpseId = rawOpen;
|
||||
|
|
@ -4632,7 +4684,7 @@ public sealed partial class RynthAiPlugin
|
|||
ResetCurrentLootItem();
|
||||
_processedCorpseItems.Clear();
|
||||
_corpseItemAttempts.Clear();
|
||||
_pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear();
|
||||
_pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear(); _pendingPerDay.Clear();
|
||||
}
|
||||
|
||||
private void HandleCorpseObjectDeleted(uint objectId)
|
||||
|
|
|
|||
|
|
@ -90,6 +90,8 @@ internal interface IDashboardHost
|
|||
bool AutoSortMoving { get; }
|
||||
/// <summary>Fight the monster I select (combat setting), for the options menu's toggle.</summary>
|
||||
bool FightSelectedTarget { get; }
|
||||
/// <summary>Debuff every monster in range before attacking (combat setting), for the options menu's toggle.</summary>
|
||||
bool DebuffAllBeforeAttacking { get; }
|
||||
void SetAutoSort(bool on);
|
||||
/// <summary>RynthSort's own window, shown or hidden.</summary>
|
||||
void ToggleSortWindow();
|
||||
|
|
@ -1143,6 +1145,17 @@ internal sealed unsafe class InstrumentDashboard
|
|||
ImGui.CloseCurrentPopup();
|
||||
_d.Command("/ra fightselected");
|
||||
}
|
||||
// Debuff every monster in range before attacking (also Settings > Combat > Targeting): a
|
||||
// toggle, the command's reply says the new state.
|
||||
bool debuffAll = _d.DebuffAllBeforeAttacking;
|
||||
if (MenuItem(dl, ref p, w, "##m_debuffall", RynthIcons.Flask,
|
||||
"Debuff every monster first", debuffAll ? "ON" : "OFF",
|
||||
"Casts each monster's Monsters-rule debuffs on every monster in range, nearest first, before attacking any\n" +
|
||||
"(/ra debuffall). Click to turn it " + (debuffAll ? "off." : "on.")))
|
||||
{
|
||||
ImGui.CloseCurrentPopup();
|
||||
_d.Command("/ra debuffall");
|
||||
}
|
||||
// Which worn items have their magic on (RynthAiPlugin.ActiveGear.cs): its own window, no bar button.
|
||||
if (MenuItem(dl, ref p, w, "##m_gear", RynthIcons.BatteryCharging, "Active gear", "/ra gear",
|
||||
"Which worn items have their magic on, their mana and how long it lasts (the Active Gear window)."))
|
||||
|
|
|
|||
|
|
@ -47,6 +47,7 @@ internal enum TickStep
|
|||
AutoVendor,
|
||||
AutoTrade,
|
||||
WeaponElements,
|
||||
AutoKits,
|
||||
CramStack,
|
||||
InventoryStatus,
|
||||
CombatTelemetry,
|
||||
|
|
@ -138,6 +139,7 @@ internal sealed class TickGuard
|
|||
Add(TickStep.AutoVendor, "AutoVendor", LogCat.Vendor);
|
||||
Add(TickStep.AutoTrade, "AutoTrade", LogCat.Vendor);
|
||||
Add(TickStep.WeaponElements, "weapon elements", LogCat.Combat);
|
||||
Add(TickStep.AutoKits, "make kits when low", LogCat.Crafting);
|
||||
Add(TickStep.CramStack, "AutoCram/AutoStack", LogCat.Inventory);
|
||||
Add(TickStep.InventoryStatus, "inventory status", LogCat.Inventory);
|
||||
Add(TickStep.CombatTelemetry, "combat telemetry", LogCat.Combat);
|
||||
|
|
|
|||
|
|
@ -41,6 +41,38 @@ internal sealed class DungeonDoorway
|
|||
public (double Nx, double Ny) NormalFrom(uint fromCell) => fromCell == CellA ? (Nx, Ny) : (-Nx, -Ny);
|
||||
}
|
||||
|
||||
/// <summary>What a placed object is to a body on the floor it stands on (DungeonGeometry's placed objects).</summary>
|
||||
internal enum PlacedClass
|
||||
{
|
||||
/// <summary>In the body band, and nothing else here: walked round.</summary>
|
||||
Obstacle,
|
||||
/// <summary>Its top no more than the step-up (0.60 m) over its floor, with somewhere to stand on it.</summary>
|
||||
StepOver,
|
||||
/// <summary>Walkable faces climbed onto from its floor reaching 1 m and more (stairs, ramps, platforms), or a slab that is a floor the map lacks.</summary>
|
||||
Connector,
|
||||
/// <summary>All of it under the band (under its floor + 0.45 m).</summary>
|
||||
Low,
|
||||
/// <summary>All of it over the band (over its floor + 1.83 m).</summary>
|
||||
Overhead,
|
||||
/// <summary>Nothing of it in the band, though it reaches both under and over it (an arch's beam with no posts).</summary>
|
||||
Clear,
|
||||
}
|
||||
|
||||
/// <summary>One placed object as the map took it: model, cell, class, whether it went on the map, world box, its floor (L),
|
||||
/// whether that floor is the map's, its footprint at L (m2), and where it came from.</summary>
|
||||
internal readonly record struct PlacedInfo(uint Setup, uint Cell, PlacedClass Class, bool OnMap,
|
||||
double MinX, double MinY, double MinZ, double MaxX, double MaxY, double MaxZ,
|
||||
double Floor, bool FloorFound, double FootprintArea, string Source);
|
||||
|
||||
/// <summary>Which placed objects go on the map, and the tag their layer gets.</summary>
|
||||
internal sealed record PlacedObjectOptions
|
||||
{
|
||||
/// <summary>Null: obstacles, step-overs and connectors (whatever is in the body band at its floor).</summary>
|
||||
public Func<PlacedInfo, bool>? Keep { get; init; }
|
||||
/// <summary>Where the objects came from ("dats" for the base layer by default).</summary>
|
||||
public string? Source { get; init; }
|
||||
}
|
||||
|
||||
internal sealed class DungeonGeometry
|
||||
{
|
||||
/// <summary>An opening at least this wide joins two cells of one room (a 10 m cell side is
|
||||
|
|
@ -126,7 +158,7 @@ internal sealed class DungeonGeometry
|
|||
if (!IsUpwardFloor(v)) continue; // the "floor" list holds ceilings too
|
||||
if (!g._floors.TryGetValue(cell, out var list)) g._floors[cell] = list = new List<Vector3[]>();
|
||||
list.Add(v);
|
||||
g.AddFloorToGrid(v);
|
||||
g.AddFloorToGrid(v, cell);
|
||||
}
|
||||
|
||||
foreach (var (cell, v) in wallPolys)
|
||||
|
|
@ -297,6 +329,9 @@ internal sealed class DungeonGeometry
|
|||
|
||||
public bool TryGetDoorway(uint a, uint b, out DungeonDoorway door) => _doorways.TryGetValue(EdgeKey(a, b), out door!);
|
||||
|
||||
/// <summary>Every opening paired between two cells (the jump-downs look at them all: a closed ledge is gone from the graph, not from here).</summary>
|
||||
internal IEnumerable<DungeonDoorway> AllDoorways => _doorways.Values;
|
||||
|
||||
/// <summary>Openings whose centre is within r (horizontally) of (x, y) and <paramref name="dz"/> of height z.</summary>
|
||||
public IEnumerable<DungeonDoorway> DoorwaysNear(double x, double y, double z, double r, double dz = 2.0)
|
||||
{
|
||||
|
|
@ -401,20 +436,25 @@ internal sealed class DungeonGeometry
|
|||
}
|
||||
}
|
||||
|
||||
// Walls.
|
||||
// Walls (the cells' own and the placed objects' filed under them; an overlay's too).
|
||||
double zLo = Math.Min(z0, z1) + WallBandLow, zHi = Math.Max(z0, z1) + WallBandHigh;
|
||||
foreach (uint c in cells)
|
||||
bool Crossed(Dictionary<uint, List<WallSeg>> byCell)
|
||||
{
|
||||
if (!_walls.TryGetValue(c, out var list)) continue;
|
||||
foreach (var w in list)
|
||||
foreach (uint c in cells)
|
||||
{
|
||||
if (w.ZMax < zLo || w.ZMin > zHi) continue;
|
||||
if (SegmentsCross(x0, y0, x1, y1, w.X0, w.Y0, w.X1, w.Y1)) return false;
|
||||
if (SegmentsCross(x0 + ox, y0 + oy, x1 + ox, y1 + oy, w.X0, w.Y0, w.X1, w.Y1)) return false;
|
||||
if (SegmentsCross(x0 - ox, y0 - oy, x1 - ox, y1 - oy, w.X0, w.Y0, w.X1, w.Y1)) return false;
|
||||
if (!byCell.TryGetValue(c, out var list)) continue;
|
||||
foreach (var w in list)
|
||||
{
|
||||
if (w.ZMax < zLo || w.ZMin > zHi) continue;
|
||||
if (SegmentsCross(x0, y0, x1, y1, w.X0, w.Y0, w.X1, w.Y1)) return true;
|
||||
if (SegmentsCross(x0 + ox, y0 + oy, x1 + ox, y1 + oy, w.X0, w.Y0, w.X1, w.Y1)) return true;
|
||||
if (SegmentsCross(x0 - ox, y0 - oy, x1 - ox, y1 - oy, w.X0, w.Y0, w.X1, w.Y1)) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
if (Crossed(_walls)) return false;
|
||||
return _placedOverlay == null || !Crossed(_placedOverlay.CellWalls);
|
||||
}
|
||||
|
||||
// ── Clearance from walls ────────────────────────────────────────────────
|
||||
|
|
@ -446,18 +486,19 @@ internal sealed class DungeonGeometry
|
|||
public double Nx, Ny, Nz, Px, Py, Pz; // unit normal and a point on the plane
|
||||
public double MinX, MinY, MaxX, MaxY;
|
||||
public bool Walkable;
|
||||
public uint Cell; // the cell it is the floor of (a placed object's walls go to it too)
|
||||
public double HeightAt(double x, double y) => Pz - (Nx * (x - Px) + Ny * (y - Py)) / Nz;
|
||||
}
|
||||
|
||||
private static long GridKey(int gx, int gy) => ((long)gx << 32) ^ (uint)gy;
|
||||
private static int GridOf(double v) => (int)Math.Floor(v / GridCell);
|
||||
|
||||
private void AddFloorToGrid(Vector3[] v)
|
||||
private void AddFloorToGrid(Vector3[] v, uint cell)
|
||||
{
|
||||
NewellNormal(v, out double nx, out double ny, out double nz);
|
||||
double len = Math.Sqrt(nx * nx + ny * ny + nz * nz);
|
||||
if (len < 1e-9 || nz <= 1e-9) return;
|
||||
var f = new FloorPoly { V = v, Nx = nx / len, Ny = ny / len, Nz = nz / len, MinX = double.MaxValue, MinY = double.MaxValue, MaxX = double.MinValue, MaxY = double.MinValue };
|
||||
var f = new FloorPoly { V = v, Cell = cell, Nx = nx / len, Ny = ny / len, Nz = nz / len, MinX = double.MaxValue, MinY = double.MaxValue, MaxX = double.MinValue, MaxY = double.MinValue };
|
||||
double sx = 0, sy = 0, sz = 0;
|
||||
foreach (var p in v)
|
||||
{
|
||||
|
|
@ -478,15 +519,17 @@ internal sealed class DungeonGeometry
|
|||
}
|
||||
}
|
||||
|
||||
private void AddWallToGrid(WallSeg w)
|
||||
private void AddWallToGrid(WallSeg w) => AddWallTo(_wallAll, _wallGrid, w);
|
||||
|
||||
private static void AddWallTo(List<WallSeg> all, Dictionary<long, List<int>> grid, WallSeg w)
|
||||
{
|
||||
int idx = _wallAll.Count;
|
||||
_wallAll.Add(w);
|
||||
int idx = all.Count;
|
||||
all.Add(w);
|
||||
for (int gx = GridOf(Math.Min(w.X0, w.X1)); gx <= GridOf(Math.Max(w.X0, w.X1)); gx++)
|
||||
for (int gy = GridOf(Math.Min(w.Y0, w.Y1)); gy <= GridOf(Math.Max(w.Y0, w.Y1)); gy++)
|
||||
{
|
||||
long k = GridKey(gx, gy);
|
||||
if (!_wallGrid.TryGetValue(k, out var list)) _wallGrid[k] = list = new List<int>();
|
||||
if (!grid.TryGetValue(k, out var list)) grid[k] = list = new List<int>();
|
||||
list.Add(idx);
|
||||
}
|
||||
}
|
||||
|
|
@ -537,6 +580,7 @@ internal sealed class DungeonGeometry
|
|||
if (FloorNear(x, y, z)) return 0; // past the floor's edge: in or behind a wall
|
||||
h0 = z;
|
||||
}
|
||||
if (InsidePlaced(x, y, h0)) return 0; // inside an altar or a statue: its middle is far from its sides
|
||||
double best = maxR;
|
||||
for (int k = 0; k < ProbeDirs && best > 0; k++)
|
||||
{
|
||||
|
|
@ -546,6 +590,371 @@ internal sealed class DungeonGeometry
|
|||
return Math.Min(best, WallDistance(x, y, h0 + ClearWallLow, h0 + ClearWallHigh, best));
|
||||
}
|
||||
|
||||
// ── Placed objects (2026-11-18) ─────────────────────────────────────────
|
||||
//
|
||||
// What a dungeon's cells place (an altar, a statue, a pillar: the EnvCells' stabs) isn't in the cells'
|
||||
// walls and floors, so walks went through them. Thread 0x000A ("It also still doesn't see world
|
||||
// objects such as this altar it tried to run through"): an explore leg ran straight through a 1 m altar
|
||||
// in a hall, the character stuck there in a fight and died, four times in one run. Thread 0x00C1: a
|
||||
// room's middle (a look-in point) inside a 9 x 9 m statue.
|
||||
//
|
||||
// Each object is a solid model (PlacedSolid: 0.1 m columns, each with the heights where it is solid),
|
||||
// measured against a body: from the feet + PlacedBandLow (the map's step) to the top of the human setup's
|
||||
// upper sphere (PlacedBandHigh, 1.83 m). At the floor it stands on (L) that gives its footprint. The
|
||||
// footprint's outline is walls from L + 0.45 to L + 1.83 (within the object's own height): every clearance
|
||||
// measure sees them, so the corner put into a leg brushing a wall, the straightener, the walk round a hole
|
||||
// and the stuck detours go round. They are filed under every cell whose floor the footprint covers, so a
|
||||
// straight line over the next cell sees an object reaching into it. A point is
|
||||
// inside an object when, for a walker on the floor there, something of it is between that floor + 0.45 and
|
||||
// + 1.83: a table's top counts all over (not only at its legs), a rail at 0.8 m closes, an arch's beam
|
||||
// overhead and a block whose top is the floor walked on (a door sill's) don't, nor does anything on a floor
|
||||
// 4 m up or down. An open plane (a fence, a web) is its line, never a filled area.
|
||||
//
|
||||
// Classes, at L: LOW (all of it under the band), OVERHEAD (all of it over), CLEAR (nothing of it in the
|
||||
// band either way: an arch with no posts), STEP-OVER (top no more than the step-up, 0.60 m, over L, with a
|
||||
// top to stand on), CONNECTOR (walkable faces a body could climb onto, 0.6 m at most at a time, from L and
|
||||
// across other objects, reaching 1 m and more over L: stairs, ramps, platforms; or a slab that is a floor
|
||||
// the map lacks), OBSTACLE (the rest). Only what is in the band at L goes on the map. Step-overs and
|
||||
// connectors still do in this wave (the 0.60 m step-up isn't proven in game; taking a ramp's sides out was
|
||||
// measured wrong in 0x0174), but they are tagged, for a map that leaves them out (AddPlacedObjects' options).
|
||||
//
|
||||
// The dats' objects sit in the base layer. A second, replaceable layer (objects found at run time, tagged
|
||||
// with where they came from) joins it through SetPlacedOverlay and leaves through ClearPlacedOverlay, with
|
||||
// walls of its own, without the base being built again.
|
||||
|
||||
/// <summary>The body a placed object is measured against, over the floor a walker stands on: from the map's
|
||||
/// own step (ClearWallLow) to the top of the human setup 0x02000001's upper sphere (1.35 + 0.48).</summary>
|
||||
internal const double PlacedBandLow = 0.45, PlacedBandHigh = 1.83;
|
||||
/// <summary>The human setup's step-up height: an object no taller over its floor, with a top to stand on, is a step-over.</summary>
|
||||
internal const double StepOverTop = 0.60;
|
||||
// Connector chain: a step up at most this high between walkable faces at most this far apart (a step down
|
||||
// any small drop), reaching at least this high over the object's floor.
|
||||
private const double ConnectorRise = 0.6, ConnectorGap = 0.3, ConnectorDrop = 1.5, ConnectorReach = 1.0;
|
||||
// A slab: walkable faces this big (m2), raised this far over its floor (or no floor under it), and the map
|
||||
// has no floor within SlabFloorNear of most of them.
|
||||
private const double SlabArea = 1.0, SlabRaised = 1.0, SlabFloorNear = 0.3;
|
||||
// The floor an object stands on is looked for this far over and under its lowest point.
|
||||
private const double PlacedFloorSearchUp = 2.0, PlacedFloorSearchDown = 3.0;
|
||||
// A cell's floor this near an object's floor, under its footprint, gets the object's walls too.
|
||||
private const double PlacedCellFloorBand = 2.0;
|
||||
|
||||
private sealed class PlacedObj
|
||||
{
|
||||
public uint Setup, Cell;
|
||||
public PlacedShape Shape = null!;
|
||||
public PlacedBand Band = null!;
|
||||
public double Floor, ReachHigh = double.NegativeInfinity;
|
||||
public bool FloorFound, OnMap;
|
||||
public PlacedClass Class;
|
||||
public string Source = "";
|
||||
|
||||
public PlacedInfo Info => new(Setup, Cell, Class, OnMap, Shape.MinX, Shape.MinY, Shape.MinZ, Shape.MaxX, Shape.MaxY, Shape.MaxZ,
|
||||
Floor, FloorFound, Band.Area, Source);
|
||||
}
|
||||
|
||||
// One list of placed objects with its grid. The base layer's walls are the map's walls; an overlay keeps its own.
|
||||
private sealed class PlacedLayer
|
||||
{
|
||||
public readonly string Source;
|
||||
public readonly bool OwnWalls;
|
||||
public readonly List<PlacedObj> All = new();
|
||||
public readonly List<PlacedObj> OnMap = new();
|
||||
public readonly Dictionary<long, List<int>> Grid = new();
|
||||
public readonly List<WallSeg> Walls = new();
|
||||
public readonly Dictionary<long, List<int>> WallGrid = new();
|
||||
public readonly Dictionary<uint, List<WallSeg>> CellWalls = new();
|
||||
public PlacedLayer(string source, bool ownWalls) { Source = source; OwnWalls = ownWalls; }
|
||||
}
|
||||
|
||||
private readonly PlacedLayer _placedBase = new("dats", ownWalls: false);
|
||||
private PlacedLayer? _placedOverlay;
|
||||
|
||||
/// <summary>How many placed objects stand in the way at body height (on the map, both layers).</summary>
|
||||
public int PlacedCount => _placedBase.OnMap.Count + (_placedOverlay?.OnMap.Count ?? 0);
|
||||
|
||||
/// <summary>Every placed object given to the map (both layers), with its class, whether it went on the map, its box and floor.</summary>
|
||||
internal IReadOnlyList<PlacedInfo> PlacedObjects
|
||||
{
|
||||
get
|
||||
{
|
||||
var list = new List<PlacedInfo>(_placedBase.All.Count + (_placedOverlay?.All.Count ?? 0));
|
||||
foreach (var layer in PlacedLayers())
|
||||
foreach (var p in layer.All) list.Add(p.Info);
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the objects the cells place, each as its triangles in world metres (three vertices a triangle, closed or
|
||||
/// open), to the base layer: each one's footprint in the body band at its floor becomes walls, and inside it is no
|
||||
/// room. What isn't in the band there (or what <paramref name="options"/> leaves out) goes on the list only.
|
||||
/// Returns how many went on the map.
|
||||
/// </summary>
|
||||
internal int AddPlacedObjects(IEnumerable<(uint SetupId, uint CellId, Vector3[] Triangles)> objects, PlacedObjectOptions? options = null)
|
||||
=> AddPlacedTo(_placedBase, objects, options);
|
||||
|
||||
/// <summary>
|
||||
/// Replaces the overlay layer (objects found at run time) with <paramref name="objects"/>, classified and walled
|
||||
/// the same way, its walls kept apart from the map's so it can go again. Returns how many went on the map.
|
||||
/// </summary>
|
||||
internal int SetPlacedOverlay(IEnumerable<(uint SetupId, uint CellId, Vector3[] Triangles)> objects, PlacedObjectOptions? options = null)
|
||||
{
|
||||
var layer = new PlacedLayer(options?.Source ?? "overlay", ownWalls: true);
|
||||
int n = AddPlacedTo(layer, objects, options);
|
||||
_placedOverlay = layer;
|
||||
InvalidateClearance();
|
||||
return n;
|
||||
}
|
||||
|
||||
/// <summary>Drops the overlay layer: the map is the cells and the dats' objects again.</summary>
|
||||
internal void ClearPlacedOverlay()
|
||||
{
|
||||
if (_placedOverlay == null) return;
|
||||
_placedOverlay = null;
|
||||
InvalidateClearance();
|
||||
}
|
||||
|
||||
/// <summary>Forgets every clearance worked out so far (after the map's walls or objects change).</summary>
|
||||
internal void InvalidateClearance() => _clearanceMemo.Clear();
|
||||
|
||||
private static bool KeepByDefault(PlacedInfo p) => p.Class is PlacedClass.Obstacle or PlacedClass.StepOver or PlacedClass.Connector;
|
||||
|
||||
private int AddPlacedTo(PlacedLayer layer, IEnumerable<(uint SetupId, uint CellId, Vector3[] Triangles)> objects, PlacedObjectOptions? options)
|
||||
{
|
||||
var keep = options?.Keep ?? KeepByDefault;
|
||||
string source = options?.Source ?? layer.Source;
|
||||
var batch = new List<PlacedObj>();
|
||||
foreach (var (setup, cell, tris) in objects)
|
||||
{
|
||||
var shape = PlacedSolid.Place(setup, tris);
|
||||
if (shape == null) continue;
|
||||
// The floor it stands on: under its middle, near its lowest point (none there: its lowest point).
|
||||
// (A statue's mesh can reach 1 m and more under the floor: Thread 0x00C1's 020014A3 1.1 m.)
|
||||
bool found = FloorUnder((shape.MinX + shape.MaxX) / 2, (shape.MinY + shape.MaxY) / 2, shape.MinZ, PlacedFloorSearchUp, PlacedFloorSearchDown, out double f, out _);
|
||||
double floor = found ? f : shape.MinZ;
|
||||
batch.Add(new PlacedObj
|
||||
{
|
||||
Setup = setup, Cell = cell, Shape = shape, Floor = floor, FloorFound = found, Source = source,
|
||||
Band = shape.Band(floor + PlacedBandLow, floor + PlacedBandHigh),
|
||||
});
|
||||
}
|
||||
ReachUp(batch);
|
||||
int added = 0;
|
||||
foreach (var p in batch)
|
||||
{
|
||||
p.Class = Classify(p);
|
||||
layer.All.Add(p);
|
||||
if (p.Band.Empty || !keep(p.Info)) continue;
|
||||
p.OnMap = true;
|
||||
PutOnMap(layer, p);
|
||||
added++;
|
||||
}
|
||||
if (added > 0) InvalidateClearance();
|
||||
return added;
|
||||
}
|
||||
|
||||
private PlacedClass Classify(PlacedObj p)
|
||||
{
|
||||
double top = p.Shape.MaxZ - p.Floor, bottom = p.Shape.MinZ - p.Floor;
|
||||
if (p.Band.Empty)
|
||||
{
|
||||
if (IsSlab(p, bottom)) return PlacedClass.Connector;
|
||||
return top < PlacedBandLow ? PlacedClass.Low : bottom > PlacedBandHigh ? PlacedClass.Overhead : PlacedClass.Clear;
|
||||
}
|
||||
if (p.ReachHigh >= ConnectorReach) return PlacedClass.Connector;
|
||||
if (top <= StepOverTop && p.Shape.Model.WalkableTop) return PlacedClass.StepOver;
|
||||
return PlacedClass.Obstacle;
|
||||
}
|
||||
|
||||
// A slab that is a floor the map doesn't have (stepping stones over a pit, a raised platform's floor plate).
|
||||
private bool IsSlab(PlacedObj p, double bottom)
|
||||
{
|
||||
if (p.FloorFound && bottom <= SlabRaised) return false;
|
||||
var m = p.Shape.Model;
|
||||
double area = 0, missing = 0;
|
||||
for (int k = 0; k < m.WalkFaceCount; k++)
|
||||
{
|
||||
double a = m.WalkFaceArea(k);
|
||||
area += a;
|
||||
p.Shape.WalkFaceCentre(k, out double x, out double y, out double z);
|
||||
if (!TryFloorHeight(x, y, z, SlabFloorNear, out _)) missing += a;
|
||||
}
|
||||
return area >= SlabArea && missing >= area / 2;
|
||||
}
|
||||
|
||||
// The connector chain: walkable faces reached from each object's floor, a step up at a time, across every object
|
||||
// of the batch; each object's highest reached face over its own floor.
|
||||
private static void ReachUp(List<PlacedObj> batch)
|
||||
{
|
||||
var faces = new List<(int Obj, double MinX, double MinY, double MaxX, double MaxY, double Z0, double Z1)>();
|
||||
for (int o = 0; o < batch.Count; o++)
|
||||
{
|
||||
var s = batch[o].Shape;
|
||||
for (int k = 0; k < s.Model.WalkFaceCount; k++)
|
||||
{
|
||||
s.WalkFace(k, out double x0, out double y0, out double x1, out double y1, out double z0, out double z1);
|
||||
faces.Add((o, x0, y0, x1, y1, z0, z1));
|
||||
}
|
||||
}
|
||||
if (faces.Count == 0) return;
|
||||
const double bucket = 2.0;
|
||||
static int B(double v) => (int)Math.Floor(v / bucket);
|
||||
var grid = new Dictionary<long, List<int>>();
|
||||
for (int f = 0; f < faces.Count; f++)
|
||||
for (int gx = B(faces[f].MinX); gx <= B(faces[f].MaxX); gx++)
|
||||
for (int gy = B(faces[f].MinY); gy <= B(faces[f].MaxY); gy++)
|
||||
{
|
||||
long key = GridKey(gx, gy);
|
||||
if (!grid.TryGetValue(key, out var l)) grid[key] = l = new List<int>();
|
||||
l.Add(f);
|
||||
}
|
||||
var reached = new bool[faces.Count];
|
||||
var queue = new Queue<int>();
|
||||
for (int f = 0; f < faces.Count; f++)
|
||||
{
|
||||
double fl = batch[faces[f].Obj].Floor;
|
||||
if (faces[f].Z0 - fl <= ConnectorRise && faces[f].Z1 - fl >= -ConnectorRise) { reached[f] = true; queue.Enqueue(f); }
|
||||
}
|
||||
while (queue.Count > 0)
|
||||
{
|
||||
var f = faces[queue.Dequeue()];
|
||||
for (int gx = B(f.MinX - ConnectorGap); gx <= B(f.MaxX + ConnectorGap); gx++)
|
||||
for (int gy = B(f.MinY - ConnectorGap); gy <= B(f.MaxY + ConnectorGap); gy++)
|
||||
{
|
||||
if (!grid.TryGetValue(GridKey(gx, gy), out var l)) continue;
|
||||
foreach (int g in l)
|
||||
{
|
||||
if (reached[g]) continue;
|
||||
var h = faces[g];
|
||||
if (h.MinX > f.MaxX + ConnectorGap || h.MaxX < f.MinX - ConnectorGap || h.MinY > f.MaxY + ConnectorGap || h.MaxY < f.MinY - ConnectorGap) continue;
|
||||
if (h.Z0 > f.Z1 + ConnectorRise || h.Z1 < f.Z0 - ConnectorDrop) continue;
|
||||
reached[g] = true;
|
||||
queue.Enqueue(g);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (int f = 0; f < faces.Count; f++)
|
||||
{
|
||||
if (!reached[f]) continue;
|
||||
var p = batch[faces[f].Obj];
|
||||
p.ReachHigh = Math.Max(p.ReachHigh, faces[f].Z1 - p.Floor);
|
||||
}
|
||||
}
|
||||
|
||||
private void PutOnMap(PlacedLayer layer, PlacedObj p)
|
||||
{
|
||||
var s = p.Shape;
|
||||
int idx = layer.OnMap.Count;
|
||||
layer.OnMap.Add(p);
|
||||
for (int gx = GridOf(s.MinX - 0.1); gx <= GridOf(s.MaxX + 0.1); gx++)
|
||||
for (int gy = GridOf(s.MinY - 0.1); gy <= GridOf(s.MaxY + 0.1); gy++)
|
||||
{
|
||||
long key = GridKey(gx, gy);
|
||||
if (!layer.Grid.TryGetValue(key, out var list)) layer.Grid[key] = list = new List<int>();
|
||||
list.Add(idx);
|
||||
}
|
||||
var cells = CellsUnder(p);
|
||||
// The band at its floor, no higher or lower than the object itself: a walker on the floor over a block under a
|
||||
// door sill (E74E: its top the floor walked on, 1.2 m over its own) is above its sides, not beside them.
|
||||
double zLo = Math.Max(p.Floor + PlacedBandLow, s.MinZ), zHi = Math.Min(p.Floor + PlacedBandHigh, s.MaxZ);
|
||||
var byCell = layer.OwnWalls ? layer.CellWalls : _walls;
|
||||
var o = p.Band.Outline;
|
||||
for (int k = 0; k + 3 < o.Length; k += 4)
|
||||
{
|
||||
s.ToWorld(o[k], o[k + 1], out double x0, out double y0);
|
||||
s.ToWorld(o[k + 2], o[k + 3], out double x1, out double y1);
|
||||
var w = new WallSeg(x0, y0, x1, y1, zLo, zHi);
|
||||
if (layer.OwnWalls) AddWallTo(layer.Walls, layer.WallGrid, w);
|
||||
else AddWallToGrid(w);
|
||||
foreach (uint c in cells)
|
||||
{
|
||||
if (!byCell.TryGetValue(c, out var wl)) byCell[c] = wl = new List<WallSeg>();
|
||||
wl.Add(w);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The object's own cell, and every cell with a floor under its footprint near its floor's height.
|
||||
private List<uint> CellsUnder(PlacedObj p)
|
||||
{
|
||||
var cells = new List<uint> { p.Cell };
|
||||
var s = p.Shape;
|
||||
var tested = new HashSet<int>();
|
||||
double[]? centres = null;
|
||||
for (int gx = GridOf(s.MinX); gx <= GridOf(s.MaxX); gx++)
|
||||
for (int gy = GridOf(s.MinY); gy <= GridOf(s.MaxY); gy++)
|
||||
{
|
||||
if (!_floorGrid.TryGetValue(GridKey(gx, gy), out var list)) continue;
|
||||
foreach (int fi in list)
|
||||
{
|
||||
var f = _floorAll[fi];
|
||||
if (!tested.Add(fi) || cells.Contains(f.Cell)) continue;
|
||||
if (f.MaxX < s.MinX || f.MinX > s.MaxX || f.MaxY < s.MinY || f.MinY > s.MaxY) continue;
|
||||
if (centres == null)
|
||||
{
|
||||
centres = new double[p.Band.Cells.Length * 2];
|
||||
for (int k = 0; k < p.Band.Cells.Length; k++) s.CellCentre(p.Band.Cells[k], out centres[2 * k], out centres[2 * k + 1]);
|
||||
}
|
||||
for (int k = 0; k < centres.Length; k += 2)
|
||||
{
|
||||
double x = centres[k], y = centres[k + 1];
|
||||
if (x < f.MinX || x > f.MaxX || y < f.MinY || y > f.MaxY || !InsidePolygon2D(f.V, x, y)) continue;
|
||||
if (Math.Abs(f.HeightAt(x, y) - p.Floor) > PlacedCellFloorBand) continue;
|
||||
cells.Add(f.Cell);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return cells;
|
||||
}
|
||||
|
||||
/// <summary>True when a walker at (x, y), on a floor at <paramref name="floorZ"/>, is inside a placed object:
|
||||
/// something of one there between that floor + <see cref="PlacedBandLow"/> and + <see cref="PlacedBandHigh"/>.</summary>
|
||||
internal bool InsidePlaced(double x, double y, double floorZ)
|
||||
=> InsideLayer(_placedBase, x, y, floorZ, null) || (_placedOverlay != null && InsideLayer(_placedOverlay, x, y, floorZ, null));
|
||||
|
||||
/// <summary>InsidePlaced, counting only the objects whose class <paramref name="which"/> takes (a step-over, a connector).</summary>
|
||||
internal bool InsidePlaced(double x, double y, double floorZ, Func<PlacedClass, bool> which)
|
||||
=> InsideLayer(_placedBase, x, y, floorZ, which) || (_placedOverlay != null && InsideLayer(_placedOverlay, x, y, floorZ, which));
|
||||
|
||||
/// <summary>
|
||||
/// A spot at height <paramref name="z"/> (where a character stands, a recorded waypoint) is up on something placed: it
|
||||
/// reads as inside one for a walker on the map's floor under it (<paramref name="floorZ"/>), and not at its own height,
|
||||
/// which is over that object's top (a dais, a ramp, a platform). The map has no floor on an object's top, so every test
|
||||
/// from the floor under such a spot takes it for one inside the object.
|
||||
/// </summary>
|
||||
internal bool OnTopOfPlaced(double x, double y, double z, double floorZ)
|
||||
=> z > floorZ && InsidePlaced(x, y, floorZ) && !InsidePlaced(x, y, z);
|
||||
|
||||
private static bool InsideLayer(PlacedLayer layer, double x, double y, double h, Func<PlacedClass, bool>? which = null)
|
||||
{
|
||||
if (layer.OnMap.Count == 0 || !layer.Grid.TryGetValue(GridKey(GridOf(x), GridOf(y)), out var list)) return false;
|
||||
double lo = h + PlacedBandLow, hi = h + PlacedBandHigh;
|
||||
foreach (int i in list)
|
||||
if ((which == null || which(layer.OnMap[i].Class)) && layer.OnMap[i].Shape.SolidIn(x, y, lo, hi)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>The placed objects on the map near (x, y) within r, for offline inspection: model, cell, box, floor.</summary>
|
||||
internal List<(uint Setup, uint Cell, double MinX, double MinY, double MaxX, double MaxY, double Floor)> PlacedNear(double x, double y, double r)
|
||||
{
|
||||
var outList = new List<(uint, uint, double, double, double, double, double)>();
|
||||
foreach (var layer in PlacedLayers())
|
||||
foreach (var p in layer.OnMap)
|
||||
{
|
||||
var s = p.Shape;
|
||||
if (s.MaxX >= x - r && s.MinX <= x + r && s.MaxY >= y - r && s.MinY <= y + r)
|
||||
outList.Add((p.Setup, p.Cell, s.MinX, s.MinY, s.MaxX, s.MaxY, p.Floor));
|
||||
}
|
||||
return outList;
|
||||
}
|
||||
|
||||
private IEnumerable<PlacedLayer> PlacedLayers()
|
||||
{
|
||||
yield return _placedBase;
|
||||
if (_placedOverlay != null) yield return _placedOverlay;
|
||||
}
|
||||
|
||||
// Clearance is asked again and again for the same spots (a patrol passes a doorway several
|
||||
// times a lap; every standoff is tried in turn): remembered to the centimetre.
|
||||
private readonly Dictionary<(long, long, long, int), double> _clearanceMemo = new();
|
||||
|
|
@ -728,16 +1137,27 @@ internal sealed class DungeonGeometry
|
|||
private bool WallHit(double x0, double y0, double x1, double y1, double zLo, double zHi, out double t)
|
||||
{
|
||||
t = 1;
|
||||
bool hit = WallHitIn(_wallAll, _wallGrid, x0, y0, x1, y1, zLo, zHi, ref t);
|
||||
if (_placedOverlay is { Walls.Count: > 0 } ov) hit |= WallHitIn(ov.Walls, ov.WallGrid, x0, y0, x1, y1, zLo, zHi, ref t);
|
||||
return hit;
|
||||
}
|
||||
|
||||
private static bool WallHitIn(List<WallSeg> all, Dictionary<long, List<int>> grid, double x0, double y0, double x1, double y1, double zLo, double zHi, ref double t)
|
||||
{
|
||||
bool hit = false;
|
||||
double bx0 = Math.Min(x0, x1), bx1 = Math.Max(x0, x1), by0 = Math.Min(y0, y1), by1 = Math.Max(y0, y1);
|
||||
var span = System.Runtime.InteropServices.CollectionsMarshal.AsSpan(all);
|
||||
// Every bucket the step touches (a wall is in every bucket its own box touches).
|
||||
for (int gx = GridOf(Math.Min(x0, x1)); gx <= GridOf(Math.Max(x0, x1)); gx++)
|
||||
for (int gy = GridOf(Math.Min(y0, y1)); gy <= GridOf(Math.Max(y0, y1)); gy++)
|
||||
for (int gx = GridOf(bx0); gx <= GridOf(bx1); gx++)
|
||||
for (int gy = GridOf(by0); gy <= GridOf(by1); gy++)
|
||||
{
|
||||
if (!_wallGrid.TryGetValue(GridKey(gx, gy), out var list)) continue;
|
||||
if (!grid.TryGetValue(GridKey(gx, gy), out var list)) continue;
|
||||
foreach (int i in list)
|
||||
{
|
||||
var w = _wallAll[i];
|
||||
ref readonly var w = ref span[i];
|
||||
if (w.ZMax < zLo || w.ZMin > zHi) continue;
|
||||
// Boxes apart: no crossing (a 0.1 m probe step against a 4 m bucket's walls, mostly).
|
||||
if ((w.X0 < bx0 && w.X1 < bx0) || (w.X0 > bx1 && w.X1 > bx1) || (w.Y0 < by0 && w.Y1 < by0) || (w.Y0 > by1 && w.Y1 > by1)) continue;
|
||||
if (!SegmentParam(x0, y0, x1, y1, w.X0, w.Y0, w.X1, w.Y1, out double s) || s >= t) continue;
|
||||
var (lo, hi) = w.ZRangeAt(x0 + (x1 - x0) * s, y0 + (y1 - y0) * s);
|
||||
if (hi < zLo || lo > zHi) continue;
|
||||
|
|
@ -766,11 +1186,14 @@ internal sealed class DungeonGeometry
|
|||
foreach (var v in list)
|
||||
{
|
||||
if (v.Length < 3) continue;
|
||||
double area = 0, cx = 0, cy = 0, cz = 0;
|
||||
// In doubles, from the first corner: a.X * b.Y in floats at world coordinates (44388 * 15006)
|
||||
// keeps about 40 m² of 6.7e8, so a small cell's floor came out with no area and the cell read
|
||||
// as floorless (building E74E#14, 2026-11-17: 01B2, the west stairs 01BE and 01C0, its doorway cells).
|
||||
double area = 0, cx = 0, cy = 0, cz = 0, ox = v[0].X, oy = v[0].Y;
|
||||
for (int i = 0; i < v.Length; i++)
|
||||
{
|
||||
var a = v[i]; var b = v[(i + 1) % v.Length];
|
||||
area += a.X * b.Y - b.X * a.Y;
|
||||
area += (a.X - ox) * (b.Y - oy) - (b.X - ox) * (a.Y - oy);
|
||||
cx += a.X; cy += a.Y; cz += a.Z;
|
||||
}
|
||||
area = Math.Abs(area) * 0.5;
|
||||
|
|
@ -785,35 +1208,50 @@ internal sealed class DungeonGeometry
|
|||
internal List<(double X0, double Y0, double X1, double Y1, double ZMin, double ZMax, double Dist)> WallsNear(double x, double y, double r)
|
||||
{
|
||||
var res = new List<(double, double, double, double, double, double, double)>();
|
||||
var seen = new HashSet<int>();
|
||||
for (int gx = GridOf(x - r); gx <= GridOf(x + r); gx++)
|
||||
for (int gy = GridOf(y - r); gy <= GridOf(y + r); gy++)
|
||||
{
|
||||
if (!_wallGrid.TryGetValue(GridKey(gx, gy), out var list)) continue;
|
||||
foreach (int i in list)
|
||||
void From(List<WallSeg> all, Dictionary<long, List<int>> grid)
|
||||
{
|
||||
var seen = new HashSet<int>();
|
||||
for (int gx = GridOf(x - r); gx <= GridOf(x + r); gx++)
|
||||
for (int gy = GridOf(y - r); gy <= GridOf(y + r); gy++)
|
||||
{
|
||||
if (!seen.Add(i)) continue;
|
||||
var w = _wallAll[i];
|
||||
double d = PointSegDist(x, y, w.X0, w.Y0, w.X1, w.Y1, out double cx, out double cy);
|
||||
var (lo, hi) = w.ZRangeAt(cx, cy); // its height range at the nearest point
|
||||
if (d <= r) res.Add((w.X0, w.Y0, w.X1, w.Y1, lo, hi, d));
|
||||
if (!grid.TryGetValue(GridKey(gx, gy), out var list)) continue;
|
||||
foreach (int i in list)
|
||||
{
|
||||
if (!seen.Add(i)) continue;
|
||||
var w = all[i];
|
||||
double d = PointSegDist(x, y, w.X0, w.Y0, w.X1, w.Y1, out double cx, out double cy);
|
||||
var (lo, hi) = w.ZRangeAt(cx, cy); // its height range at the nearest point
|
||||
if (d <= r) res.Add((w.X0, w.Y0, w.X1, w.Y1, lo, hi, d));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
From(_wallAll, _wallGrid);
|
||||
if (_placedOverlay != null) From(_placedOverlay.Walls, _placedOverlay.WallGrid);
|
||||
return res;
|
||||
}
|
||||
|
||||
// Exact distance from (x, y) to the nearest wall reaching into zLo..zHi, up to maxR.
|
||||
private double WallDistance(double x, double y, double zLo, double zHi, double maxR)
|
||||
{
|
||||
double best = WallDistanceIn(_wallAll, _wallGrid, x, y, zLo, zHi, maxR);
|
||||
if (_placedOverlay is { Walls.Count: > 0 } ov) best = WallDistanceIn(ov.Walls, ov.WallGrid, x, y, zLo, zHi, best);
|
||||
return best;
|
||||
}
|
||||
|
||||
private static double WallDistanceIn(List<WallSeg> all, Dictionary<long, List<int>> grid, double x, double y, double zLo, double zHi, double maxR)
|
||||
{
|
||||
double best = maxR;
|
||||
var span = System.Runtime.InteropServices.CollectionsMarshal.AsSpan(all);
|
||||
for (int gx = GridOf(x - maxR); gx <= GridOf(x + maxR); gx++)
|
||||
for (int gy = GridOf(y - maxR); gy <= GridOf(y + maxR); gy++)
|
||||
{
|
||||
if (!_wallGrid.TryGetValue(GridKey(gx, gy), out var list)) continue;
|
||||
if (!grid.TryGetValue(GridKey(gx, gy), out var list)) continue;
|
||||
foreach (int i in list)
|
||||
{
|
||||
var w = _wallAll[i];
|
||||
ref readonly var w = ref span[i];
|
||||
if (w.ZMax < zLo || w.ZMin > zHi) continue;
|
||||
// Its box farther off than the best so far: no nearer point on it.
|
||||
if ((w.X0 < x - best && w.X1 < x - best) || (w.X0 > x + best && w.X1 > x + best) || (w.Y0 < y - best && w.Y1 < y - best) || (w.Y0 > y + best && w.Y1 > y + best)) continue;
|
||||
double d = PointSegDist(x, y, w.X0, w.Y0, w.X1, w.Y1, out double cx, out double cy);
|
||||
if (d >= best) continue;
|
||||
var (lo, hi) = w.ZRangeAt(cx, cy);
|
||||
|
|
|
|||
|
|
@ -8,12 +8,28 @@
|
|||
//
|
||||
// GetGeometry closes each doorway a placed object stands across (both ways, as a wall), before the
|
||||
// ledges are looked at, so every walk laid on the map (patrol, explore, dunroute, the stuck detours)
|
||||
// goes round. Blocked: walking lines straight through the doorway, 0.25 m apart across it, hit an
|
||||
// object's physics polygons within 1.2 m of the doorway at some body height (0.6 to 1.5 m: a web's
|
||||
// strands leave gaps a line slips through and a character doesn't), leaving no free gap of
|
||||
// BlockedGapMeters. An arch or a frame round a doorway leaves its
|
||||
// middle free; a pillar to one side leaves a gap. The objects come from StaticMeshSource (the plugin
|
||||
// points it at GeometryLoader.GetDungeonStaticMeshes once the raycast is up; null: nothing closed).
|
||||
// goes round. Blocked: walking lines straight through the doorway, 0.25 m apart across it, meet an
|
||||
// object within 1.2 m of the doorway in a body's way, leaving no free gap of BlockedGapMeters. An arch or a
|
||||
// frame round a doorway leaves its middle free; a pillar to one side leaves a gap.
|
||||
//
|
||||
// 2026-11-18: the objects are the map's own solid models (PlacedSolid) and a lane is a body's walk, not
|
||||
// rays. The rays (two of four heights, 0.6 to 1.5 m, hitting) counted a ray that went into an object's box
|
||||
// and met none of its polygons as a hit, so an arch round a doorway shut it (0x0150's 0x01000E60), the
|
||||
// bridge over 0x000A's hall shut the four doorways onto it (0x02000224: they open onto its deck, a body's
|
||||
// height clear between its rails), 0x039B's spiral stair shut the doorway that opens onto its foot, and
|
||||
// 0x238E's stair towers their doors. Now each lane is walked from free floor on either side: the feet on
|
||||
// the doorway's floor or on what is placed, a step up of StepOverTop at most at a time (onto the foot of a
|
||||
// ramp and up it to a platform: 0x8804's 0x0200033D), stopped by anything between the feet + PlacedBandLow
|
||||
// and + PlacedBandHigh (the band the placed objects' walls use). A web's strands at every height add up to
|
||||
// a closed line; a step block under a door sill (its top the doorway's floor) is stood on; a block taller
|
||||
// than a step (0x5456's 0x02000CCE) stops the walk. The objects come from StaticMeshSource (the plugin points
|
||||
// it at GeometryLoader.GetDungeonStaticMeshes once the raycast is up; null: nothing closed).
|
||||
//
|
||||
// 2026-11-18, landblocks with buildings: this map is the stuck detours' there (NavRecovery.PlanIndoor), and it
|
||||
// took every stab, stairs too, as walls and closed the doorways stairs stand in (1,094 building doorways
|
||||
// world-wide, 1,620 cells no door reached any more; 7D64 from its first doors 113 rooms to 99, E74E 155 to 129).
|
||||
// There the objects are BuildingMap's furniture: its stairs (BuildingMap.FurnitureFilter) are no walls and close
|
||||
// no doorway. Dungeons are as before.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
|
@ -31,11 +47,11 @@ internal static partial class DungeonPathfinder
|
|||
|
||||
/// <summary>A doorway with no free gap this wide left at body height is blocked.</summary>
|
||||
internal const double BlockedGapMeters = 1.0;
|
||||
// Lanes this far apart across the doorway, none nearer its sides than the margin; each looked along from
|
||||
// BlockedNear before the doorway to BlockedNear past it (a web 0.8 m into the next cell is in it).
|
||||
private const double BlockedLaneStep = 0.25, BlockedEdgeMargin = 0.4, BlockedNear = 1.2;
|
||||
// A body's height: a web's strands leave gaps a thin line slips through, a character doesn't.
|
||||
private static readonly double[] BlockedHeights = { 0.6, 0.9, 1.2, 1.5 };
|
||||
// Lanes this far apart across the doorway, none nearer its sides than the margin; each walked from
|
||||
// BlockedNear before the doorway to BlockedNear past it (a web 0.8 m into the next cell is in it), a
|
||||
// sample every BlockedAlong (half a column of the solid models). A lane starts on free floor, looked for
|
||||
// up to BlockedRunUp further out (the foot of a ramp up to the doorway).
|
||||
private const double BlockedLaneStep = 0.25, BlockedEdgeMargin = 0.4, BlockedNear = 1.2, BlockedAlong = 0.05, BlockedRunUp = 2.0;
|
||||
|
||||
/// <summary>What closing the blocked doorways did in the last dungeon (one line, for the build log), or null.</summary>
|
||||
internal static string? BlockedNote;
|
||||
|
|
@ -51,13 +67,22 @@ internal static partial class DungeonPathfinder
|
|||
var list = new List<(uint, uint, uint[])>();
|
||||
if (statics.Count == 0) return list;
|
||||
var seen = new HashSet<ulong>();
|
||||
var shapes = new Dictionary<int, PlacedShape?>(); // each object's model, placed once
|
||||
foreach (var n in graph.Values)
|
||||
foreach (uint nb in n.Neighbors)
|
||||
{
|
||||
if (!graph.ContainsKey(nb) || !seen.Add(EdgeKey(n.CellId, nb))) continue;
|
||||
if (!geo.TryGetDoorway(n.CellId, nb, out var d) || d.IsWide) continue;
|
||||
var near = statics.Where(s => s.Mesh.Max.X >= d.X - 4 && s.Mesh.Min.X <= d.X + 4 && s.Mesh.Max.Y >= d.Y - 4 && s.Mesh.Min.Y <= d.Y + 4
|
||||
&& s.Mesh.Max.Z >= d.Z && s.Mesh.Min.Z <= d.Z + 2.5).ToList();
|
||||
var near = new List<(uint SetupId, PlacedShape Shape)>();
|
||||
for (int i = 0; i < statics.Count; i++)
|
||||
{
|
||||
var m = statics[i].Mesh;
|
||||
if (m.MeshTriangles is not { Length: >= 3 }) continue;
|
||||
if (m.Max.X < d.X - 4 || m.Min.X > d.X + 4 || m.Max.Y < d.Y - 4 || m.Min.Y > d.Y + 4
|
||||
|| m.Max.Z < d.Z || m.Min.Z > d.Z + 2.5) continue;
|
||||
if (!shapes.TryGetValue(i, out var shape)) shapes[i] = shape = PlacedSolid.Place(statics[i].SetupId, m.MeshTriangles);
|
||||
if (shape != null) near.Add((statics[i].SetupId, shape));
|
||||
}
|
||||
if (near.Count == 0) continue;
|
||||
if (DoorwayBlocked(d, near, out var by)) list.Add((d.CellA, d.CellB, by));
|
||||
}
|
||||
|
|
@ -69,30 +94,135 @@ internal static partial class DungeonPathfinder
|
|||
return list;
|
||||
}
|
||||
|
||||
private static bool DoorwayBlocked(DungeonDoorway d, List<(uint SetupId, uint CellId, BoundingVolume Mesh)> near, out uint[] by)
|
||||
private static bool DoorwayBlocked(DungeonDoorway d, List<(uint SetupId, PlacedShape Shape)> near, out uint[] by)
|
||||
{
|
||||
var setups = new HashSet<uint>();
|
||||
double tx = -d.Ny, ty = d.Nx, half = d.Width / 2 - BlockedEdgeMargin;
|
||||
var dir = new Vector3((float)d.Nx, (float)d.Ny, 0f);
|
||||
double half = d.Width / 2 - BlockedEdgeMargin;
|
||||
double run = 0, bestRun = 0;
|
||||
var onLane = new List<(uint SetupId, PlacedShape Shape)>();
|
||||
double reach = BlockedNear + BlockedRunUp;
|
||||
for (double o = -half; o <= half + 1e-6; o += BlockedLaneStep)
|
||||
{
|
||||
// Shut when something is in the way at two body heights or more (a step or a low kerb meets the lowest only).
|
||||
int heights = 0;
|
||||
foreach (double h in BlockedHeights)
|
||||
{
|
||||
var start = new Vector3((float)(d.X + tx * o - d.Nx * BlockedNear), (float)(d.Y + ty * o - d.Ny * BlockedNear), (float)(d.Z + h));
|
||||
foreach (var s in near)
|
||||
if (s.Mesh.RayIntersect(start, dir, (float)(2 * BlockedNear), out _)) { heights++; setups.Add(s.SetupId); break; }
|
||||
}
|
||||
bool shut = heights >= 2;
|
||||
if (shut) run = 0;
|
||||
// The objects whose box the lane (with its run-ups) crosses: none, nothing to walk.
|
||||
double lx = d.X - d.Ny * o, ly = d.Y + d.Nx * o;
|
||||
double x0 = Math.Min(lx - d.Nx * reach, lx + d.Nx * reach) - 0.2, x1 = Math.Max(lx - d.Nx * reach, lx + d.Nx * reach) + 0.2;
|
||||
double y0 = Math.Min(ly - d.Ny * reach, ly + d.Ny * reach) - 0.2, y1 = Math.Max(ly - d.Ny * reach, ly + d.Ny * reach) + 0.2;
|
||||
onLane.Clear();
|
||||
foreach (var s in near)
|
||||
if (s.Shape.MaxX >= x0 && s.Shape.MinX <= x1 && s.Shape.MaxY >= y0 && s.Shape.MinY <= y1) onLane.Add(s);
|
||||
// Open when a body gets through either way.
|
||||
bool open = onLane.Count == 0 || LaneWalk(d, o, onLane, +1, setups) || LaneWalk(d, o, onLane, -1, setups);
|
||||
if (!open) run = 0;
|
||||
else { run += BlockedLaneStep; bestRun = Math.Max(bestRun, run); }
|
||||
}
|
||||
by = setups.ToArray();
|
||||
return bestRun < BlockedGapMeters && setups.Count > 0;
|
||||
}
|
||||
|
||||
// A body walking lane o of the doorway (dir +1: from CellA's side). It starts on free floor (nothing placed from the
|
||||
// doorway's floor up to the body's top), at the lane's end or up to BlockedRunUp further out; its feet are on the
|
||||
// doorway's floor or on the highest thing a step up at most from them; anything in its band over its feet stops it
|
||||
// (that object's model goes into `by`).
|
||||
private static bool LaneWalk(DungeonDoorway d, double o, List<(uint SetupId, PlacedShape Shape)> near, int dir, HashSet<uint> by)
|
||||
{
|
||||
double lx = d.X - d.Ny * o, ly = d.Y + d.Nx * o;
|
||||
double startA = -dir * BlockedNear, endA = dir * BlockedNear;
|
||||
bool Free(double a)
|
||||
{
|
||||
double x = lx + d.Nx * a, y = ly + d.Ny * a;
|
||||
foreach (var s in near) if (s.Shape.SolidIn(x, y, d.Z + 0.05, d.Z + DungeonGeometry.PlacedBandHigh)) return false;
|
||||
return true;
|
||||
}
|
||||
for (double ext = 0; ext <= BlockedRunUp + 1e-9; ext += BlockedAlong)
|
||||
if (Free(startA - dir * ext)) { startA -= dir * ext; break; }
|
||||
double feet = d.Z;
|
||||
int n = (int)Math.Round((endA - startA) * dir / BlockedAlong);
|
||||
for (int k = 0; k <= n; k++)
|
||||
{
|
||||
double a = startA + dir * k * BlockedAlong;
|
||||
double x = lx + d.Nx * a, y = ly + d.Ny * a;
|
||||
double stand = d.Z;
|
||||
foreach (var s in near) stand = Math.Max(stand, s.Shape.TopAtMost(x, y, feet + DungeonGeometry.StepOverTop));
|
||||
feet = stand;
|
||||
foreach (var s in near)
|
||||
if (s.Shape.SolidIn(x, y, feet + DungeonGeometry.PlacedBandLow, feet + DungeonGeometry.PlacedBandHigh)) { by.Add(s.SetupId); return false; }
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Off: placed objects are no walls on the map (tests compare; the blocked doorways are apart).</summary>
|
||||
internal static bool PlacedObjectsAsWalls = true;
|
||||
|
||||
// The stairs left off a building landblock's map (AddPlacedObjectsTo), by its geometry, for the blocked doorways.
|
||||
private static readonly System.Runtime.CompilerServices.ConditionalWeakTable<DungeonGeometry, HashSet<BuildingMap.PieceKey>> _buildingStairs = new();
|
||||
|
||||
private static readonly Dictionary<uint, bool> _hasBuildings = new();
|
||||
|
||||
/// <summary>The landblock's LandBlockInfo lists buildings (the outdoor world's towns and houses; a dungeon's lists none).</summary>
|
||||
internal static bool HasBuildings(uint landblockKey, DatDatabase cellDat)
|
||||
{
|
||||
lock (_hasBuildings)
|
||||
if (_hasBuildings.TryGetValue(landblockKey, out bool known)) return known;
|
||||
bool has = false;
|
||||
try
|
||||
{
|
||||
byte[]? info = cellDat.GetFileData((landblockKey << 16) | 0xFFFE);
|
||||
if (info != null && info.Length >= 12)
|
||||
{
|
||||
uint numObjects = BitConverter.ToUInt32(info, 8);
|
||||
long at = 12 + (long)numObjects * 32;
|
||||
has = at + 2 <= info.Length && BitConverter.ToUInt16(info, (int)at) > 0;
|
||||
}
|
||||
}
|
||||
catch { has = false; }
|
||||
lock (_hasBuildings)
|
||||
{
|
||||
if (_hasBuildings.Count > 512) _hasBuildings.Clear();
|
||||
_hasBuildings[landblockKey] = has;
|
||||
}
|
||||
return has;
|
||||
}
|
||||
|
||||
/// <summary>What the placed objects added to the last dungeon's map (one line, for the build log), or null.</summary>
|
||||
internal static string? PlacedNote;
|
||||
|
||||
/// <summary>GetGeometry's step: the objects the cells place (an altar, a statue) on the map by what they put in
|
||||
/// a body's way at their floor, the outline as walls (DungeonGeometry.AddPlacedObjects), so every walk keeps
|
||||
/// clear of them. On a landblock with buildings (<paramref name="cellDat"/> says), its furniture, the stairs left out.</summary>
|
||||
private static void AddPlacedObjectsTo(uint landblockKey, DungeonGeometry geo, DatDatabase? cellDat = null)
|
||||
{
|
||||
PlacedNote = null;
|
||||
var source = StaticMeshSource;
|
||||
if (!PlacedObjectsAsWalls || source == null) return;
|
||||
try
|
||||
{
|
||||
var statics = source(landblockKey);
|
||||
if (statics == null || statics.Count == 0) return;
|
||||
int added, stairs = 0;
|
||||
bool buildings = cellDat != null && HasBuildings(landblockKey, cellDat);
|
||||
if (buildings)
|
||||
{
|
||||
MarkBuildingMap(geo);
|
||||
var f = BuildingMap.AddFurniture(geo, statics);
|
||||
_buildingStairs.AddOrUpdate(geo, f.Stairs);
|
||||
added = f.Kept;
|
||||
stairs = f.Stairs.Count;
|
||||
}
|
||||
else added = geo.AddPlacedObjects(statics.Where(s => s.Mesh.MeshTriangles is { Length: >= 3 })
|
||||
.Select(s => (s.SetupId, s.CellId, s.Mesh.MeshTriangles)));
|
||||
var inv = CultureInfo.InvariantCulture;
|
||||
var classes = geo.PlacedObjects.GroupBy(p => p.Class).OrderBy(g => g.Key)
|
||||
.Select(g => string.Format(inv, "{0} {1}", g.Key.ToString().ToLowerInvariant(), g.Count()));
|
||||
PlacedNote = string.Format(inv, "{0} of {1} placed object(s) stand in the way at body height: walls on the map ({2}){3}",
|
||||
added, statics.Count, string.Join(", ", classes),
|
||||
buildings ? string.Format(inv, "; a landblock with buildings: {0} stair(s) left out", stairs) : "");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
PlacedNote = "placed objects not added: " + e.GetType().Name;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>GetGeometry's step: the cached graph of <paramref name="landblockKey"/> loses the doorways placed
|
||||
/// objects stand across (both ways), then its ledges.</summary>
|
||||
private static void CloseMapBlocksOf(uint landblockKey, Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo)
|
||||
|
|
@ -111,6 +241,9 @@ internal static partial class DungeonPathfinder
|
|||
{
|
||||
var statics = source(landblockKey);
|
||||
if (statics == null || statics.Count == 0) return;
|
||||
// A building's stairs close no doorway (AddPlacedObjectsTo left them off its map).
|
||||
if (_buildingStairs.TryGetValue(geo, out var stairs) && stairs.Count > 0)
|
||||
statics = statics.Where(s => BuildingMap.KeyOf(s.SetupId, s.CellId, s.Mesh.MeshTriangles) is not BuildingMap.PieceKey k || !stairs.Contains(k)).ToList();
|
||||
var blocked = FindBlockedDoorways(graph, geo, statics);
|
||||
if (blocked.Count == 0) return;
|
||||
foreach (var (a, b, _) in blocked)
|
||||
|
|
|
|||
|
|
@ -69,6 +69,7 @@ internal static partial class DungeonPathfinder
|
|||
out ExplorePlan plan,
|
||||
IReadOnlySet<uint>? preferCells = null)
|
||||
{
|
||||
using var holes = CountHoles(); // one build: the note's "no way round" counts every walk round of it (Holes.cs)
|
||||
LastPortalAvoidance = null;
|
||||
var o = ((options ?? DungeonPatrolOptions.Default) with { Coverage = PatrolCoverage.Everything }).Clamped();
|
||||
NavRouteParser route;
|
||||
|
|
@ -210,7 +211,8 @@ internal static partial class DungeonPathfinder
|
|||
finally { ScanMiddles = null; }
|
||||
if (mid != null) { Append(pts, Tag(mid, "explore-end")); middles.Add(mid); }
|
||||
// Round a hole in a cell's floor, not over it (DungeonPathfinder.Holes.cs): before the
|
||||
// straightening, so its legs keep the clearance the walk round has.
|
||||
// straightening, so its legs keep the clearance the walk round has. (EmitSteps walked its legs
|
||||
// round placed objects already; this is the floor, and an object on the leg into the end too.)
|
||||
int holes = WalkRoundHoles(pts, geo!);
|
||||
if (holes > 0 || HolesLeft > 0)
|
||||
MainRouteNote = (MainRouteNote == null ? "" : MainRouteNote + "; ") + $"holes: {holes} walked round" + (HolesLeft > 0 ? $", {HolesLeft} with no way round" : "");
|
||||
|
|
|
|||
|
|
@ -15,9 +15,21 @@
|
|||
// edges by HoleKeepOff. The A* path is then pulled straight wherever a leg stays on the floor and
|
||||
// keeps that clearance. With no way round, the leg stays as laid (a drop the walk can't do
|
||||
// otherwise) and the note says so.
|
||||
//
|
||||
// 2026-11-18, objects: a walk round can start inside something placed (a corner laid by a chair, the
|
||||
// character itself beside a table): every sample round it was too close to it, so there was no way
|
||||
// round at all (46 of the 139 legs the building survey still found through furniture). It may now
|
||||
// cross the samples of what it stands in, and the ring round it, until it is out. In a building map
|
||||
// (BuildingMap, or the dungeon map of a landblock with buildings) a walk point's height is often not
|
||||
// a floor's (a doorway's lowest corner, a corner on a stair the map has no floor for): the floor nearest
|
||||
// it within 3 m was the ground floor under the stair, and the walk round went down there (Holtburg
|
||||
// A9B3#0, 0104 to 0106 by 32626,34455 at 116.0 from a stair corner at 117.5). There it is the floor
|
||||
// within BuildingStartBand of the point, else the point's own height, and a walk round that leaves the
|
||||
// leg's heights by more than BuildingRoundBand is no way round.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.CompilerServices;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
|
@ -33,18 +45,56 @@ internal static partial class DungeonPathfinder
|
|||
private const double HolePad = 10.0; // the box round the leg (metres each way)
|
||||
private const int HoleMaxGrid = 160 * 160;
|
||||
private const double HoleStartBand = 3.0; // a walk point's floor, looked for this far above or below it
|
||||
// In a building map: a walk point's floor within this of its height, and no walk round leaving the leg's
|
||||
// heights by more than BuildingRoundBand.
|
||||
internal const double BuildingStartBand = 1.0, BuildingRoundBand = 1.0;
|
||||
// In a building map the box round a leg is this much each way (its rooms are small; with no way round, the A*
|
||||
// went over every sample of a 10 m box, at a clearance each: most of a furnished walk's time).
|
||||
internal const double BuildingHolePad = 4.0;
|
||||
|
||||
/// <summary>How many legs over a hole the last walk had walked round, and how many it couldn't.</summary>
|
||||
internal static int HolesWalkedRound, HolesLeft;
|
||||
/// <summary>How many legs over a hole (or through a placed object) the build walked round, and how many it couldn't:
|
||||
/// running counts over one build (<see cref="CountHoles"/>), every walk-round of the build added in (the patrol's
|
||||
/// rooms, its cell walk, the portal step's legs, each stretch of a jump walk). A call outside any build counts on
|
||||
/// its own. They were the last call's only, so a patrol's notes said 0 with no way round where 4 legs had none
|
||||
/// (0x00FE, 0x00D6: re-walking the finished patrols found them).</summary>
|
||||
[ThreadStatic] internal static int HolesWalkedRound, HolesLeft;
|
||||
[ThreadStatic] private static int _holeCountDepth;
|
||||
|
||||
/// <summary>Begins a build's count (the outermost one only sets the counts to 0); dispose it when the build is done.</summary>
|
||||
internal static HoleCount CountHoles()
|
||||
{
|
||||
if (_holeCountDepth++ == 0) HolesWalkedRound = HolesLeft = 0;
|
||||
return new HoleCount();
|
||||
}
|
||||
|
||||
internal readonly struct HoleCount : IDisposable
|
||||
{
|
||||
public void Dispose() { if (_holeCountDepth > 0) _holeCountDepth--; }
|
||||
}
|
||||
|
||||
// The geometries that are a building's (BuildingMap's, or the dungeon map of a landblock with buildings).
|
||||
private static readonly ConditionalWeakTable<DungeonGeometry, object> _buildingMaps = new();
|
||||
|
||||
/// <summary>Marks <paramref name="geo"/> as a building's map: its walks round start on the floor at their own height.</summary>
|
||||
internal static void MarkBuildingMap(DungeonGeometry geo) => _buildingMaps.AddOrUpdate(geo, _buildingMaps);
|
||||
|
||||
internal static bool IsBuildingMap(DungeonGeometry geo) => _buildingMaps.TryGetValue(geo, out _);
|
||||
|
||||
/// <summary>
|
||||
/// Replaces each leg of <paramref name="pts"/> that leaves the floor with a walk round on it
|
||||
/// (see the file's comment). Returns how many legs were walked round.
|
||||
/// (see the file's comment). Returns how many legs this call walked round (the build's counts
|
||||
/// go up by as many, and by the legs it couldn't). <paramref name="accept"/>, when given, must
|
||||
/// take every leg of a walk round (from, to) or the leg stays as laid and counts as having no way
|
||||
/// round: the portal step's (DungeonPathfinder.Portals.cs: a walk round an object must not go into
|
||||
/// a portal's circle).
|
||||
/// </summary>
|
||||
internal static int WalkRoundHoles(List<NavPoint> pts, DungeonGeometry geo)
|
||||
internal static int WalkRoundHoles(List<NavPoint> pts, DungeonGeometry geo, bool objectsOnly = false,
|
||||
Func<NavPoint, NavPoint, bool>? accept = null)
|
||||
{
|
||||
HolesWalkedRound = HolesLeft = 0;
|
||||
using var count = CountHoles();
|
||||
if (!HolesEnabled || pts.Count < 2) return 0;
|
||||
if (objectsOnly && geo.PlacedCount == 0) return 0;
|
||||
int walked = 0;
|
||||
var outPts = new List<NavPoint>(pts.Count + 16) { pts[0] };
|
||||
for (int i = 0; i + 1 < pts.Count; i++)
|
||||
{
|
||||
|
|
@ -52,29 +102,71 @@ internal static partial class DungeonPathfinder
|
|||
var b = pts[i + 1];
|
||||
double ax = DungeonGeometry.NavToWorld(a.EW), ay = DungeonGeometry.NavToWorld(a.NS), az = a.Z * 240.0;
|
||||
double bx = DungeonGeometry.NavToWorld(b.EW), by = DungeonGeometry.NavToWorld(b.NS), bz = b.Z * 240.0;
|
||||
if (OnFloorAll(geo, ax, ay, az, bx, by, bz))
|
||||
if (objectsOnly ? !LegMeetsPlaced(geo, ax, ay, az, bx, by, bz) : OnFloorAll(geo, ax, ay, az, bx, by, bz))
|
||||
{
|
||||
outPts.Add(b);
|
||||
continue;
|
||||
}
|
||||
var round = FloorPath(geo, ax, ay, az, bx, by, bz);
|
||||
if (round == null)
|
||||
List<NavPoint>? laid = null;
|
||||
if (round != null)
|
||||
{
|
||||
laid = new List<NavPoint>(round.Count);
|
||||
foreach (var (x, y, z) in round)
|
||||
laid.Add(new NavPoint { Type = NavPointType.Point, NS = DungeonGeometry.WorldToNav(y), EW = DungeonGeometry.WorldToNav(x), Z = z / 240.0 });
|
||||
if (accept != null)
|
||||
{
|
||||
var from = a;
|
||||
for (int k = 0; k <= laid.Count; k++)
|
||||
{
|
||||
var p = k < laid.Count ? laid[k] : b;
|
||||
if (!accept(from, p)) { laid = null; break; }
|
||||
from = p;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (laid == null)
|
||||
{
|
||||
HolesLeft++;
|
||||
outPts.Add(b);
|
||||
continue;
|
||||
}
|
||||
HolesWalkedRound++;
|
||||
foreach (var (x, y, z) in round)
|
||||
outPts.Add(new NavPoint { Type = NavPointType.Point, NS = DungeonGeometry.WorldToNav(y), EW = DungeonGeometry.WorldToNav(x), Z = z / 240.0 });
|
||||
walked++;
|
||||
outPts.AddRange(laid);
|
||||
outPts.Add(b);
|
||||
}
|
||||
if (HolesWalkedRound > 0)
|
||||
if (walked > 0)
|
||||
{
|
||||
pts.Clear();
|
||||
pts.AddRange(outPts);
|
||||
}
|
||||
return HolesWalkedRound;
|
||||
return walked;
|
||||
}
|
||||
|
||||
/// <summary>The straight walk from a to b stays on the floor all the way (OnFloorAll): the hole rule's
|
||||
/// test, and the straightener's (DungeonPathfinder.Straighten.cs).</summary>
|
||||
internal static bool LegOnFloor(DungeonGeometry geo, NavPoint a, NavPoint b)
|
||||
=> OnFloorAll(geo, DungeonGeometry.NavToWorld(a.EW), DungeonGeometry.NavToWorld(a.NS), a.Z * 240.0,
|
||||
DungeonGeometry.NavToWorld(b.EW), DungeonGeometry.NavToWorld(b.NS), b.Z * 240.0);
|
||||
|
||||
// The straight walk a-b goes through something the cells place (an altar, a statue) on the floor it
|
||||
// follows; a stretch with no floor under it on the map is no concern here (the walk round holes is the
|
||||
// explore's: a tube's floorless cells would be walked round to nowhere).
|
||||
private static bool ThroughPlaced(DungeonGeometry geo, double ax, double ay, double az, double bx, double by, double bz)
|
||||
{
|
||||
double dx = bx - ax, dy = by - ay, len = Math.Sqrt(dx * dx + dy * dy);
|
||||
if (len < HoleSample) return false;
|
||||
if (!geo.TryFloorHeight(ax, ay, az, HoleStartBand, out double zf)) zf = az;
|
||||
int steps = (int)Math.Ceiling(len / HoleSample);
|
||||
for (int s = 1; s < steps; s++)
|
||||
{
|
||||
double t = (double)s / steps, x = ax + dx * t, y = ay + dy * t;
|
||||
if (!geo.TryFloorHeight(x, y, zf, HoleStep, out double h) && !geo.TryFloorHeight(x, y, az + (bz - az) * t, HoleStep, out h)) continue;
|
||||
zf = h;
|
||||
if (geo.InsidePlaced(x, y, h)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// The straight walk a-b stays on the floor all the way: every sample has a floor within a step of
|
||||
|
|
@ -94,6 +186,9 @@ internal static partial class DungeonPathfinder
|
|||
if (s == steps && Math.Abs(bz - zf) <= 1.5 && geo.TryFloorHeight(x, y, bz, HoleStep, out _)) return true;
|
||||
return false;
|
||||
}
|
||||
// Through an altar or a statue the cells place (DungeonGeometry.AddPlacedObjects): no floor to
|
||||
// walk there either, so the leg is walked round it like a hole (the far end is the walk's own).
|
||||
if (s < steps && geo.InsidePlaced(x, y, h)) return false;
|
||||
zf = h;
|
||||
}
|
||||
return true;
|
||||
|
|
@ -102,9 +197,11 @@ internal static partial class DungeonPathfinder
|
|||
// A* round on the floor from a to b; the points between (pulled straight), or null with no way.
|
||||
private static List<(double X, double Y, double Z)>? FloorPath(DungeonGeometry geo, double ax, double ay, double az, double bx, double by, double bz)
|
||||
{
|
||||
double x0 = Math.Min(ax, bx) - HolePad, y0 = Math.Min(ay, by) - HolePad;
|
||||
int nx = (int)Math.Ceiling((Math.Abs(bx - ax) + 2 * HolePad) / HoleSample) + 1;
|
||||
int ny = (int)Math.Ceiling((Math.Abs(by - ay) + 2 * HolePad) / HoleSample) + 1;
|
||||
bool building = IsBuildingMap(geo);
|
||||
double pad = building ? BuildingHolePad : HolePad;
|
||||
double x0 = Math.Min(ax, bx) - pad, y0 = Math.Min(ay, by) - pad;
|
||||
int nx = (int)Math.Ceiling((Math.Abs(bx - ax) + 2 * pad) / HoleSample) + 1;
|
||||
int ny = (int)Math.Ceiling((Math.Abs(by - ay) + 2 * pad) / HoleSample) + 1;
|
||||
if (nx * ny > HoleMaxGrid) return null;
|
||||
int Idx(int i, int j) => j * nx + i;
|
||||
double Gx(int i) => x0 + i * HoleSample;
|
||||
|
|
@ -118,11 +215,33 @@ internal static partial class DungeonPathfinder
|
|||
var from = new int[nx * ny];
|
||||
for (int k = 0; k < g.Length; k++) { g[k] = double.MaxValue; from[k] = -1; }
|
||||
|
||||
if (!geo.TryFloorHeight(ax, ay, az, HoleStartBand, out double sh)) sh = az;
|
||||
if (!geo.TryFloorHeight(ax, ay, az, building ? BuildingStartBand : HoleStartBand, out double sh)) sh = az;
|
||||
int start = Idx(si, sj), goal = Idx(ti, tj);
|
||||
height[start] = sh; state[start] = 1; // the walk stands there already
|
||||
g[start] = 0;
|
||||
|
||||
// A start inside something placed: the boxes of what it stands in, with the ring a sample keeps off them,
|
||||
// where the walk may cross their samples on its way out (only from the start, or from a sample it reached so).
|
||||
bool[]? esc = null;
|
||||
byte[]? escState = null; // 0 unknown, 1 floor and not in a wall, 2 no
|
||||
double ex0 = double.MaxValue, ey0 = double.MaxValue, ex1 = double.MinValue, ey1 = double.MinValue;
|
||||
if (geo.PlacedCount > 0 && geo.InsidePlaced(ax, ay, sh))
|
||||
{
|
||||
foreach (var o in geo.PlacedNear(ax, ay, 0))
|
||||
{
|
||||
ex0 = Math.Min(ex0, o.MinX); ey0 = Math.Min(ey0, o.MinY);
|
||||
ex1 = Math.Max(ex1, o.MaxX); ey1 = Math.Max(ey1, o.MaxY);
|
||||
}
|
||||
if (ex0 <= ex1)
|
||||
{
|
||||
double ring = HoleKeepOff + HoleSample;
|
||||
ex0 -= ring; ey0 -= ring; ex1 += ring; ey1 += ring;
|
||||
esc = new bool[nx * ny];
|
||||
escState = new byte[nx * ny];
|
||||
esc[start] = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Floor at a step from `fromH`, and clear of walls and edges (the goal: only its floor).
|
||||
bool Walkable(int i, int j, double fromH, bool isGoal, out double h)
|
||||
{
|
||||
|
|
@ -139,6 +258,23 @@ internal static partial class DungeonPathfinder
|
|||
return true;
|
||||
}
|
||||
|
||||
// On the way out of what the start stands in: a floor sample in its box (or the ring round it), not in a wall.
|
||||
bool Escapes(int i, int j, double fromH, out double h)
|
||||
{
|
||||
h = 0;
|
||||
if (escState == null || i < 0 || j < 0 || i >= nx || j >= ny) return false;
|
||||
double x = Gx(i), y = Gy(j);
|
||||
if (x < ex0 || x > ex1 || y < ey0 || y > ey1) return false;
|
||||
if (!geo.TryFloorHeight(x, y, fromH, HoleStep, out h)) return false;
|
||||
int k = Idx(i, j);
|
||||
if (escState[k] == 0)
|
||||
escState[k] = geo.InsidePlaced(x, y, h) || geo.ClearanceMemo(x, y, h, HoleKeepOff + 0.1) > 0.05 ? (byte)1 : (byte)2;
|
||||
return escState[k] == 1;
|
||||
}
|
||||
|
||||
// A diagonal's side sample: walkable, or on the way out.
|
||||
bool Side(int i, int j, double fromH, bool leaving) => Walkable(i, j, fromH, false, out _) || (leaving && Escapes(i, j, fromH, out _));
|
||||
|
||||
var open = new PriorityQueue<int, double>();
|
||||
open.Enqueue(start, HoleDist(ax, ay, bx, by));
|
||||
var closed = new bool[nx * ny];
|
||||
|
|
@ -160,14 +296,22 @@ internal static partial class DungeonPathfinder
|
|||
int k2 = Idx(i2, j2);
|
||||
if (closed[k2]) continue;
|
||||
bool isGoal = k2 == goal;
|
||||
if (!Walkable(i2, j2, height[k], isGoal, out double h2)) continue;
|
||||
bool leaving = esc != null && esc[k]; // still on the way out of what the start stands in
|
||||
bool viaEscape = false;
|
||||
if (!Walkable(i2, j2, height[k], isGoal, out double h2))
|
||||
{
|
||||
if (!leaving || !Escapes(i2, j2, height[k], out h2)) continue;
|
||||
viaEscape = true;
|
||||
}
|
||||
if (isGoal) height[k2] = h2;
|
||||
// A diagonal step only between two floor samples (not across a corner of the hole).
|
||||
if (d >= 4 && !(Walkable(ci + di[d], cj, height[k], false, out _) && Walkable(ci, cj + dj[d], height[k], false, out _))) continue;
|
||||
if (d >= 4 && !(Side(ci + di[d], cj, height[k], leaving) && Side(ci, cj + dj[d], height[k], leaving))) continue;
|
||||
double ng = g[k] + (d >= 4 ? 1.41421356 : 1.0) * HoleSample;
|
||||
if (ng >= g[k2]) continue;
|
||||
g[k2] = ng;
|
||||
from[k2] = k;
|
||||
if (viaEscape) { height[k2] = h2; esc![k2] = true; }
|
||||
else if (esc != null) esc[k2] = false;
|
||||
open.Enqueue(k2, ng + HoleDist(Gx(i2), Gy(j2), bx, by));
|
||||
}
|
||||
}
|
||||
|
|
@ -176,6 +320,17 @@ internal static partial class DungeonPathfinder
|
|||
var cells = new List<int>();
|
||||
for (int k = goal; k != -1; k = from[k]) cells.Add(k);
|
||||
cells.Reverse();
|
||||
// In a building map, a walk round that goes up or down a floor from the leg's own heights (down to the ground
|
||||
// floor under a stair the map has no floor for) is no way round.
|
||||
if (building)
|
||||
{
|
||||
// The leg's heights: its ends' and the floors under them (a doorway's height is its lowest corner, a metre
|
||||
// over the floor under it in some of Holtburg's houses).
|
||||
double zLo = Math.Min(Math.Min(az, bz), Math.Min(sh, height[goal])) - BuildingRoundBand;
|
||||
double zHi = Math.Max(Math.Max(az, bz), Math.Max(sh, height[goal])) + BuildingRoundBand;
|
||||
foreach (int k in cells)
|
||||
if (height[k] < zLo || height[k] > zHi) return null;
|
||||
}
|
||||
var path = new List<(double X, double Y, double Z)>(cells.Count);
|
||||
foreach (int k in cells) path.Add((Gx(k % nx), Gy(k / nx), height[k]));
|
||||
path[0] = (ax, ay, az);
|
||||
|
|
@ -184,6 +339,17 @@ internal static partial class DungeonPathfinder
|
|||
// Pulled straight: from each point, the farthest one a straight leg reaches on the floor, clear.
|
||||
var kept = new List<(double X, double Y, double Z)>();
|
||||
int at = 0;
|
||||
if (esc != null)
|
||||
{
|
||||
// Out of what the start stands in: straight to the first sample clear of it (across it), pulled from there.
|
||||
int e = 0;
|
||||
while (e + 1 < cells.Count - 1 && esc[cells[e + 1]]) e++;
|
||||
if (e > 0)
|
||||
{
|
||||
at = e + 1;
|
||||
if (at < path.Count - 1) kept.Add(path[at]);
|
||||
}
|
||||
}
|
||||
while (at < path.Count - 1)
|
||||
{
|
||||
int best = at + 1;
|
||||
|
|
|
|||
298
Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Jumps.cs
Normal file
298
Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Jumps.cs
Normal file
|
|
@ -0,0 +1,298 @@
|
|||
// DungeonPathfinder, jump-downs (2026-11-17).
|
||||
//
|
||||
// AC won't walk a character off a ledge (it slides along the edge): a jump goes over. DreamWeave Thread
|
||||
// 0x0169: the last three monsters were in a cave 9-12 m under the top floor, and the one way down is a
|
||||
// 20 m shaft in the middle of a hall (four open-air cells, no rim). The dungeon map had no walk there, so
|
||||
// the character was left there; a jump by hand took it in.
|
||||
//
|
||||
// A jump-down is one way (nobody climbs back up a ledge), so a walk takes one only when asked:
|
||||
// /ra dunnav-to <id> jump, which a script sends only when no monster left can be walked to. In a
|
||||
// Thread that is safe: the cache and the exit appear where you stand once it is cleared.
|
||||
//
|
||||
// A jump-down is an opening (a doorway of the map) from a cell standing on its own floor to a side whose
|
||||
// floor, under the opening, is more than LedgeMeters lower, however much: the ledges, found from the
|
||||
// openings themselves (a closed ledge is gone from the graph, not from the geometry). It lands in the cell
|
||||
// whose own floor is under the spot a short hop past the edge. No depth limit (2026-11-18: "No limit
|
||||
// on jump down"; the fall doesn't matter): it was 15 m, and the floor under the far side was looked for
|
||||
// only as deep as the ledge pass looks (18 m); now all the way down to the dungeon's lowest floor.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Raycasting;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
/// <summary>A jump down off the edge of an opening: from cell <see cref="From"/> (its floor at <see cref="Z"/>)
|
||||
/// at the opening's centre (<see cref="X"/>, <see cref="Y"/>), facing (<see cref="Nx"/>, <see cref="Ny"/>), onto
|
||||
/// cell <see cref="Land"/>'s floor at (<see cref="LandX"/>, <see cref="LandY"/>, <see cref="LandZ"/>).</summary>
|
||||
internal readonly record struct DungeonJump(uint From, uint Land, double X, double Y, double Z, double Nx, double Ny,
|
||||
double LandX, double LandY, double LandZ)
|
||||
{
|
||||
public double Drop => Z - LandZ;
|
||||
}
|
||||
|
||||
internal static partial class DungeonPathfinder
|
||||
{
|
||||
/// <summary>Below the ledge pass's look (18 m), the floor under a jump is looked for every this many metres
|
||||
/// (each look covers LedgeDownBand either side) down to the dungeon's lowest floor.</summary>
|
||||
internal const double JumpDownStep = 3.0;
|
||||
/// <summary>A jump-down costs the path this much walk: any walk round is taken first.</summary>
|
||||
internal const double JumpCostMeters = 40.0;
|
||||
/// <summary>The jump's power (spacebar held, of 1000): a short hop over the edge.</summary>
|
||||
internal const int JumpHoldMs = 300;
|
||||
/// <summary>The walk lines up square to the edge from this far back ...</summary>
|
||||
internal const double JumpApproachMeters = 1.5;
|
||||
/// <summary>... and jumps from this far short of it (the edge stops the character there anyway).</summary>
|
||||
internal const double JumpBackMeters = 0.1;
|
||||
|
||||
// Where the hop is looked for a floor to land on: this far past the edge (the first that has one).
|
||||
private static readonly double[] JumpLandInsets = { 2.0, 1.5, 3.0, 1.0, 4.0 };
|
||||
|
||||
/// <summary>Every jump-down of the dungeon (both ways of every opening looked at).</summary>
|
||||
internal static List<DungeonJump> FindJumps(Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo)
|
||||
{
|
||||
var list = new List<DungeonJump>();
|
||||
if (graph.Count == 0) return list;
|
||||
double lowest = LowestLook(graph); // under the lowest cell: the deepest look
|
||||
var solids = new FallSolids(graph);
|
||||
foreach (var d in geo.AllDoorways)
|
||||
foreach (var (from, to) in new[] { (d.CellA, d.CellB), (d.CellB, d.CellA) })
|
||||
{
|
||||
if (!graph.ContainsKey(from) || !graph.ContainsKey(to)) continue;
|
||||
var (nx, ny) = d.NormalFrom(from); // out of from, over the edge
|
||||
if (OwnFloorInside(geo, from, d, -nx, -ny) is not { } top) continue; // standing on nothing: no jump from there
|
||||
if (FloorInside(geo, to, d, nx, ny, LedgeFloorFallback ? lowest : double.NaN) is not { } low) continue;
|
||||
double drop = top - low;
|
||||
if (drop <= LedgeMeters) continue;
|
||||
// Where the walk lines up and jumps from: nobody stands there inside something placed.
|
||||
if (geo.InsidePlaced(d.X - nx * JumpApproachMeters, d.Y - ny * JumpApproachMeters, top)
|
||||
|| geo.InsidePlaced(d.X - nx * JumpBackMeters, d.Y - ny * JumpBackMeters, top)) continue;
|
||||
if (!TryLanding(graph, geo, d, nx, ny, top, lowest, solids, out uint land, out double lx, out double ly, out double lz) || land == from) continue;
|
||||
list.Add(new DungeonJump(from, land, d.X, d.Y, top, nx, ny, lx, ly, lz));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
// ── What the cells place, in the way of a jump (2026-11-18) ──────────────────
|
||||
// The landing was looked for on the cells' floors only. A spot inside an altar or a statue on that floor is no
|
||||
// landing (the map's InsidePlaced), and a fall that meets something placed between the take-off and the floor
|
||||
// lands on that instead: a platform or a bridge over a pit (0x000A's hall: the 0x02000224 bridge and the
|
||||
// 0x02000222 slabs at z -12.8 over the hole near 0131/0132; 22 of 458 jumps in nine dungeons fell onto one).
|
||||
// Those are looked for in every object the cells place (StaticMeshSource), the ones the map leaves off too (a
|
||||
// slab has nothing in a body's band at its own floor), in the body's column at the landing spot.
|
||||
|
||||
/// <summary>The column a falling body sweeps: its middle and four points this far out.</summary>
|
||||
internal const double JumpFallRadius = 0.4;
|
||||
/// <summary>The fall is looked at from the landing floor + PlacedBandLow (lower is stepped over on landing) up to the
|
||||
/// take-off height + this (a deck flush with the edge is walked onto, not jumped past).</summary>
|
||||
internal const double JumpFallOverTop = 0.3;
|
||||
|
||||
// The objects the cells place, as solid models, placed the first time a landing spot needs them.
|
||||
private sealed class FallSolids
|
||||
{
|
||||
private readonly List<(uint SetupId, uint CellId, BoundingVolume Mesh)>? _statics;
|
||||
private readonly Dictionary<int, PlacedShape?> _shapes = new();
|
||||
|
||||
public FallSolids(Dictionary<uint, DungeonNavNode> graph)
|
||||
{
|
||||
var source = StaticMeshSource;
|
||||
if (source == null || graph.Count == 0) return;
|
||||
uint lb = 0;
|
||||
foreach (uint c in graph.Keys) { lb = c >> 16; break; }
|
||||
try { _statics = source(lb); } catch { _statics = null; }
|
||||
}
|
||||
|
||||
/// <summary>Something placed is solid in the body's column at (x, y) between zLo and zHi.</summary>
|
||||
public bool Hit(double x, double y, double zLo, double zHi)
|
||||
{
|
||||
if (_statics == null || zHi <= zLo) return false;
|
||||
double r = JumpFallRadius;
|
||||
for (int i = 0; i < _statics.Count; i++)
|
||||
{
|
||||
var m = _statics[i].Mesh;
|
||||
if (m.MeshTriangles is not { Length: >= 3 }) continue;
|
||||
if (m.Max.X < x - r || m.Min.X > x + r || m.Max.Y < y - r || m.Min.Y > y + r || m.Max.Z < zLo || m.Min.Z > zHi) continue;
|
||||
if (!_shapes.TryGetValue(i, out var s)) _shapes[i] = s = PlacedSolid.Place(_statics[i].SetupId, m.MeshTriangles);
|
||||
if (s == null) continue;
|
||||
if (s.SolidIn(x, y, zLo, zHi) || s.SolidIn(x + r, y, zLo, zHi) || s.SolidIn(x - r, y, zLo, zHi)
|
||||
|| s.SolidIn(x, y + r, zLo, zHi) || s.SolidIn(x, y - r, zLo, zHi)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// The cell's own floor just inside the opening (none: null).
|
||||
private static double? OwnFloorInside(DungeonGeometry geo, uint cell, DungeonDoorway d, double ux, double uy)
|
||||
{
|
||||
foreach (double inset in LedgeInsets)
|
||||
{
|
||||
double x = d.X + ux * inset, y = d.Y + uy * inset;
|
||||
foreach (double dz in LedgeZRefs)
|
||||
if (geo.TryCellFloorHeight(cell, x, y, d.Z + dz, out double h)) return h;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// The floor a hop past the edge lands on, and the cell it is the floor of: the first floor under the spot (the
|
||||
// one a fall meets), clear of what the cells place there and on the way down; else the next inset.
|
||||
private static bool TryLanding(Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo, DungeonDoorway d,
|
||||
double nx, double ny, double top, double lowest, FallSolids? solids,
|
||||
out uint land, out double lx, out double ly, out double lz)
|
||||
{
|
||||
foreach (double inset in JumpLandInsets)
|
||||
{
|
||||
double x = d.X + nx * inset, y = d.Y + ny * inset;
|
||||
bool found = false;
|
||||
double fx = 0, fy = 0, fz = 0;
|
||||
uint fc = 0;
|
||||
for (double dz = 0; top + dz >= lowest && !found; dz -= JumpDownStep) // 0, -3, -6 ... as far down as the dungeon goes
|
||||
{
|
||||
if (!geo.TryFloorHeight(x, y, top + dz, LedgeDownBand, out double h) || h > top - LedgeMeters) continue;
|
||||
foreach (var n in graph.Values)
|
||||
if (geo.TryCellFloorHeight(n.CellId, x, y, h, out double hh) && Math.Abs(hh - h) < 0.5)
|
||||
{
|
||||
fc = n.CellId; fx = x; fy = y; fz = hh;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) continue;
|
||||
// Inside an altar or a statue on that floor, or a platform on the way down: not here.
|
||||
if (geo.InsidePlaced(fx, fy, fz)) continue;
|
||||
if (solids != null && solids.Hit(fx, fy, fz + DungeonGeometry.PlacedBandLow, top + JumpFallOverTop)) continue;
|
||||
land = fc; lx = fx; ly = fy; lz = fz;
|
||||
return true;
|
||||
}
|
||||
land = 0; lx = ly = lz = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A* from <paramref name="start"/> to <paramref name="goal"/> as <see cref="FindPath"/>, and the
|
||||
/// jump-downs as one-way steps (each costs <see cref="JumpCostMeters"/> of walk). Each cell comes with
|
||||
/// the jump taken into it (null: walked). Empty: unreachable even so.
|
||||
/// </summary>
|
||||
internal static List<(uint Cell, DungeonJump? Jump)> FindPathWithJumps(
|
||||
uint start, uint goal, Dictionary<uint, DungeonNavNode> graph, IReadOnlyList<DungeonJump> jumps,
|
||||
IReadOnlySet<uint>? hazardCells = null)
|
||||
{
|
||||
var path = new List<(uint, DungeonJump?)>();
|
||||
if (!graph.ContainsKey(start) || !graph.ContainsKey(goal)) return path;
|
||||
var byFrom = jumps.GroupBy(j => j.From).ToDictionary(g => g.Key, g => g.ToList());
|
||||
var goalNode = graph[goal];
|
||||
var gScore = new Dictionary<uint, double> { [start] = 0.0 };
|
||||
var cameFrom = new Dictionary<uint, (uint From, DungeonJump? Jump)>();
|
||||
var open = new PriorityQueue<uint, double>();
|
||||
var closed = new HashSet<uint>();
|
||||
open.Enqueue(start, H(graph[start], goalNode));
|
||||
double jumpCost = JumpCostMeters / 240.0; // nav units
|
||||
|
||||
while (open.Count > 0)
|
||||
{
|
||||
uint current = open.Dequeue();
|
||||
if (!closed.Add(current)) continue;
|
||||
if (current == goal) break;
|
||||
var cur = graph[current];
|
||||
double gCur = gScore[current];
|
||||
|
||||
void Relax(uint nb, double cost, DungeonJump? jump)
|
||||
{
|
||||
if (closed.Contains(nb) || !graph.TryGetValue(nb, out var nbNode)) return;
|
||||
if (nb != goal && hazardCells != null && hazardCells.Contains(nb)) return;
|
||||
double g = gCur + cost;
|
||||
if (g >= gScore.GetValueOrDefault(nb, double.MaxValue)) return;
|
||||
gScore[nb] = g;
|
||||
cameFrom[nb] = (current, jump);
|
||||
open.Enqueue(nb, g + H(nbNode, goalNode));
|
||||
}
|
||||
|
||||
foreach (uint nb in cur.Neighbors)
|
||||
if (graph.TryGetValue(nb, out var nbNode) && !IsDropEdge(cur, nbNode)) Relax(nb, H(cur, nbNode), null);
|
||||
if (byFrom.TryGetValue(current, out var js))
|
||||
foreach (var j in js)
|
||||
{
|
||||
var landNode = graph[j.Land];
|
||||
Relax(j.Land, H(cur, landNode) + jumpCost, j);
|
||||
}
|
||||
}
|
||||
if (!closed.Contains(goal)) return path;
|
||||
for (uint c = goal; ; )
|
||||
{
|
||||
if (cameFrom.TryGetValue(c, out var step)) { path.Add((c, step.Jump)); c = step.From; }
|
||||
else { path.Add((c, null)); break; }
|
||||
}
|
||||
path.Reverse();
|
||||
return path;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Points for walking a path with jump-downs (from <see cref="FindPathWithJumps"/>), the destination
|
||||
/// not included: each stretch walked as <see cref="BuildPathPoints"/> lays it; at each jump, a point
|
||||
/// <see cref="JumpApproachMeters"/> back from the edge (square to it), then a Jump point just short of
|
||||
/// it facing over it; the next stretch starts where it lands.
|
||||
/// </summary>
|
||||
internal static List<NavPoint> BuildJumpPathPoints(
|
||||
List<(uint Cell, DungeonJump? Jump)> path, Dictionary<uint, DungeonNavNode> graph, DungeonGeometry? geo,
|
||||
IReadOnlySet<uint>? hazardCells, double startNS, double startEW, double startZ,
|
||||
double destNS, double destEW, double destZ, out int jumps)
|
||||
{
|
||||
using var holes = CountHoles(); // one build: every stretch's walk-rounds count
|
||||
var pts = new List<NavPoint>();
|
||||
jumps = 0;
|
||||
int seg = 0;
|
||||
double sNs = startNS, sEw = startEW, sZ = startZ;
|
||||
for (int k = 1; k <= path.Count; k++)
|
||||
{
|
||||
if (k < path.Count && path[k].Jump is null) continue;
|
||||
var cells = path.GetRange(seg, k - seg).Select(p => p.Cell).ToList();
|
||||
if (k == path.Count)
|
||||
{
|
||||
pts.AddRange(BuildPathPoints(cells, graph, geo, hazardCells, sNs, sEw, sZ, destNS, destEW, destZ, out _));
|
||||
break;
|
||||
}
|
||||
var j = path[k].Jump!.Value;
|
||||
double aNs = DungeonGeometry.WorldToNav(j.Y - j.Ny * JumpApproachMeters), aEw = DungeonGeometry.WorldToNav(j.X - j.Nx * JumpApproachMeters);
|
||||
// The stretch to the approach point: BuildPathPoints walks its legs round what the cells place, the leg
|
||||
// into the approach point too (the stretch's destination, 2026-11-18).
|
||||
pts.AddRange(BuildPathPoints(cells, graph, geo, hazardCells, sNs, sEw, sZ, aNs, aEw, j.Z, out _));
|
||||
var approach = new NavPoint { Type = NavPointType.Point, NS = aNs, EW = aEw, Z = j.Z / 240.0 };
|
||||
var jump = new NavPoint
|
||||
{
|
||||
Type = NavPointType.Jump,
|
||||
NS = DungeonGeometry.WorldToNav(j.Y - j.Ny * JumpBackMeters),
|
||||
EW = DungeonGeometry.WorldToNav(j.X - j.Nx * JumpBackMeters),
|
||||
Z = j.Z / 240.0,
|
||||
JumpHeading = JumpHeadingOf(j.Nx, j.Ny),
|
||||
JumpShift = false,
|
||||
JumpMs = JumpHoldMs,
|
||||
Doorway = true, // the tight reach: jump at the edge, not a metre short of it
|
||||
};
|
||||
pts.Add(approach);
|
||||
// The line-up to the edge (1.4 m, square to it) was never looked at either: an object on it is walked
|
||||
// round to the Jump point, whose heading still faces over the edge.
|
||||
if (geo != null && geo.PlacedCount > 0)
|
||||
{
|
||||
var lineUp = new List<NavPoint> { approach, jump };
|
||||
if (WalkRoundHoles(lineUp, geo, objectsOnly: true) > 0)
|
||||
for (int q = 1; q + 1 < lineUp.Count; q++) pts.Add(lineUp[q]);
|
||||
}
|
||||
pts.Add(jump);
|
||||
jumps++;
|
||||
sNs = DungeonGeometry.WorldToNav(j.LandY);
|
||||
sEw = DungeonGeometry.WorldToNav(j.LandX);
|
||||
sZ = j.LandZ;
|
||||
seg = k;
|
||||
}
|
||||
return pts;
|
||||
}
|
||||
|
||||
/// <summary>The compass heading (0 north, 90 east) of the world direction (x east, y north).</summary>
|
||||
internal static double JumpHeadingOf(double nx, double ny)
|
||||
{
|
||||
double deg = Math.Atan2(nx, ny) * (180.0 / Math.PI);
|
||||
return deg < 0 ? deg + 360.0 : deg;
|
||||
}
|
||||
}
|
||||
|
|
@ -37,7 +37,7 @@ internal static partial class DungeonPathfinder
|
|||
// ... at these heights from the opening's lowest vertex (a floor 6 m below a ledge's opening, say).
|
||||
private static readonly double[] LedgeZRefs = { 0, 3, -3, 6, -6, 12, -12 };
|
||||
// ... and, for a cell with no floor there, below the opening only.
|
||||
private static readonly double[] LedgeDownRefs = { 0, -3, -6, -9, -12, -18 };
|
||||
private static readonly double[] LedgeDownRefs = { 0, -3, -6, -9, -12, -15, -18 };
|
||||
|
||||
/// <summary>What closing the ledges did in the last dungeon (one line, for the build log), or null.</summary>
|
||||
internal static string? LedgeNote;
|
||||
|
|
@ -49,20 +49,30 @@ internal static partial class DungeonPathfinder
|
|||
{
|
||||
var list = new List<DungeonLedge>();
|
||||
var seen = new HashSet<ulong>();
|
||||
double lowest = LowestLook(graph);
|
||||
foreach (var n in graph.Values)
|
||||
foreach (uint nb in n.Neighbors)
|
||||
{
|
||||
if (!graph.ContainsKey(nb) || !seen.Add(EdgeKey(n.CellId, nb))) continue;
|
||||
if (!geo.TryGetDoorway(n.CellId, nb, out var d)) continue;
|
||||
var (nx, ny) = d.NormalFrom(n.CellId); // out of n, into nb
|
||||
double? ha = FloorInside(geo, n.CellId, d, -nx, -ny), hb = FloorInside(geo, nb, d, nx, ny);
|
||||
double? ha = FloorInside(geo, n.CellId, d, -nx, -ny, lowest), hb = FloorInside(geo, nb, d, nx, ny, lowest);
|
||||
if (ha is not { } a || hb is not { } b || Math.Abs(a - b) <= LedgeMeters) continue;
|
||||
list.Add(a > b ? new DungeonLedge(n.CellId, nb, a - b, d.X, d.Y, d.Z) : new DungeonLedge(nb, n.CellId, b - a, d.X, d.Y, d.Z));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private static double? FloorInside(DungeonGeometry geo, uint cell, DungeonDoorway d, double ux, double uy)
|
||||
/// <summary>Under every cell of the graph: as deep as a look for a floor under an opening goes.</summary>
|
||||
internal static double LowestLook(Dictionary<uint, DungeonNavNode> graph)
|
||||
=> graph.Count == 0 ? 0 : graph.Values.Min(n => (double)n.Z) - 2 * JumpDownStep;
|
||||
|
||||
// The floor just inside the opening on the cell's side, its own or (none) any under it, looked for as
|
||||
// deep as `lowest` (NaN: the LedgeDownRefs' 18 m). It went no deeper than 18 m (+1.5) before 2026-11-18:
|
||||
// Thread 0x000A's hall has a 30 x 20 m hole in its middle down to a floor 24 m below, no ledge was seen
|
||||
// round it, and its six floorless cells were walked across ("It tries to navigate over an opening
|
||||
// in the floor which is impossible").
|
||||
private static double? FloorInside(DungeonGeometry geo, uint cell, DungeonDoorway d, double ux, double uy, double lowest = double.NaN)
|
||||
{
|
||||
foreach (double inset in LedgeInsets)
|
||||
{
|
||||
|
|
@ -75,20 +85,38 @@ internal static partial class DungeonPathfinder
|
|||
// 0x039B's corridor at -6 opens through 0143 into a round room whose floor, at -12, is its other
|
||||
// cells'): the floor UNDER that side, whichever cell it is. Only under it: a level above is no
|
||||
// floor to land on (Tiny Hive's floorless tube cells found the next level's floor 5 m up).
|
||||
// Each height looked at covers LedgeDownBand either side, so together they leave no gap (at
|
||||
// 0.6 m round heights 3 m apart, a floor 9.7 m down was between two: Thread 0x0169's shaft, whose
|
||||
// cave floor slopes from -9 to -12, had two of its eight openings found as no ledge).
|
||||
foreach (double inset in LedgeInsets)
|
||||
{
|
||||
double x = d.X + ux * inset, y = d.Y + uy * inset;
|
||||
foreach (double dz in LedgeDownRefs)
|
||||
if (geo.TryFloorHeight(x, y, d.Z + dz, 0.6, out double h) && h <= d.Z + 0.6) return h;
|
||||
if (geo.TryFloorHeight(x, y, d.Z + dz, LedgeDownBand, out double h) && h <= d.Z + 0.6) return h;
|
||||
}
|
||||
if (double.IsNaN(lowest)) return null;
|
||||
// Nothing within 18 m at any inset: deeper (only then, so the floors found before are found as before).
|
||||
foreach (double inset in LedgeInsets)
|
||||
{
|
||||
double x = d.X + ux * inset, y = d.Y + uy * inset;
|
||||
for (double z = d.Z + LedgeDownRefs[^1] - JumpDownStep; z >= lowest; z -= JumpDownStep)
|
||||
if (geo.TryFloorHeight(x, y, z, LedgeDownBand, out double h) && h <= d.Z + 0.6) return h;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Half the 3 m between two LedgeDownRefs: every height below the opening is looked at.</summary>
|
||||
private const double LedgeDownBand = 1.5;
|
||||
|
||||
/// <summary>
|
||||
/// Closes each ledge in <paramref name="graph"/> (both ways) unless that leaves its two cells with no
|
||||
/// other way between them; those are returned (the only way on). The graph is changed in place.
|
||||
/// With <paramref name="hasFloor"/>, a ledge into air is closed even then: when nothing it alone
|
||||
/// leads to has a floor of its own (Thread 0x0169's shaft, four open-air cells over a cave), it
|
||||
/// leads nowhere to walk, and keeping it open had the walks step off into the shaft.
|
||||
/// </summary>
|
||||
internal static List<DungeonLedge> CloseLedges(Dictionary<uint, DungeonNavNode> graph, IReadOnlyList<DungeonLedge> ledges, out int closed)
|
||||
internal static List<DungeonLedge> CloseLedges(Dictionary<uint, DungeonNavNode> graph, IReadOnlyList<DungeonLedge> ledges, out int closed,
|
||||
Func<uint, bool>? hasFloor = null)
|
||||
{
|
||||
closed = 0;
|
||||
var kept = new List<DungeonLedge>();
|
||||
|
|
@ -99,6 +127,7 @@ internal static partial class DungeonPathfinder
|
|||
int loLinks = lo.Neighbors.RemoveAll(c => c == l.High);
|
||||
if (hiLinks + loLinks == 0) continue;
|
||||
if (Linked(graph, l.High, l.Low)) { closed++; continue; }
|
||||
if (hasFloor != null && !Walked(graph, l.Low).Any(hasFloor)) { closed++; continue; } // only air beyond it
|
||||
// The only way between them: put it back.
|
||||
for (int i = 0; i < Math.Max(1, hiLinks); i++) hi.Neighbors.Add(l.Low);
|
||||
for (int i = 0; i < Math.Max(1, loLinks); i++) lo.Neighbors.Add(l.High);
|
||||
|
|
@ -107,6 +136,21 @@ internal static partial class DungeonPathfinder
|
|||
return kept;
|
||||
}
|
||||
|
||||
// Every cell a walk (no drop edges) reaches from a, a included.
|
||||
private static HashSet<uint> Walked(Dictionary<uint, DungeonNavNode> graph, uint a)
|
||||
{
|
||||
var seen = new HashSet<uint> { a };
|
||||
var queue = new Queue<uint>();
|
||||
queue.Enqueue(a);
|
||||
while (queue.Count > 0)
|
||||
{
|
||||
if (!graph.TryGetValue(queue.Dequeue(), out var n)) continue;
|
||||
foreach (uint nb in n.Neighbors)
|
||||
if (graph.TryGetValue(nb, out var o) && !IsDropEdge(n, o) && seen.Add(nb)) queue.Enqueue(nb);
|
||||
}
|
||||
return seen;
|
||||
}
|
||||
|
||||
// a and b joined by a walk (no drop edges).
|
||||
private static bool Linked(Dictionary<uint, DungeonNavNode> graph, uint a, uint b)
|
||||
{
|
||||
|
|
@ -132,7 +176,7 @@ internal static partial class DungeonPathfinder
|
|||
var ledges = FindLedges(graph, geo);
|
||||
LedgeNoteLandblock = landblockKey;
|
||||
if (ledges.Count == 0) { LedgeNote = null; return; }
|
||||
var kept = CloseLedges(graph, ledges, out int closed);
|
||||
var kept = CloseLedges(graph, ledges, out int closed, geo.HasFloor);
|
||||
var inv = CultureInfo.InvariantCulture;
|
||||
LedgeNote = string.Format(inv, "{0} ledge(s) (floors over {1:0.#} m apart across an opening): {2} closed, walked round",
|
||||
ledges.Count, LedgeMeters, closed)
|
||||
|
|
|
|||
|
|
@ -155,16 +155,22 @@ internal static partial class DungeonPathfinder
|
|||
var closed = PortalClosedOpenings(graph, geo, hazardCells, portals, startCell, startAt, reports);
|
||||
double splitMs = clock.Elapsed.TotalMilliseconds;
|
||||
int laid = 0;
|
||||
// The walk-round counts are the last laying's (each round lays the whole walk again).
|
||||
using var holes = CountHoles();
|
||||
int walked0 = HolesWalkedRound, left0 = HolesLeft;
|
||||
|
||||
NavRouteParser route;
|
||||
Dictionary<uint, DungeonNavNode> g;
|
||||
for (int round = 0; ; round++)
|
||||
{
|
||||
HolesWalkedRound = walked0; HolesLeft = left0;
|
||||
g = WithoutOpenings(graph, closed, startCell);
|
||||
route = lay(g);
|
||||
laid++;
|
||||
foreach (var r in reports) r.Moved = r.Dropped = r.Bent = 0; // the last laying's
|
||||
var asLaid = geo != null && geo.PlacedCount > 0 ? LegsOf(route.Points, loop) : null;
|
||||
var unresolved = KeepOutOfPortals(route.Points, closed: loop, g, geo, portals, reports, wall);
|
||||
if (asLaid != null) WalkPortalLegsRoundObjects(route.Points, loop, geo!, portals, asLaid);
|
||||
if (unresolved.Count == 0 || round >= PortalMaxRounds) break;
|
||||
|
||||
// Legs no bend gets round: cut off the cell there (never the start), and lay it again.
|
||||
|
|
@ -563,6 +569,58 @@ internal static partial class DungeonPathfinder
|
|||
return unresolved;
|
||||
}
|
||||
|
||||
// ── The portal step's legs and the placed objects (2026-11-18) ───────────────
|
||||
// KeepOutOfPortals runs on the finished walk, after EmitSteps walked it round what the cells place. Its bend
|
||||
// corners and moved points keep clear of objects (ClearanceMemo and LegClearance see their walls), but the leg
|
||||
// a dropped point leaves (its neighbours joined) is never looked at, and a bend's legs are judged walkable at
|
||||
// 0.25 m: with an object near the portal, a bent leg could cut into it. Every Thread has its exit portal, so
|
||||
// every Thread patrol and explore takes this step. Each leg the step changed is checked again
|
||||
// (ThroughPlaced) and walked round on the floor; a walk round that would go into a portal's circle is not
|
||||
// taken: the portal keep-out wins (touching a portal takes the character through), and the leg counts in
|
||||
// HolesLeft.
|
||||
|
||||
/// <summary>The legs of the walk as laid (by the points' identity), each with its two ends' positions.</summary>
|
||||
private static Dictionary<(NavPoint, NavPoint), (double, double, double, double, double, double)> LegsOf(List<NavPoint> pts, bool loop)
|
||||
{
|
||||
var legs = new Dictionary<(NavPoint, NavPoint), (double, double, double, double, double, double)>(pts.Count);
|
||||
for (int i = 0; i < pts.Count; i++)
|
||||
{
|
||||
if (i + 1 >= pts.Count && !loop) break;
|
||||
var a = pts[i]; var b = pts[(i + 1) % pts.Count];
|
||||
legs[(a, b)] = (a.EW, a.NS, a.Z, b.EW, b.NS, b.Z);
|
||||
}
|
||||
return legs;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Walks round the placed objects every leg of <paramref name="pts"/> that is not in <paramref name="asLaid"/>
|
||||
/// as it was (a leg KeepOutOfPortals bent, or whose end it moved, or that a dropped point left), keeping every
|
||||
/// new leg out of the portals' circles; a leg with no such way round stays as it is (HolesLeft). Returns how
|
||||
/// many legs were walked round.
|
||||
/// </summary>
|
||||
internal static int WalkPortalLegsRoundObjects(List<NavPoint> pts, bool loop, DungeonGeometry geo, IReadOnlyList<PatrolPortal> portals,
|
||||
Dictionary<(NavPoint, NavPoint), (double, double, double, double, double, double)> asLaid)
|
||||
{
|
||||
if (geo.PlacedCount == 0 || pts.Count < 2) return 0;
|
||||
int walked = 0;
|
||||
bool Keeps(NavPoint p, NavPoint q) => PortalLegClear(null, portals, p, q);
|
||||
for (int i = 0; i < pts.Count; i++)
|
||||
{
|
||||
if (i + 1 >= pts.Count && !loop) break;
|
||||
var a = pts[i]; var b = pts[(i + 1) % pts.Count];
|
||||
if (asLaid.TryGetValue((a, b), out var was) && was == (a.EW, a.NS, a.Z, b.EW, b.NS, b.Z)) continue;
|
||||
if (!LegMeetsPlaced(geo, X(a), Y(a), a.Z * 240.0, X(b), Y(b), b.Z * 240.0)) continue;
|
||||
var leg = new List<NavPoint> { a, b };
|
||||
if (WalkRoundHoles(leg, geo, objectsOnly: true, accept: Keeps) == 0) continue;
|
||||
var corners = leg.GetRange(1, leg.Count - 2);
|
||||
foreach (var c in corners) { Tag(c, "object-round"); NotePortal(c, "round-object-by-portal"); }
|
||||
pts.InsertRange(i + 1, corners);
|
||||
i += corners.Count;
|
||||
walked++;
|
||||
}
|
||||
return walked;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Where the character at (px, py, pz) walks first when it stands inside a portal's circle: to just
|
||||
/// past the circle's edge, on walkable floor with some clearance, reached in a straight walk through
|
||||
|
|
|
|||
|
|
@ -110,6 +110,7 @@ internal static partial class DungeonPathfinder
|
|||
}
|
||||
_cachedGeometry = DungeonGeometry.Build(graph, portals, floors, walls);
|
||||
_geoLandblock = landblockKey;
|
||||
AddPlacedObjectsTo(landblockKey, _cachedGeometry, cellDat);
|
||||
// Doorways placed objects stand across (a spider web: DungeonPathfinder.Blocked.cs), then ledges
|
||||
// (DungeonPathfinder.Ledges.cs): closed in the cached graph, so every walk goes round them.
|
||||
if (ReferenceEquals(graph, _cachedGraph)) { CloseMapBlocksOf(landblockKey, graph, _cachedGeometry); _ledgesClosedOn = graph; }
|
||||
|
|
@ -340,6 +341,7 @@ internal static partial class DungeonPathfinder
|
|||
out int doorways,
|
||||
bool mergeSamePieces = true)
|
||||
{
|
||||
using var holes = CountHoles();
|
||||
doorways = 0;
|
||||
var pts = new List<NavPoint>();
|
||||
if (geo == null)
|
||||
|
|
@ -396,6 +398,10 @@ internal static partial class DungeonPathfinder
|
|||
{
|
||||
if (start != null && dest != null && rooms.RoomOf.TryGetValue(startCell, out int r0))
|
||||
CrossRoom(pts, graph, geo, rooms, r0, start, startCell, dest, destCell, revisit: false, wall);
|
||||
// One room, start to destination: the walk across it goes round what the cells place too (it went
|
||||
// straight on through: a stuck detour inside the room it stuck in headed back into the table).
|
||||
KeepPointsOutOfObjects(geo, pts, closed: false, wall, graph, rooms);
|
||||
WalkRoundObjectsOf(geo, pts, closed: false, start, dest);
|
||||
return pts;
|
||||
}
|
||||
|
||||
|
|
@ -446,9 +452,97 @@ internal static partial class DungeonPathfinder
|
|||
|
||||
DropCollinear(pts, closed);
|
||||
KeepLegsOffWalls(geo, pts, closed, wall);
|
||||
// A point laid inside something the cells place goes out of it (or goes) before the legs are walked round.
|
||||
KeepPointsOutOfObjects(geo, pts, closed, wall, graph, rooms);
|
||||
// Round something the cells place (an altar, a statue), not through it, on every walk laid here: the
|
||||
// patrol, the explore, a walk to somewhere, a stuck detour (2026-11-18: Thread 0x000A's walks went
|
||||
// through altars). A corner put in by KeepLegsOffWalls can't get a leg past an object in its middle
|
||||
// (the push out of it goes along the leg); this walks round on the floor. Holes in the floor are
|
||||
// still the explore's own pass (a tube's floorless cells would be walked round to nowhere).
|
||||
WalkRoundObjectsOf(geo, pts, closed, start, dest);
|
||||
return pts;
|
||||
}
|
||||
|
||||
// WalkRoundHoles for placed objects only, the closing leg of a loop included. A walk that ends (a detour, a walk
|
||||
// to somewhere) has its start and destination walked round too, then left off again (the caller has them): its
|
||||
// first and last legs were never looked at, so a stuck detour's first leg headed straight back through the
|
||||
// object it stuck on (0x0190 room 88's table, recovery #8: "stuck on the detour"), and of 648 walks laid past the
|
||||
// objects of nine dungeons, 421 had an end leg through one (2026-11-18, real dats). That covers the stuck
|
||||
// detours, dunroute, BuildingMap's end legs and each stretch of a jump walk (to its approach point).
|
||||
private static void WalkRoundObjectsOf(DungeonGeometry geo, List<NavPoint> pts, bool closed, NavPoint? start = null, NavPoint? dest = null)
|
||||
{
|
||||
if (geo.PlacedCount == 0) return;
|
||||
var laid = KindLog != null || PointLog != null ? new HashSet<NavPoint>(pts) : null;
|
||||
if (closed)
|
||||
{
|
||||
if (pts.Count < 2) return;
|
||||
pts.Add(pts[0]);
|
||||
WalkRoundHoles(pts, geo, objectsOnly: true);
|
||||
pts.RemoveAt(pts.Count - 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
var walk = new List<NavPoint>(pts.Count + 2);
|
||||
if (start != null) walk.Add(start);
|
||||
walk.AddRange(pts);
|
||||
if (dest != null) walk.Add(dest);
|
||||
if (walk.Count < 2 || WalkRoundHoles(walk, geo, objectsOnly: true) == 0) return;
|
||||
// WalkRoundHoles keeps the first and the last point as they are, so the ends come off as they went on.
|
||||
int from = start != null ? 1 : 0, to = walk.Count - (dest != null ? 1 : 0);
|
||||
pts.Clear();
|
||||
for (int i = from; i < to; i++) pts.Add(walk[i]);
|
||||
}
|
||||
if (laid != null)
|
||||
foreach (var p in pts)
|
||||
if (!laid.Contains(p)) Tag(p, "object-round");
|
||||
}
|
||||
|
||||
// How far a point laid inside a placed object may be pushed to get out (a 9 x 9 m statue's middle: 4.5 m).
|
||||
private const double ObjectPushMax = MiddlePushMax;
|
||||
|
||||
/// <summary>
|
||||
/// A point laid inside something the cells place (an approach point on a pedestal, a corner the string pull put
|
||||
/// under a table) is moved out of it to the wall distance, at most ObjectPushMax, as RoomMiddle's middle is; one
|
||||
/// no push gets out is dropped (nobody stands there, and the walk round goes from point to point). A loop keeps
|
||||
/// at least three points. With <paramref name="graph"/>, the push stays on the floor of the point's room
|
||||
/// (<paramref name="rooms"/>) or of its cell and the cells next to it: the walk round goes round objects, not
|
||||
/// through walls, so a point must not be pushed through one into the next room. Returns how many points were
|
||||
/// moved or dropped.
|
||||
/// </summary>
|
||||
internal static int KeepPointsOutOfObjects(DungeonGeometry geo, List<NavPoint> pts, bool closed, double wall = WallClearance,
|
||||
Dictionary<uint, DungeonNavNode>? graph = null, DungeonRooms? rooms = null)
|
||||
{
|
||||
if (geo.PlacedCount == 0) return 0;
|
||||
int changed = 0;
|
||||
for (int i = 0; i < pts.Count; i++)
|
||||
{
|
||||
var p = pts[i];
|
||||
if (!NavRouteParser.IsPlainWaypoint(p.Type)) continue;
|
||||
double x = DungeonGeometry.NavToWorld(p.EW), y = DungeonGeometry.NavToWorld(p.NS);
|
||||
if (!geo.TryFloorHeight(x, y, p.Z * 240.0, HoleStartBand, out double h)) continue; // no floor: not the object's to say
|
||||
if (!geo.InsidePlaced(x, y, h)) continue;
|
||||
changed++;
|
||||
IReadOnlyCollection<uint>? cells = null;
|
||||
if (graph != null)
|
||||
{
|
||||
uint cell = CellAt(graph, geo, p);
|
||||
if (rooms != null && rooms.RoomOf.ContainsKey(cell)) cells = RoomCells(rooms, cell);
|
||||
else if (graph.TryGetValue(cell, out var node)) cells = new List<uint>(node.Neighbors) { cell };
|
||||
}
|
||||
geo.PushClear(ref x, ref y, h, wall, ObjectPushMax, cells);
|
||||
if (!geo.InsidePlaced(x, y, h) && geo.OnWalkableFloor(x, y, h))
|
||||
{
|
||||
p.EW = DungeonGeometry.WorldToNav(x);
|
||||
p.NS = DungeonGeometry.WorldToNav(y);
|
||||
if (PointLog != null) Info(p).Why += Info(p).Why.Length > 0 ? ",out-of-object" : "out-of-object";
|
||||
continue;
|
||||
}
|
||||
if (closed && pts.Count <= 3) continue;
|
||||
pts.RemoveAt(i--);
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
// A leg brushing a wall: its least clearance (away from its end points) under this, or under
|
||||
// its end points' own when they are tighter (a narrow opening's centre).
|
||||
private const double LegMinClearance = 0.6;
|
||||
|
|
@ -633,11 +727,15 @@ internal static partial class DungeonPathfinder
|
|||
if (i == j)
|
||||
{
|
||||
if (!DoorwayPoints(graph, geo, rooms, steps[i].From, steps[i].To, wall, out approach, out exit, out narrow)) narrow = false;
|
||||
OutOfPlaced(geo, rooms, approach, steps[i].From, steps[i].From, steps[i].To);
|
||||
OutOfPlaced(geo, rooms, exit, steps[i].To, steps[i].From, steps[i].To);
|
||||
return;
|
||||
}
|
||||
|
||||
DoorwayPoints(graph, geo, rooms, steps[i].From, steps[i].To, wall, out approach, out _, out bool n0);
|
||||
DoorwayPoints(graph, geo, rooms, steps[j].From, steps[j].To, wall, out _, out exit, out bool n1);
|
||||
OutOfPlaced(geo, rooms, approach, steps[i].From, steps[i].From, steps[i].To);
|
||||
OutOfPlaced(geo, rooms, exit, steps[j].To, steps[j].From, steps[j].To);
|
||||
narrow = n0 || n1;
|
||||
var doors = new List<(DungeonDoorway Door, uint From, int Step)>();
|
||||
for (int k = i; k <= j; k++)
|
||||
|
|
@ -674,6 +772,84 @@ internal static partial class DungeonPathfinder
|
|||
if (narrow) { approach.Doorway = true; exit.Doorway = true; }
|
||||
}
|
||||
|
||||
// A doorway point inside something placed (2026-11-18: in buildings, beside a chair, a table or a bed, 20 of
|
||||
// the survey's walk corners were) is slid along the doorway's normal, the nearest first, to where it is on the
|
||||
// room's floor and in nothing; with no such spot, onto the opening's centre. The legs from it are then walked
|
||||
// round what it was in (EmitSteps), which a point inside one never could be.
|
||||
private const double OutOfPlacedStep = 0.25, OutOfPlacedSlide = 3.0, OutOfPlacedNearest = 0.5, FallbackFloorBand = 2.0;
|
||||
|
||||
private static void OutOfPlaced(DungeonGeometry geo, DungeonRooms rooms, NavPoint p, uint cell, uint a, uint b)
|
||||
{
|
||||
if (geo.PlacedCount == 0) return;
|
||||
double x = DungeonGeometry.NavToWorld(p.EW), y = DungeonGeometry.NavToWorld(p.NS), z = p.Z * 240.0;
|
||||
if (!InsidePlacedAt(geo, x, y, z)) return;
|
||||
if (!geo.TryGetDoorway(a, b, out var d))
|
||||
{
|
||||
// No opening known (a cell-centre fallback point, which may lie between the two rooms). Its height is the
|
||||
// two cells' centres' between, not a floor's (E74E#0: 32.6 over 0103's floor at 34.0, under the 0.45 m dais
|
||||
// 02000117 there): first the floor under it within FallbackFloorBand; in nothing there, it is only
|
||||
// put on that floor. Else the nearest spot round it, on any floor, that is in nothing.
|
||||
if (geo.TryFloorHeight(x, y, z, FallbackFloorBand, out double fh) && Math.Abs(fh - z) > 1.0)
|
||||
{
|
||||
z = fh;
|
||||
if (!geo.InsidePlaced(x, y, fh)) { p.Z = fh / 240.0; return; }
|
||||
}
|
||||
if (NearestOutOfPlaced(geo, ref x, ref y, z, OutOfPlacedSlide))
|
||||
{
|
||||
p.EW = DungeonGeometry.WorldToNav(x);
|
||||
p.NS = DungeonGeometry.WorldToNav(y);
|
||||
p.Z = z / 240.0;
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Along the normal, on the point's own side of the opening, no nearer to it than OutOfPlacedNearest.
|
||||
var (nx, ny) = d.NormalFrom(a);
|
||||
double side = (x - d.X) * nx + (y - d.Y) * ny < 0 ? -1 : 1;
|
||||
var cells = RoomCells(rooms, cell);
|
||||
for (double s = OutOfPlacedStep; s <= OutOfPlacedSlide + 1e-9; s += OutOfPlacedStep)
|
||||
foreach (double sign in new[] { 1.0, -1.0 })
|
||||
{
|
||||
double qx = x + nx * s * sign, qy = y + ny * s * sign;
|
||||
if (((qx - d.X) * nx + (qy - d.Y) * ny) * side < OutOfPlacedNearest) continue;
|
||||
if (!geo.OnFloorOfAny(cells, qx, qy, z) || InsidePlacedAt(geo, qx, qy, z)) continue;
|
||||
if (geo.ClearanceMemo(qx, qy, z, 0.6) <= 0.05) continue; // in or against a wall
|
||||
p.EW = DungeonGeometry.WorldToNav(qx);
|
||||
p.NS = DungeonGeometry.WorldToNav(qy);
|
||||
return;
|
||||
}
|
||||
if (InsidePlacedAt(geo, d.X, d.Y, d.Z)) return;
|
||||
p.EW = DungeonGeometry.WorldToNav(d.X);
|
||||
p.NS = DungeonGeometry.WorldToNav(d.Y);
|
||||
p.Z = d.Z / 240.0;
|
||||
}
|
||||
|
||||
/// <summary>Inside something placed, for a walker on the floor at (or within a metre of) z.</summary>
|
||||
internal static bool InsidePlacedAt(DungeonGeometry geo, double x, double y, double z)
|
||||
=> geo.InsidePlaced(x, y, geo.TryFloorHeight(x, y, z, 1.0, out double h) ? h : z);
|
||||
|
||||
/// <summary>
|
||||
/// Moves (x, y), inside something placed, to the nearest spot round it (rings 0.25 m apart out to
|
||||
/// <paramref name="maxR"/>, 16 ways; on a ring the clearest) that is on the floor (of <paramref name="cells"/> when
|
||||
/// given), in nothing, and not against a wall. False (and the point left) when there is none.
|
||||
/// </summary>
|
||||
internal static bool NearestOutOfPlaced(DungeonGeometry geo, ref double x, ref double y, double z, double maxR, IReadOnlyCollection<uint>? cells = null)
|
||||
{
|
||||
for (double r = OutOfPlacedStep; r <= maxR + 1e-9; r += OutOfPlacedStep)
|
||||
{
|
||||
double bestC = 0.05, bx = 0, by = 0;
|
||||
for (int k = 0; k < 16; k++)
|
||||
{
|
||||
double a = k * Math.PI / 8, qx = x + Math.Cos(a) * r, qy = y + Math.Sin(a) * r;
|
||||
if (cells != null ? !geo.OnFloorOfAny(cells, qx, qy, z) : !geo.OnWalkableFloor(qx, qy, z)) continue;
|
||||
if (InsidePlacedAt(geo, qx, qy, z)) continue;
|
||||
double c = geo.ClearanceMemo(qx, qy, geo.TryFloorHeight(qx, qy, z, 1.0, out double h) ? h : z, 1.0);
|
||||
if (c > bestC) { bestC = c; bx = qx; by = qy; }
|
||||
}
|
||||
if (bestC > 0.05) { x = bx; y = by; return true; }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ── Doorway points ───────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -922,6 +1098,9 @@ internal static partial class DungeonPathfinder
|
|||
: Tag(WorldPoint(DungeonGeometry.NavToWorld(nearest.EW), DungeonGeometry.NavToWorld(nearest.NS), nearest.Z, false), "room-middle-cell");
|
||||
// A one-cell dead end's origin is inside its end cap; a big room's middle can be a pillar.
|
||||
PushOffWalls(geo, mid, cells, MiddlePushMax, wall);
|
||||
// Still inside something the cells place (Thread 0x00C1 room 81: a 9 x 9 m statue fills the middle,
|
||||
// the explore stuck at its side): no middle to go to. A statue that big is seen past anyway.
|
||||
if (geo.InsidePlaced(DungeonGeometry.NavToWorld(mid.EW), DungeonGeometry.NavToWorld(mid.NS), mid.Z * 240.0)) return null;
|
||||
return mid;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -11,7 +11,14 @@
|
|||
// - on walkable floor, keeping the walk's wall clearance, or at least as much as the legs it
|
||||
// replaces had (LegClearance: a floor edge counts as a wall, so never over a ledge or a pit), and
|
||||
// - passing through the room of every point it skips (the explore must still walk into each room
|
||||
// it was laid through).
|
||||
// it was laid through), and
|
||||
// - staying on the floor all the way, a step at a time (OnFloorAll, as the hole rule judges a leg).
|
||||
// 2026-11-17, a DreamWeave Thread in 0x0278: a ramp climbs south from a room at -36 to a corridor
|
||||
// at -30 that runs back north over that room. The walk went up the ramp and back along the
|
||||
// corridor; seen from above every point of that U-turn lies on one line, so one straight leg north
|
||||
// "passed through" all their rooms, and its samples kept their clearance (none fell in the 7 m with
|
||||
// no floor between the room's end and the corridor). The character ran north along the bottom
|
||||
// into the room's end wall and stuck there ("running into a wall in a place that makes no sense").
|
||||
// Only plain waypoints are skipped, and never one in keepPoints: the middles of the rooms the explore walks
|
||||
// into (2026-11-16, enter and scan). A look into a dead end, in and out by one doorway, passes "through" the
|
||||
// room at its doorway: Thread 0x00B5's boss room lost its middle here and was only touched at the door.
|
||||
|
|
@ -85,6 +92,7 @@ internal static partial class DungeonPathfinder
|
|||
double needClear, double wall)
|
||||
{
|
||||
if (LegLeast(geo, pts[i], pts[j], wall, out _, out _, out _) < needClear - 0.01) return false;
|
||||
if (!LegOnFloor(geo, pts[i], pts[j])) return false;
|
||||
var must = new HashSet<int>();
|
||||
for (int k = i; k < j; k++) must.UnionWith(legRooms[k]);
|
||||
for (int k = i + 1; k < j; k++)
|
||||
|
|
|
|||
|
|
@ -365,6 +365,7 @@ internal static partial class DungeonPathfinder
|
|||
DungeonGeometry? geo = null, IReadOnlySet<uint>? hazardCells = null,
|
||||
double startNS = double.NaN, double startEW = double.NaN, double startZ = 0, double destZ = 0)
|
||||
{
|
||||
using var holes = CountHoles();
|
||||
var route = new NavRouteParser { RouteType = NavRouteType.Once };
|
||||
|
||||
// With the dungeon map geometry: straight on through doorways, straight across rooms.
|
||||
|
|
@ -854,6 +855,25 @@ internal static partial class DungeonPathfinder
|
|||
DungeonPatrolOptions? options = null,
|
||||
IReadOnlyList<PatrolPortal>? portals = null,
|
||||
(double X, double Y, double Z)? startAt = null)
|
||||
{
|
||||
// One build: every walk round of it counts (HolesWalkedRound / HolesLeft), and the patrol's notes say so.
|
||||
using var holes = CountHoles();
|
||||
bool outermost = _holeCountDepth == 1;
|
||||
var route = BuildPatrolRouteCore(graph, startCell, hazardCells, geo, options, portals, startAt);
|
||||
if (outermost && PointLog != null && (HolesWalkedRound > 0 || HolesLeft > 0))
|
||||
MainRouteNote = (MainRouteNote == null ? "" : MainRouteNote + "; ")
|
||||
+ $"objects and holes: {HolesWalkedRound} leg(s) walked round" + (HolesLeft > 0 ? $", {HolesLeft} with no way round" : "");
|
||||
return route;
|
||||
}
|
||||
|
||||
private static NavRouteParser BuildPatrolRouteCore(
|
||||
Dictionary<uint, DungeonNavNode> graph,
|
||||
uint startCell,
|
||||
IReadOnlySet<uint>? hazardCells,
|
||||
DungeonGeometry? geo,
|
||||
DungeonPatrolOptions? options,
|
||||
IReadOnlyList<PatrolPortal>? portals,
|
||||
(double X, double Y, double Z)? startAt)
|
||||
{
|
||||
LastPortalAvoidance = null;
|
||||
var o = (options ?? DungeonPatrolOptions.Default).Clamped();
|
||||
|
|
@ -959,11 +979,95 @@ internal static partial class DungeonPathfinder
|
|||
// The map geometry is there but the room patrol found nothing to walk (the start is cut
|
||||
// off from every doorway): the cell walk's points still keep off the walls.
|
||||
if (geo != null)
|
||||
{
|
||||
foreach (var p in route.Points)
|
||||
PushOffWalls(geo, Tag(p, "cell-walk"), null, CornerPushMax, o.WallClearance);
|
||||
// And round what the cells place, as the room patrol's walks are (EmitSteps): with the loader's posts,
|
||||
// pillars and spheres on the map (2026-11-18), Thread 0x0169's cell walk went through 20 of them, every
|
||||
// one with a way round on the floor. A cell's centre under one (a pillar in the middle of a room) goes
|
||||
// out of it first: the walk round goes from point to point.
|
||||
KeepPointsOutOfObjects(geo, route.Points, closed: true, o.WallClearance, graph);
|
||||
WalkRoundObjectsOf(geo, route.Points, closed: true);
|
||||
}
|
||||
return route;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The straight walk a-b at a body's height on the dungeon map: on the floor all the way (LegOnFloor, the hole
|
||||
/// rule's test, which also stops at a placed object on the floor it follows) and through nothing the cells place
|
||||
/// (ThroughPlaced). A sight line at eye height doesn't say that: one that raises the eye 1.2 m and looks from
|
||||
/// 1.45 m up, so a 1 m altar or a 0.9 m table (0x0190's 0x020002FB) never blocked it, and the line of sight to a
|
||||
/// later waypoint skipped the corners laid round one (2026-11-18). The patrol's first
|
||||
/// waypoint go by it. An end up on something placed is judged from where the leg leaves it; an end the map can't
|
||||
/// place clear of what is there leaves the walk to the sight line (true).
|
||||
/// </summary>
|
||||
internal static bool StraightWalkClear(DungeonGeometry geo, NavPoint a, NavPoint b)
|
||||
{
|
||||
if (geo.PlacedCount > 0 && !(FromWhereItStands(geo, ref a, b) && FromWhereItStands(geo, ref b, a))) return true;
|
||||
return LegOnFloor(geo, a, b) && !LegMeetsPlaced(geo, X(a), Y(a), a.Z * 240.0, X(b), Y(b), b.Z * 240.0);
|
||||
}
|
||||
|
||||
// One end of the walk test. The leg tests measure from the map's floor under a point, so a character standing on a
|
||||
// dais, half way up a ramp or on a platform read as inside it, and every leg failed at its first sample: a patrol
|
||||
// started from there went for waypoint 0, across the room behind a pillar maybe (the "runs into a wall on login" the
|
||||
// first-waypoint pick is there for) (review of wf/obst-int). An end up
|
||||
// on something placed (DungeonGeometry.OnTopOfPlaced) is moved along the leg to where it leaves what is under it: that
|
||||
// stretch is the walk across its top. False, the walk not judged, for an end inside something at its own height too
|
||||
// (wedged against it where the footprint is a little big), or a leg that never leaves what it stands on.
|
||||
private static bool FromWhereItStands(DungeonGeometry geo, ref NavPoint end, NavPoint other)
|
||||
{
|
||||
double ex = X(end), ey = Y(end), ez = end.Z * 240.0;
|
||||
if (!geo.TryFloorHeight(ex, ey, ez, HoleStartBand, out double zf)) zf = ez;
|
||||
if (!geo.InsidePlaced(ex, ey, zf)) return true;
|
||||
if (!geo.OnTopOfPlaced(ex, ey, ez, zf)) return false;
|
||||
double ox = X(other), oy = Y(other), oz = other.Z * 240.0;
|
||||
double dx = ox - ex, dy = oy - ey, len = Math.Sqrt(dx * dx + dy * dy);
|
||||
int n = (int)Math.Ceiling(len / PlacedFineStep);
|
||||
for (int s = 1; s <= n; s++)
|
||||
{
|
||||
double t = (double)s / n, x = ex + dx * t, y = ey + dy * t;
|
||||
if (geo.TryFloorHeight(x, y, zf, HoleStep, out double h) || geo.TryFloorHeight(x, y, ez + (oz - ez) * t, HoleStep, out h)) zf = h;
|
||||
if (geo.InsidePlaced(x, y, zf)) continue;
|
||||
end = new NavPoint { Type = NavPointType.Point, EW = DungeonGeometry.WorldToNav(x), NS = DungeonGeometry.WorldToNav(y), Z = zf / 240.0 };
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>The straight walk a-b goes through something the cells place, on the floor it follows: ThroughPlaced,
|
||||
/// or a crossing between its samples (CrossesPlaced).</summary>
|
||||
internal static bool LegMeetsPlaced(DungeonGeometry geo, double ax, double ay, double az, double bx, double by, double bz)
|
||||
=> ThroughPlaced(geo, ax, ay, az, bx, by, bz) || CrossesPlaced(geo, ax, ay, az, bx, by, bz);
|
||||
|
||||
// ThroughPlaced looks every 0.5 m, and a rail (0x020003B3 is 0.13 m across), a post or a narrow end of a bench fits
|
||||
// between two looks: a leg across one was taken as clear and went on as laid. This looks at the solid models' own
|
||||
// spacing (0.1 m); the floor is found every HoleSample as ThroughPlaced finds it, the looks between at the last
|
||||
// floor found. Samples with no floor are left out as there.
|
||||
private const double PlacedFineStep = 0.1;
|
||||
|
||||
internal static bool CrossesPlaced(DungeonGeometry geo, double ax, double ay, double az, double bx, double by, double bz)
|
||||
{
|
||||
if (geo.PlacedCount == 0) return false;
|
||||
double dx = bx - ax, dy = by - ay, len = Math.Sqrt(dx * dx + dy * dy);
|
||||
if (len < 2 * PlacedFineStep) return false;
|
||||
if (!geo.TryFloorHeight(ax, ay, az, HoleStartBand, out double zf)) zf = az;
|
||||
int n = (int)Math.Ceiling(len / PlacedFineStep);
|
||||
bool floor = true;
|
||||
double nextFloorAt = 0;
|
||||
for (int s = 1; s < n; s++)
|
||||
{
|
||||
double t = (double)s / n, d = t * len, x = ax + dx * t, y = ay + dy * t;
|
||||
if (d >= nextFloorAt)
|
||||
{
|
||||
floor = geo.TryFloorHeight(x, y, zf, HoleStep, out double h) || geo.TryFloorHeight(x, y, az + (bz - az) * t, HoleStep, out h);
|
||||
if (floor) zf = h;
|
||||
nextFloorAt = d + HoleSample;
|
||||
}
|
||||
if (floor && geo.InsidePlaced(x, y, zf)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Canonical undirected-edge key (order-independent).
|
||||
private static ulong EdgeKey(uint a, uint b)
|
||||
=> a < b ? ((ulong)a << 32) | b : ((ulong)b << 32) | a;
|
||||
|
|
|
|||
|
|
@ -214,6 +214,7 @@ public sealed partial class RynthAiPlugin
|
|||
if (!_objectCache.IsOnGround(id) && _objectCache.GetContainerId(id) != 0)
|
||||
{
|
||||
LootDiag($"[RynthAi] Ground loot: pickup confirmed for 0x{(uint)id:X8} '{_groundTargetName}'.");
|
||||
NotePerDayPickedUp(id); // Keep # per day: it counts now
|
||||
if (DescribeLootPickup(id, _groundTargetAction, _groundTargetName, _groundTargetRule,
|
||||
_groundTargetIsSalvage, IsStackAtSend(id), where: "ground") is { } described)
|
||||
WriteItemInfoLine(described.Line, described.ChatType);
|
||||
|
|
@ -284,6 +285,7 @@ public sealed partial class RynthAiPlugin
|
|||
: Host.UseObject(uid);
|
||||
_groundPickupAttempts++;
|
||||
_groundPickupRequestedAt = now;
|
||||
if (sent) NotePerDaySent(unchecked((int)uid)); // Keep # per day: on its way
|
||||
LootDiag($"[RynthAi] Ground loot: pickup {(sent ? "sent" : "rejected")} for 0x{uid:X8} attempt {_groundPickupAttempts}.");
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -39,6 +39,8 @@ public sealed class HudState
|
|||
/// <summary>Pet row: the summon that is out (health, time left), else the next combat essence.</summary>
|
||||
public bool MiniShowPet = true;
|
||||
public bool MiniShowGems = true;
|
||||
/// <summary>Loot row: the loot profile in use, a dropdown of LootProfiles that switches it.</summary>
|
||||
public bool MiniShowLootProfile = true;
|
||||
public bool MiniShowToggles = true;
|
||||
/// <summary>Obsolete since 2026-10-20 (kept so huds.json loads): the Bank section's switch is RynthILT's (copied once).</summary>
|
||||
public bool MiniShowBank = true;
|
||||
|
|
|
|||
|
|
@ -21,6 +21,8 @@
|
|||
// Target the creature combat is attacking: name, health bar, distance
|
||||
// Pet the summon that is out (health bar, time left), else (while a server plugin is active)
|
||||
// the next combat essence and whether it is ready
|
||||
// Loot the loot profile in use, a dropdown of LootProfiles that switches it (the dashboard
|
||||
// pickers' list and path; chat says which profile is in use)
|
||||
// Slots 5 × 6 quick-use item grid; click uses the item (an empty slot takes the selected
|
||||
// pack item), right-click assigns / clears, and items dragged from the game's
|
||||
// inventory or the RynthCore Inventory window drop straight into a slot. Ctrl+wheel
|
||||
|
|
@ -309,7 +311,7 @@ internal sealed class MiniRemoteHud
|
|||
if (!s.MiniRemoteHorizontal) return colW;
|
||||
int cols = 0;
|
||||
if (s.MiniShowStats || s.MiniShowTarget || s.MiniShowPet) cols++;
|
||||
if (s.MiniShowGems || ShowToggles(s)) cols++;
|
||||
if (s.MiniShowGems || s.MiniShowLootProfile || ShowToggles(s)) cols++;
|
||||
if (s.MiniShowRebuff || s.MiniShowTranslate || _serverEconomyDrawn) cols++;
|
||||
cols = Math.Max(1, cols);
|
||||
return cols * colW + (cols - 1) * ImGui.GetStyle().ItemSpacing.X;
|
||||
|
|
@ -390,7 +392,7 @@ internal sealed class MiniRemoteHud
|
|||
RenderStatusSections(s, remote);
|
||||
ImGui.EndChild();
|
||||
}
|
||||
if (s.MiniShowGems || ShowToggles(s))
|
||||
if (s.MiniShowGems || s.MiniShowLootProfile || ShowToggles(s))
|
||||
{
|
||||
BeginColumn("##mrcolactions", colW);
|
||||
RenderActionSections(s);
|
||||
|
|
@ -445,6 +447,7 @@ internal sealed class MiniRemoteHud
|
|||
|
||||
private void RenderActionSections(HudState s)
|
||||
{
|
||||
if (s.MiniShowLootProfile) RenderLootProfile(s);
|
||||
if (s.MiniShowGems) RenderSlots(s);
|
||||
if (ShowToggles(s)) RenderToggles(_hud.Dashboard.Settings);
|
||||
}
|
||||
|
|
@ -784,11 +787,47 @@ internal sealed class MiniRemoteHud
|
|||
ImGui.EndPopup();
|
||||
}
|
||||
|
||||
// The Loot row's list while its dropdown is open (a copy of the dashboard's, taken each frame it shows).
|
||||
private string[] _lootList = Array.Empty<string>();
|
||||
|
||||
/// <summary>
|
||||
/// The Loot row: the loot profile in use, and a dropdown of LootProfiles (*.utl, *.json; the
|
||||
/// dashboard's list, which follows the folder within 3 s). A pick switches it on the pump thread
|
||||
/// through the dashboard pickers' own path (SelectProfileAtIndex), which saves it and says so in chat.
|
||||
/// </summary>
|
||||
private void RenderLootProfile(HudState s)
|
||||
{
|
||||
var dash = _hud.Dashboard;
|
||||
string shown = Loot.LootProfileList.ShownName(dash.Settings.CurrentLootPath);
|
||||
SafeImGui.TextColored(ColLabel, "Loot:");
|
||||
float labelW = ImGui.GetItemRectSize().X + ImGui.GetStyle().ItemSpacing.X;
|
||||
ImGui.SameLine();
|
||||
// A fixed width (the column's), so the auto-resizing window can't grow from it.
|
||||
ImGui.SetNextItemWidth(Math.Max(80f, ColumnWidth(s) - labelW));
|
||||
bool open = ImGui.BeginCombo("##mrloot", shown, ImGuiComboFlags.HeightLarge);
|
||||
if (!open && ImGui.IsItemHovered())
|
||||
SafeImGui.SetTooltip("The loot profile in use: " + shown + "\nPick another to switch to it (chat says so).\n" +
|
||||
"Lists RynthAi\\LootProfiles; a file copied in shows within a few seconds.");
|
||||
if (!open) return;
|
||||
_lootList = dash.LootProfileNames();
|
||||
for (int i = 0; i < _lootList.Length; i++)
|
||||
{
|
||||
string name = _lootList[i];
|
||||
bool selected = string.Equals(name, shown, StringComparison.OrdinalIgnoreCase);
|
||||
ImGui.PushID(i);
|
||||
if (ImGui.Selectable(name, selected))
|
||||
_hud.Post(() => dash.SelectLootProfileByName(name));
|
||||
if (selected) ImGui.SetItemDefaultFocus();
|
||||
ImGui.PopID();
|
||||
}
|
||||
ImGui.EndCombo();
|
||||
}
|
||||
|
||||
private void RenderToggles(LegacyUiSettings settings)
|
||||
{
|
||||
var dash = _hud.Dashboard;
|
||||
if (!ImGui.BeginTable("##mrtoggles", 3, ImGuiTableFlags.SizingStretchSame)) return;
|
||||
Toggle("Macro", settings.IsMacroRunning, _ => dash.TogglePanelMacro());
|
||||
Toggle("Macro", settings.IsMacroRunning, _ => dash.TogglePanelMacro("the Mini Remote's Macro toggle"));
|
||||
Toggle("Combat", settings.EnableCombat, on => dash.SetSubsystemEnabled(0, on));
|
||||
Toggle("Buff", settings.EnableBuffing, on => dash.SetSubsystemEnabled(1, on));
|
||||
Toggle("Nav", settings.EnableNavigation, on => dash.SetSubsystemEnabled(2, on));
|
||||
|
|
@ -836,6 +875,8 @@ internal sealed class MiniRemoteHud
|
|||
Flag("Session stats", ref s.MiniShowStats);
|
||||
Flag("Attack target", ref s.MiniShowTarget);
|
||||
Flag("Pet / summon", ref s.MiniShowPet);
|
||||
Flag("Loot profile", ref s.MiniShowLootProfile);
|
||||
if (ImGui.IsItemHovered()) ImGui.SetTooltip("A Loot row: the loot profile in use, and a dropdown to switch it.");
|
||||
Flag("Item slots", ref s.MiniShowGems);
|
||||
// The drawer's dashboard has these switches already; the setting is for the windows.
|
||||
if (!InDrawer) Flag("Toggles", ref s.MiniShowToggles);
|
||||
|
|
|
|||
|
|
@ -813,13 +813,16 @@ internal sealed class LegacyAdvancedSettingsUi
|
|||
ImGui.SetTooltip("Which monster to attack, among those of the highest priority inside Monster Range.\nLeast turning: the one needing the smallest turn to face. Unknown health counts as full.");
|
||||
ImGui.Checkbox("Target Lock", ref _settings.TargetLock);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("On: keeps the target it picked until it dies or leaves Monster Range, even when a higher-priority monster shows up.\nOff: a higher-priority monster in range takes over at once, and it switches whenever another monster is clearly better by the Targeting rule.");
|
||||
ImGui.SetTooltip("On: keeps the target it picked until it dies or leaves Monster Range, even when a higher-priority monster shows up.\nWith Targeting on Closest, a monster that reaches you (within 5 yd) takes over from a target more than 6.5 m off.\nOff: a higher-priority monster in range takes over at once, and it switches whenever another monster is clearly better by the Targeting rule.");
|
||||
ImGui.Checkbox("Fight the monster I select", ref _settings.FightSelectedTarget);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip(LegacyUiSettings.FightSelectedTargetTip);
|
||||
ImGui.Checkbox("Melee through walls", ref _settings.MeleeThroughWalls);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip(LegacyUiSettings.MeleeThroughWallsTip);
|
||||
ImGui.Checkbox("Debuff every monster in range before attacking", ref _settings.DebuffAllBeforeAttacking);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip(LegacyUiSettings.DebuffAllBeforeAttackingTip);
|
||||
|
||||
ImGui.Spacing();
|
||||
ImGui.Text("Corpse Acquisition (Yards)");
|
||||
|
|
@ -1115,22 +1118,22 @@ internal sealed class LegacyAdvancedSettingsUi
|
|||
break;
|
||||
|
||||
case "Looting":
|
||||
ImGui.Checkbox("Enable Looting", ref _settings.EnableLooting);
|
||||
// The loot profile picker (the dashboard's LOOT list), and beside it Loot Mode, which
|
||||
// decides whether that profile is used at all.
|
||||
// The loot profile picker first (the dashboard's LOOT list, the same switch), then Loot
|
||||
// Mode, which decides whether that profile is used at all.
|
||||
string[]? lootFiles = LootProfiles?.Invoke();
|
||||
if (lootFiles != null && lootFiles.Length > 0 && SelectLootProfile != null)
|
||||
{
|
||||
int lootIdx = Math.Clamp(_settings.LootProfileIdx, 0, lootFiles.Length - 1);
|
||||
ImGui.SetNextItemWidth(200);
|
||||
ImGui.SetNextItemWidth(240);
|
||||
if (ImGui.Combo("Loot Profile", ref lootIdx, lootFiles, lootFiles.Length) && lootIdx != _settings.LootProfileIdx)
|
||||
SelectLootProfile(lootIdx);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip(Loot.LootModes.IsRares(_settings.LootMode)
|
||||
? "The loot profile. Not used while Loot Mode is Rares and needed mana stones only."
|
||||
: "The loot profile: what corpses, chests and ground items give up.");
|
||||
ImGui.SameLine();
|
||||
: "The loot profile: what corpses, chests and ground items give up.\n" +
|
||||
"The same list as the dashboard's Loaded files (LOOT) and the Mini Remote's Loot row.");
|
||||
}
|
||||
ImGui.Checkbox("Enable Looting", ref _settings.EnableLooting);
|
||||
_settings.LootMode = Loot.LootModes.Clamp(_settings.LootMode);
|
||||
ImGui.SetNextItemWidth(240);
|
||||
ImGui.Combo("Loot Mode", ref _settings.LootMode, Loot.LootModes.Labels, Loot.LootModes.Labels.Length);
|
||||
|
|
@ -1141,7 +1144,12 @@ internal sealed class LegacyAdvancedSettingsUi
|
|||
"nothing else (no salvage, no Learn Unknown Spells, no Mana Tap). Recover My Corpse still works.\n" +
|
||||
"Also /ra loot mode profile|rares, and the meta setting LootMode (0 or 1).");
|
||||
ImGui.Checkbox("Boost Loot Priority", ref _settings.BoostLootPriority);
|
||||
// "Loot Only Rare Corpses" is hidden: nothing reads LootOnlyRareCorpses.
|
||||
ImGui.Checkbox("Loot Only Rare Corpses", ref _settings.LootOnlyRareCorpses);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("Only a corpse that generated a rare is opened (its description says \"This corpse\n" +
|
||||
"generated a rare item!\"); every other corpse is left closed, for rare farming.\n" +
|
||||
"With Loot Mode \"Rares and needed mana stones only\" the rare is all it takes.\n" +
|
||||
"Your own corpse (Recover My Corpse) is always recovered.");
|
||||
ImGui.Checkbox("Learn Unknown Spells", ref _settings.ReadUnknownScrolls);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("Loots scrolls of spells you don't know and can learn (magic school trained or\nspecialized, skill high enough), and reads them when it's safe. Scrolls already\nin your pack are read too.");
|
||||
|
|
@ -1155,7 +1163,8 @@ internal sealed class LegacyAdvancedSettingsUi
|
|||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("When the pickup is done the chest stays open and chat says what was taken,\n" +
|
||||
"so you can check it and take anything your profile missed. Untick it and\n" +
|
||||
"RynthAi closes the chest when it's done (some chests lock again on close).");
|
||||
"RynthAi closes the chest when it's done (some chests lock again on close).\n" +
|
||||
"A chest it took nothing from is always left open.");
|
||||
ImGui.Unindent();
|
||||
}
|
||||
ImGui.Checkbox("Loot Nearby Chests", ref _settings.LootNearbyChests);
|
||||
|
|
|
|||
|
|
@ -454,7 +454,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
_settings.SelectedProfile = activeProfile;
|
||||
ApplyUiStateFromSettings();
|
||||
|
||||
_settings.IsMacroRunning = _settings.StartMacroOnLogin;
|
||||
_settings.SetMacroRunning(_settings.StartMacroOnLogin, "Start Macro On Login (profile load)");
|
||||
_settings.CurrentState = "Default";
|
||||
_settings.BotAction = "Default";
|
||||
|
||||
|
|
@ -542,7 +542,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
_charFolder = string.Empty;
|
||||
_settingsFilePath = string.Empty;
|
||||
_lastSavedJson = string.Empty;
|
||||
_settings.IsMacroRunning = false;
|
||||
_settings.SetMacroRunning(false, "the character session ending (logout or character change)");
|
||||
_settings.CurrentState = "Default";
|
||||
_settings.BotAction = "Default";
|
||||
}
|
||||
|
|
@ -1427,6 +1427,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
TargetLock = s.TargetLock,
|
||||
FightSelectedTarget = s.FightSelectedTarget,
|
||||
MeleeThroughWalls = s.MeleeThroughWalls,
|
||||
DebuffAllBeforeAttacking = s.DebuffAllBeforeAttacking,
|
||||
RingRange = s.RingRange,
|
||||
ApproachRange = s.ApproachRange,
|
||||
CorpseApproachRangeMax = s.CorpseApproachRangeMax,
|
||||
|
|
@ -1721,6 +1722,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
if (p.TargetLock is bool targetLock) s.TargetLock = targetLock; // absent = unchanged
|
||||
if (p.FightSelectedTarget is bool fightSel) s.FightSelectedTarget = fightSel; // absent = unchanged
|
||||
if (p.MeleeThroughWalls is bool meleeWalls) s.MeleeThroughWalls = meleeWalls; // absent = unchanged
|
||||
if (p.DebuffAllBeforeAttacking is bool debuffAll) s.DebuffAllBeforeAttacking = debuffAll; // absent = unchanged
|
||||
s.RingRange = p.RingRange;
|
||||
s.ApproachRange = p.ApproachRange;
|
||||
s.CorpseApproachRangeMax = p.CorpseApproachRangeMax;
|
||||
|
|
@ -2183,6 +2185,9 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
dst.UnboxAetheriaWhenIdle = tmp.UnboxAetheriaWhenIdle;
|
||||
dst.AutoConfirmCraft = tmp.AutoConfirmCraft;
|
||||
dst.AutoConfirmCraftPercent = tmp.AutoConfirmCraftPercent;
|
||||
dst.MakeKitsWhenLow = tmp.MakeKitsWhenLow;
|
||||
dst.MakeKitsBelow = Math.Clamp(tmp.MakeKitsBelow, 1, MiniRemote.Crafting.KitAuto.MaxBelow);
|
||||
dst.MakeKitsUpTo = Math.Clamp(tmp.MakeKitsUpTo, 1, MiniRemote.Crafting.KitAuto.MaxUpTo);
|
||||
dst.EnableCombineSalvage = tmp.EnableCombineSalvage;
|
||||
dst.CombineBagsDuringSalvage = tmp.CombineBagsDuringSalvage;
|
||||
dst.SalvageWithoutPanel = tmp.SalvageWithoutPanel;
|
||||
|
|
@ -2257,6 +2262,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
dst.TargetLock = tmp.TargetLock;
|
||||
dst.FightSelectedTarget = tmp.FightSelectedTarget;
|
||||
dst.MeleeThroughWalls = tmp.MeleeThroughWalls;
|
||||
dst.DebuffAllBeforeAttacking = tmp.DebuffAllBeforeAttacking;
|
||||
dst.RingRange = tmp.RingRange;
|
||||
dst.HandlerRingEvade = tmp.HandlerRingEvade; // obsolete (RynthILT's now): carried so the profile keeps it for RynthILT's one-time import
|
||||
dst.ApproachRange = tmp.ApproachRange;
|
||||
|
|
@ -2275,6 +2281,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
dst.CustomPetRange = tmp.CustomPetRange;
|
||||
dst.PetMinMonsters = tmp.PetMinMonsters;
|
||||
dst.PetAutoRefill = tmp.PetAutoRefill;
|
||||
dst.PetElement = tmp.PetElement ?? string.Empty; // read through PetChoice.NormalizeElement
|
||||
dst.AdvancedOptions = tmp.AdvancedOptions;
|
||||
dst.MineOnly = tmp.MineOnly;
|
||||
dst.ShowEditor = tmp.ShowEditor;
|
||||
|
|
@ -2791,14 +2798,15 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
|
||||
private void RefreshNavFiles()
|
||||
{
|
||||
// The top of NavProfiles, then its subfolders as "Folder\Name" (NavFileList, 2026-11-22:
|
||||
// VirindiTank navs dropped in as a folder never showed).
|
||||
var list = new List<string> { "None" };
|
||||
int sel = 0;
|
||||
if (Directory.Exists(_navFolder))
|
||||
foreach (string file in Directory.GetFiles(_navFolder, "*.nav"))
|
||||
{
|
||||
list.Add(Path.GetFileNameWithoutExtension(file));
|
||||
if (file.Equals(_settings.CurrentNavPath, StringComparison.OrdinalIgnoreCase)) sel = list.Count - 1;
|
||||
}
|
||||
foreach (string name in NavFileList.List(_navFolder))
|
||||
{
|
||||
list.Add(name);
|
||||
if (Path.Combine(_navFolder, name + ".nav").Equals(_settings.CurrentNavPath, StringComparison.OrdinalIgnoreCase)) sel = list.Count - 1;
|
||||
}
|
||||
lock (_profileListsLock) { _navFiles.Clear(); _navFiles.AddRange(list); }
|
||||
_selectedNavIdx = sel;
|
||||
}
|
||||
|
|
@ -2806,6 +2814,85 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
private DateTime _navFolderStamp, _lootFolderStamp, _metaFolderStamp, _profileFolderStamp;
|
||||
private long _nextNavFolderCheckMs;
|
||||
|
||||
// ── VirindiTank navs in the wrong folder (StrayNavs) ──────────────────
|
||||
// Null-safe where read: the host tests build the dashboard without its constructor.
|
||||
private List<StrayNav>? _strayNavs = new();
|
||||
private string? _strayNavText = string.Empty;
|
||||
private DateTime _strayStamp;
|
||||
private bool _strayLooked;
|
||||
private int _strayNoticeCount; // how many the last chat line was about (a new one only for more)
|
||||
private string? _strayChatPending = string.Empty;
|
||||
private List<string>? _strayFolders;
|
||||
|
||||
/// <summary>The folders the stray-nav check looks in (the host tests point it at scratch folders).</summary>
|
||||
internal List<string> StrayFolders { set => _strayFolders = value; }
|
||||
|
||||
private static List<string> StrayCandidateFolders() => StrayNavs.CandidateFolders(
|
||||
RynthCore.Install.RynthInstallPaths.CoreDir,
|
||||
RynthCore.Install.RynthInstallPaths.SuiteDir,
|
||||
RynthCore.Install.RynthInstallPaths.RynthAiDir,
|
||||
Environment.GetEnvironmentVariable("RYNTHNAV_NAVDATA"),
|
||||
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthnav.json"));
|
||||
|
||||
/// <summary>
|
||||
/// Looks again for VirindiTank navs outside NavProfiles when one of the folders worth a look
|
||||
/// changed (or the first time). Sets the Nav panel's line and queues one chat line when there
|
||||
/// are more than the last line was about. Plugin tick, from <see cref="TickNavFolder"/>.
|
||||
/// </summary>
|
||||
private void RefreshStrayNavs(DateTime navStamp, bool force = false)
|
||||
{
|
||||
try
|
||||
{
|
||||
List<string> folders = _strayFolders ??= StrayCandidateFolders(); // once a session
|
||||
DateTime stamp = navStamp; // a nav copied into NavProfiles settles one too
|
||||
foreach (string f in folders)
|
||||
{
|
||||
try { DateTime t = Directory.GetLastWriteTimeUtc(f); if (t > stamp) stamp = t; } // a missing folder: 1601
|
||||
catch { }
|
||||
}
|
||||
if (!force && _strayLooked && stamp == _strayStamp) return;
|
||||
_strayLooked = true;
|
||||
_strayStamp = stamp;
|
||||
|
||||
_strayNavs = StrayNavs.Find(folders, _navFolder);
|
||||
_strayNavText = StrayNavs.Notice(_strayNavs, _navFolder);
|
||||
if (_strayNavs.Count > _strayNoticeCount)
|
||||
{
|
||||
_strayNoticeCount = _strayNavs.Count;
|
||||
_strayChatPending = _strayNavText + " Nav panel: Copy them into NavProfiles (or /ra nav import).";
|
||||
_host.Log("[RynthAi] " + _strayChatPending);
|
||||
}
|
||||
else if (_strayNavs.Count == 0) _strayNoticeCount = 0;
|
||||
}
|
||||
catch (Exception ex) { _host.Log($"[RynthAi] Stray nav check failed: {ex.Message}"); }
|
||||
}
|
||||
|
||||
/// <summary>Posts the stray-navs line waiting for chat (plugin tick, in game).</summary>
|
||||
public void DrainStrayNavNotice(Func<string, bool> write)
|
||||
{
|
||||
if (string.IsNullOrEmpty(_strayChatPending)) return;
|
||||
if (write("[RynthAi] " + _strayChatPending)) _strayChatPending = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// /ra nav import and the Nav panel's button: copies the VirindiTank navs found outside
|
||||
/// NavProfiles into it (never over a nav of that name; the originals stay). Returns the line
|
||||
/// to show; <paramref name="ok"/> false when nothing could be copied.
|
||||
/// </summary>
|
||||
public string CopyStrayNavs(out bool ok)
|
||||
{
|
||||
RefreshStrayNavs(NavFileList.Stamp(_navFolder), force: true);
|
||||
List<StrayNav> strays = _strayNavs ?? new List<StrayNav>();
|
||||
StrayCopyResult r = StrayNavs.CopyInto(strays, _navFolder, (from, to) =>
|
||||
RynthCore.Plugin.Shared.DataWriteGuard.TrySave("the nav", to, () => File.Copy(from, to, overwrite: false), out string why, callerShows: true)
|
||||
? null : why);
|
||||
ok = r.Failed == 0;
|
||||
RefreshNavFiles();
|
||||
RefreshStrayNavs(NavFileList.Stamp(_navFolder), force: true);
|
||||
_strayChatPending = string.Empty;
|
||||
return StrayNavs.CopyReply(r, _navFolder);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lists a folder again when it changed since the last look (a file added, removed or renamed:
|
||||
/// a route saved by RynthNav's "save as nav route", a loot profile or meta copied in, a settings
|
||||
|
|
@ -2819,7 +2906,9 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
long now = Environment.TickCount64;
|
||||
if (now < _nextNavFolderCheckMs) return;
|
||||
_nextNavFolderCheckMs = now + 3000;
|
||||
if (FolderChanged(_navFolder, ref _navFolderStamp)) RefreshNavFiles();
|
||||
DateTime navStamp = NavFileList.Stamp(_navFolder); // NavProfiles and its subfolders
|
||||
if (StampChanged(navStamp, ref _navFolderStamp)) RefreshNavFiles();
|
||||
RefreshStrayNavs(navStamp);
|
||||
if (FolderChanged(_lootFolder, ref _lootFolderStamp)) RefreshLootFiles();
|
||||
if (FolderChanged(_metaFolder, ref _metaFolderStamp)) RefreshMetaFiles();
|
||||
if (FolderChanged(_charFolder, ref _profileFolderStamp)) RefreshProfilesList();
|
||||
|
|
@ -2832,14 +2921,20 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
try
|
||||
{
|
||||
DateTime now = !string.IsNullOrEmpty(folder) && Directory.Exists(folder) ? Directory.GetLastWriteTimeUtc(folder) : DateTime.MinValue;
|
||||
if (now == stamp) return false;
|
||||
bool first = stamp == default;
|
||||
stamp = now;
|
||||
return !first;
|
||||
return StampChanged(now, ref stamp);
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
/// <summary>FolderChanged for a time worked out by the caller (NavFileList.Stamp).</summary>
|
||||
private static bool StampChanged(DateTime now, ref DateTime stamp)
|
||||
{
|
||||
if (now == stamp) return false;
|
||||
bool first = stamp == default;
|
||||
stamp = now;
|
||||
return !first;
|
||||
}
|
||||
|
||||
/// <summary>Save button and /ra nav save [name]. Returns the chat line.</summary>
|
||||
public string SaveRoute(string? name)
|
||||
{
|
||||
|
|
@ -2859,6 +2954,32 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
/// </summary>
|
||||
public string LoadNavByName(string name)
|
||||
{
|
||||
// A nav in a subfolder ("VirindiTank\Hunt", or just "Hunt" when only one subfolder has it):
|
||||
// loaded from the list. A name at the top, or no such nav, goes on as before (a new one is made).
|
||||
string typed = NewProfileFiles.Tidy(name, NewProfileFiles.NavExtensions, out _);
|
||||
if (!File.Exists(Path.Combine(_navFolder, typed.Replace('/', '\\') + ".nav")) || typed.Contains('\\') || typed.Contains('/'))
|
||||
{
|
||||
RefreshNavFiles();
|
||||
string? listed;
|
||||
int matches;
|
||||
List<string> same;
|
||||
lock (_profileListsLock)
|
||||
{
|
||||
listed = NavFileList.Find(_navFiles, typed, out matches);
|
||||
same = matches > 1 ? NavFileList.SameName(_navFiles, typed) : new List<string>();
|
||||
}
|
||||
if (listed != null && !listed.Equals("None", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
lock (_profileListsLock) _selectedNavIdx = _navFiles.IndexOf(listed);
|
||||
LoadSelectedNav();
|
||||
SaveSettings();
|
||||
return $"[RynthAi] Loaded {listed} ({_settings.CurrentRoute.Points.Count} waypoints).";
|
||||
}
|
||||
if (matches > 1)
|
||||
return $"[RynthAi] {matches} navs are named '{typed}': {string.Join(", ", same)}. /ra nav load <folder>\\<name> picks one.";
|
||||
// Not listed: on as before (a name with a folder in it is refused there; nothing is made in a subfolder).
|
||||
}
|
||||
|
||||
ProfileFileResult r = NewProfileFiles.FindOrCreateNav(_navFolder, name, out string want, out _, out string error);
|
||||
if (r == ProfileFileResult.Rejected)
|
||||
return $"[RynthAi] Can't use '{want}' as a nav name: {error}.";
|
||||
|
|
@ -2952,26 +3073,36 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
|
||||
private void RefreshLootFiles()
|
||||
{
|
||||
var list = new System.Collections.Generic.List<string> { "None" };
|
||||
int idx = _settings.LootProfileIdx;
|
||||
if (Directory.Exists(_lootFolder))
|
||||
{
|
||||
var files = new System.Collections.Generic.List<string>();
|
||||
files.AddRange(Directory.GetFiles(_lootFolder, "*.utl"));
|
||||
files.AddRange(Directory.GetFiles(_lootFolder, "*.json"));
|
||||
files.Sort(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
foreach (string file in files)
|
||||
{
|
||||
list.Add(Path.GetFileName(file));
|
||||
if (file.Equals(_settings.CurrentLootPath, StringComparison.OrdinalIgnoreCase))
|
||||
idx = list.Count - 1;
|
||||
}
|
||||
}
|
||||
// One list for every loot profile picker (Loot.LootProfileList).
|
||||
List<string> list = Loot.LootProfileList.Build(_lootFolder);
|
||||
int idx = Loot.LootProfileList.SelectedIndex(list, _lootFolder, _settings.CurrentLootPath, _settings.LootProfileIdx);
|
||||
lock (_profileListsLock) { _lootFiles.Clear(); _lootFiles.AddRange(list); }
|
||||
_settings.LootProfileIdx = idx;
|
||||
}
|
||||
|
||||
/// <summary>The loot profile pickers' list ("None", then LootProfiles' *.utl and *.json), a copy. Any thread.</summary>
|
||||
public string[] LootProfileNames()
|
||||
{
|
||||
lock (_profileListsLock) return _lootFiles.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Mini Remote's Loot row: picks <paramref name="fileName"/> from the list by name (the list can
|
||||
/// change between the click and this call) through the pickers' one path, SelectProfileAtIndex.
|
||||
/// Pump thread.
|
||||
/// </summary>
|
||||
public void SelectLootProfileByName(string fileName)
|
||||
{
|
||||
int idx;
|
||||
lock (_profileListsLock) idx = Loot.LootProfileList.IndexOf(_lootFiles, fileName);
|
||||
if (idx < 0)
|
||||
{
|
||||
_host.WriteToChat($"[RynthAi] Loot profile {fileName} is no longer in LootProfiles.", 4);
|
||||
return;
|
||||
}
|
||||
SelectProfileAtIndex(1, idx);
|
||||
}
|
||||
|
||||
private void RefreshMetaFiles()
|
||||
{
|
||||
var list = new List<string> { "None" };
|
||||
|
|
@ -3118,7 +3249,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
? "None (Unsaved)"
|
||||
: _settings.CurrentNavPath.StartsWith("<embedded:", StringComparison.Ordinal)
|
||||
? _settings.CurrentNavPath.Substring(10).TrimEnd('>') + " (in meta)"
|
||||
: Path.GetFileNameWithoutExtension(_settings.CurrentNavPath),
|
||||
: NavListName(_settings.CurrentNavPath),
|
||||
NavStatusLine = _settings.NavStatusLine ?? string.Empty,
|
||||
NavIsStuck = _settings.NavIsStuck,
|
||||
MacroRunning = _settings.IsMacroRunning,
|
||||
|
|
@ -3134,12 +3265,31 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
TrailPoints = NavBreadcrumbs?.Trail.Length ?? 0,
|
||||
TrailYards = NavBreadcrumbs?.TrailYards ?? 0,
|
||||
EditStatus = CurrentNavEditStatus(),
|
||||
StrayNavCount = _strayNavs?.Count ?? 0,
|
||||
StrayNavText = _strayNavText ?? string.Empty,
|
||||
};
|
||||
return JsonSerializer.Serialize(payload, RynthAiJsonContext.Default.NavBridgePayload);
|
||||
}
|
||||
catch { return "{}"; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The nav list's name for a nav file: "Folder\Name" for one in a NavProfiles subfolder (so the
|
||||
/// Nav panel's picker shows it as the one loaded), else the file name without ".nav".
|
||||
/// </summary>
|
||||
private string NavListName(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
string rel = Path.GetRelativePath(_navFolder, path);
|
||||
if (!rel.StartsWith("..", StringComparison.Ordinal) && !Path.IsPathRooted(rel)
|
||||
&& rel.EndsWith(".nav", StringComparison.OrdinalIgnoreCase) && rel.Contains('\\'))
|
||||
return rel[..^4];
|
||||
}
|
||||
catch { }
|
||||
return Path.GetFileNameWithoutExtension(path);
|
||||
}
|
||||
|
||||
public void HandleNavCommand(string json)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json)) return;
|
||||
|
|
@ -3152,7 +3302,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
{
|
||||
case "startNav":
|
||||
_settings.RearmFinishedNavRoute(); // the player's Start Navigation re-runs a finished Once route
|
||||
_settings.IsMacroRunning = true;
|
||||
_settings.SetMacroRunning(true, "the remote's Start Navigation");
|
||||
_settings.EnableNavigation = true;
|
||||
if (_settings.BotAction != "Navigating")
|
||||
_settings.BotAction = "Default";
|
||||
|
|
@ -3253,6 +3403,13 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
if (ni >= 0) { _selectedNavIdx = ni; LoadSelectedNav(); SaveSettings(); }
|
||||
break;
|
||||
|
||||
case "copyStrayNavs":
|
||||
// Nav panel: "Copy them into NavProfiles" under the stray-navs line.
|
||||
string copied = CopyStrayNavs(out bool copyOk);
|
||||
SetNavEditStatus(copied);
|
||||
_host.WriteToChat("[RynthAi] " + copied, copyOk ? CommandReply.OkColor : CommandReply.FailColor);
|
||||
break;
|
||||
|
||||
default:
|
||||
// Route editor commands (multi-select edits, pause / portal steps, trail -> route).
|
||||
HandleNavEditCommand(cmd);
|
||||
|
|
@ -3480,7 +3637,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
return sb.ToString();
|
||||
}
|
||||
|
||||
public void TogglePanelMacro() => _settings.IsMacroRunning = !_settings.IsMacroRunning;
|
||||
public void TogglePanelMacro(string source = "the panel's macro toggle") => _settings.SetMacroRunning(!_settings.IsMacroRunning, source);
|
||||
|
||||
public void SetSubsystemEnabled(int id, bool enabled)
|
||||
{
|
||||
|
|
@ -3533,9 +3690,14 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
case 1:
|
||||
if (lootFile != null)
|
||||
{
|
||||
string before = _settings.CurrentLootPath ?? string.Empty;
|
||||
_settings.LootProfileIdx = index;
|
||||
_settings.CurrentLootPath = index == 0 ? string.Empty : Path.Combine(_lootFolder, lootFile);
|
||||
SaveSettings();
|
||||
// Every picker (Loaded files, Classic Loot tab, Settings > Looting, the Mini Remote) says
|
||||
// what it switched to; the profile itself loads when looting next reads it.
|
||||
if (!string.Equals(before, _settings.CurrentLootPath, StringComparison.OrdinalIgnoreCase))
|
||||
_host.WriteToChat(Loot.LootProfileList.SwitchedLine(_settings.CurrentLootPath), 1);
|
||||
}
|
||||
break;
|
||||
case 2:
|
||||
|
|
|
|||
|
|
@ -76,7 +76,7 @@ internal sealed class LegacyNavigationUi
|
|||
if (ImGui.Button("Start Navigation", new Vector2(-1, 28)))
|
||||
{
|
||||
_settings.RearmFinishedNavRoute(); // a finished Once route runs again
|
||||
_settings.IsMacroRunning = true;
|
||||
_settings.SetMacroRunning(true, "the Start Navigation button");
|
||||
_settings.EnableNavigation = true;
|
||||
if (_settings.BotAction != "Navigating")
|
||||
_settings.BotAction = "Default";
|
||||
|
|
|
|||
|
|
@ -18,7 +18,69 @@ public static class DashWindows
|
|||
public sealed class LegacyUiSettings
|
||||
{
|
||||
// ── Runtime-only state — never persisted ────────────────────────────────
|
||||
[JsonIgnore] public bool IsMacroRunning;
|
||||
// The macro switch. Every change records who made it (MacroStopSource / MacroStartSource), for the
|
||||
// "Macro stopped" / "Macro started" log lines: a stop with no cause logged could not be told apart
|
||||
// (the player's button, a script, a meta, the HP failsafe) (2026-11-22). A caller names itself with
|
||||
// SetMacroRunning, or wraps its calls in MacroSource(...) (a meta's rule, a script's call); a plain
|
||||
// write says so.
|
||||
private bool _isMacroRunning;
|
||||
private readonly List<string> _macroSources = new();
|
||||
[JsonIgnore] public bool IsMacroRunning
|
||||
{
|
||||
get => _isMacroRunning;
|
||||
set => SetMacroRunning(value, null);
|
||||
}
|
||||
/// <summary>Who turned the macro off last ("" before the first stop).</summary>
|
||||
[JsonIgnore] public string MacroStopSource { get; private set; } = "";
|
||||
/// <summary>Who turned the macro on last ("" before the first start).</summary>
|
||||
[JsonIgnore] public string MacroStartSource { get; private set; } = "";
|
||||
|
||||
/// <summary>Turns the macro on or off, saying who did (null: only the enclosing MacroSource scopes).</summary>
|
||||
public void SetMacroRunning(bool on, string? source)
|
||||
{
|
||||
if (_isMacroRunning != on)
|
||||
{
|
||||
string who = DescribeMacroSource(source);
|
||||
if (on) MacroStartSource = who; else MacroStopSource = who;
|
||||
}
|
||||
_isMacroRunning = on;
|
||||
}
|
||||
|
||||
/// <summary>Names the caller of every macro change inside the scope (nested scopes add to it).</summary>
|
||||
public IDisposable MacroSource(string source)
|
||||
{
|
||||
lock (_macroSources) _macroSources.Add(source);
|
||||
return new MacroSourceScope(this, source);
|
||||
}
|
||||
|
||||
private string DescribeMacroSource(string? source)
|
||||
{
|
||||
var parts = new List<string>();
|
||||
if (!string.IsNullOrEmpty(source)) parts.Add(source);
|
||||
lock (_macroSources)
|
||||
for (int i = _macroSources.Count - 1; i >= 0; i--)
|
||||
if (!parts.Exists(p => p.Contains(_macroSources[i], StringComparison.Ordinal))) parts.Add(_macroSources[i]);
|
||||
if (parts.Count == 0) return "a plain write (no source named)";
|
||||
return parts.Count == 1 ? parts[0] : parts[0] + " (from " + string.Join(", from ", parts.GetRange(1, parts.Count - 1)) + ")";
|
||||
}
|
||||
|
||||
private sealed class MacroSourceScope : IDisposable
|
||||
{
|
||||
private LegacyUiSettings? _s;
|
||||
private readonly string _source;
|
||||
public MacroSourceScope(LegacyUiSettings s, string source) { _s = s; _source = source; }
|
||||
public void Dispose()
|
||||
{
|
||||
var s = _s;
|
||||
if (s == null) return;
|
||||
_s = null;
|
||||
lock (s._macroSources)
|
||||
{
|
||||
int i = s._macroSources.LastIndexOf(_source);
|
||||
if (i >= 0) s._macroSources.RemoveAt(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// RynthSort's auto-sort is on (read from RynthSort every couple of seconds): Auto Cram stands down and
|
||||
/// its checkboxes are greyed out, as the two fought over the packs (owner, 2026-11-03). Never saved.
|
||||
|
|
@ -134,6 +196,12 @@ public sealed class LegacyUiSettings
|
|||
// own dialog as usual, never a No (engine API v97; MiniRemote/Crafting/CraftAutoConfirm.cs).
|
||||
public bool AutoConfirmCraft = false;
|
||||
public int AutoConfirmCraftPercent = 100;
|
||||
// Make kits when low (2026-11-22; default off): with the macro on and nothing around, when fewer
|
||||
// than MakeKitsBelow Plentiful Healing Kits are carried, make up to MakeKitsUpTo from the pack's
|
||||
// ingredients at the Kits tab's Min chance % (MiniRemote/Crafting/KitAuto.cs, RynthAiPlugin.Kits.cs).
|
||||
public bool MakeKitsWhenLow = false;
|
||||
public int MakeKitsBelow = MiniRemote.Crafting.KitAuto.DefaultBelow;
|
||||
public int MakeKitsUpTo = MiniRemote.Crafting.KitAuto.DefaultUpTo;
|
||||
public bool EnableCombineSalvage = true;
|
||||
public bool CombineBagsDuringSalvage = true;
|
||||
// Salvage (and combine bags) by sending the 0x027D salvage request straight to the server, no
|
||||
|
|
@ -326,7 +394,8 @@ public sealed class LegacyUiSettings
|
|||
public int TargetSelection;
|
||||
// Target Lock: keep the picked target until it dies or goes, leaves Monster Range, or is
|
||||
// blacklisted or skipped by a watchdog; a higher-priority monster in range doesn't take it
|
||||
// (2026-11-07). Off: a higher priority in range takes over at once, and it switches when
|
||||
// (2026-11-07). With Targeting on Closest, a monster within 5 yd takes it from a target more
|
||||
// than 6.5 m off (2026-11-22). Off: a higher priority in range takes over at once, and it switches when
|
||||
// another is clearly better by Targeting. On by default; a profile saved before this setting
|
||||
// loads it as on.
|
||||
public bool TargetLock = true;
|
||||
|
|
@ -355,6 +424,14 @@ public sealed class LegacyUiSettings
|
|||
"in through a door.\n" +
|
||||
"Off: a monster behind a wall is never a melee target for being close; it is treated like any monster\n" +
|
||||
"out of sight. On by default. /ra meleewalls [on|off]";
|
||||
// Debuff every monster in range before attacking (2026-11-22, off by default, the meta option
|
||||
// debuffallbeforeattacking, /ra debuffall): with several monsters in Monster Range, each one's own
|
||||
// debuffs (its Monsters rule) go on all of them, nearest first, before any attack, and the pet
|
||||
// summon waits for it. Capped per monster and in time; a monster hitting you in melee is fought
|
||||
// first. CombatManager.DebuffPass.cs. A profile saved before this setting loads it as off.
|
||||
public bool DebuffAllBeforeAttacking;
|
||||
internal const string DebuffAllBeforeAttackingTip =
|
||||
"Casts each monster's Monsters-rule debuffs on every monster in range, nearest first, before attacking any (/ra debuffall).";
|
||||
public int RingRange = 5;
|
||||
// Obsolete since 2026-10-20 (unused here, kept so profiles still load and carry it): the Empyrean
|
||||
// Handler lethal-ring evade is Infinite Leaftide's and lives in RynthILT now (its ILT settings,
|
||||
|
|
@ -399,6 +476,10 @@ public sealed class LegacyUiSettings
|
|||
public int CustomPetRange = 5;
|
||||
public int PetMinMonsters = 1;
|
||||
public bool PetAutoRefill = true; // auto-consume Encapsulated Spirits to recharge empty essences
|
||||
// The element combat pets are summoned for (2026-11-22): "" = Any (the per-monster choice: the
|
||||
// Damage-panel pick, the Monsters rule, then the monster's weakness), else Fire, Cold, ... An
|
||||
// essence of it is summoned first unless the monster has a choice of its own (PetChoice.Order).
|
||||
public string PetElement = string.Empty;
|
||||
public bool AdvancedOptions;
|
||||
public bool MineOnly = true;
|
||||
public bool ShowEditor;
|
||||
|
|
@ -439,8 +520,8 @@ public sealed class LegacyUiSettings
|
|||
/// on the way as usual, recover the corpse, then carry on. Off by default.
|
||||
/// </summary>
|
||||
public bool TravelToOwnCorpse;
|
||||
/// <summary>Not read by the corpse looting (no rare-corpse check exists); kept so saved profiles
|
||||
/// round-trip. Hidden in Advanced Settings. The meta/MagTools option of that name sets Mine Only.</summary>
|
||||
/// <summary>Loot Only Rare Corpses (2026-11-22, VTank's option): only a corpse whose description says it
|
||||
/// generated a rare is opened (RynthAiPlugin.RareCorpses.cs). Off by default.</summary>
|
||||
public bool LootOnlyRareCorpses;
|
||||
/// <summary>
|
||||
/// Loot Mode (Loot.LootModes): 0 = Profile (the loot profile, the default), 1 = Rares and needed
|
||||
|
|
@ -1293,6 +1374,11 @@ public sealed class NavBridgePayload
|
|||
public double TrailYards { get; set; }
|
||||
/// <summary>Result of the last route edit ("Route reversed."), empty once it is a few seconds old.</summary>
|
||||
public string EditStatus { get; set; } = string.Empty;
|
||||
/// <summary>VirindiTank navs outside NavProfiles (StrayNavs): how many, and the line saying where
|
||||
/// they are. The Nav panel shows it with a "Copy them into NavProfiles" button (copyStrayNavs).
|
||||
/// 0 / empty when there are none; an engine that predates them ignores both.</summary>
|
||||
public int StrayNavCount { get; set; }
|
||||
public string StrayNavText { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>One-shot command sent from the Avalonia NavPanel to the plugin.</summary>
|
||||
|
|
@ -1482,6 +1568,7 @@ public sealed class SettingsBridgePayload
|
|||
public bool? TargetLock { get; set; }
|
||||
public bool? FightSelectedTarget { get; set; }
|
||||
public bool? MeleeThroughWalls { get; set; } // Melee through walls; absent (an engine without the row) = unchanged
|
||||
public bool? DebuffAllBeforeAttacking { get; set; } // Debuff every monster in range before attacking; absent = unchanged
|
||||
public int RingRange { get; set; }
|
||||
public int ApproachRange { get; set; }
|
||||
public double CorpseApproachRangeMax { get; set; }
|
||||
|
|
|
|||
|
|
@ -93,7 +93,8 @@ internal sealed class LegacyWeaponsUi
|
|||
_host.WriteToChat($"[RynthAi] {wo.Name} is already in the list.", 1);
|
||||
else
|
||||
{
|
||||
string type = DetectConsumableType(wo);
|
||||
// A server's holder of summons ("Duo Summon Gem": no "Essence" in its name) is a Pet.
|
||||
string type = PetElements.IsHolder(_host, unchecked((uint)wo.Id), wo.Name) ? "Pet" : DetectConsumableType(wo);
|
||||
_settings.ConsumableRules.Add(new ConsumableRule
|
||||
{
|
||||
Id = wo.Id,
|
||||
|
|
@ -128,6 +129,8 @@ internal sealed class LegacyWeaponsUi
|
|||
continue;
|
||||
}
|
||||
string? type = PackConsumableType(wo);
|
||||
// A server's holder of summons (PetElements: "Duo Summon Gem", no "Essence" in its name).
|
||||
if (type == null && PetElements.IsHolder(_host, unchecked((uint)wo.Id), wo.Name)) type = "Pet";
|
||||
if (type == null || _settings.ConsumableRules.Any(x => x.Id == wo.Id)) continue;
|
||||
// An "...Essence" that is no combat pet device (appraised: no charges, no Summoning
|
||||
// requirement, no summoning-gem icon; PetDeviceKind) is not listed as a combat pet: a
|
||||
|
|
|
|||
168
Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavFileList.cs
Normal file
168
Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavFileList.cs
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
|
||||
/// <summary>
|
||||
/// What the nav picker lists from NavProfiles (2026-11-22). It listed the top of the folder only,
|
||||
/// so VirindiTank navs dropped in as a folder (NavProfiles\VirindiTank\*.nav, a folder per server
|
||||
/// or per character) never showed. Now:
|
||||
/// - the top of the folder first, as before ("Hunt");
|
||||
/// - then the navs in its subfolders, as "Folder\Hunt" (up to <see cref="MaxDepth"/> deep),
|
||||
/// sorted. Not the Deleted folder (the profile buttons move files there), not hidden or
|
||||
/// dot folders, and not VirindiTank's "--<character>_<server>" state files, which a
|
||||
/// copied VirindiTank folder has hundreds of (nearly all empty).
|
||||
/// The names are paths relative to NavProfiles without ".nav", so Path.Combine(folder, name + ".nav")
|
||||
/// is the file for every entry. System only (the tests compile it in).
|
||||
/// </summary>
|
||||
internal static class NavFileList
|
||||
{
|
||||
/// <summary>How deep subfolders are looked into (NavProfiles\a\b\c\x.nav is the deepest).</summary>
|
||||
public const int MaxDepth = 3;
|
||||
|
||||
/// <summary>Most entries listed (a whole Decal folder copied in can't flood the picker).</summary>
|
||||
public const int MaxEntries = 2000;
|
||||
|
||||
/// <summary>The subfolder the profile buttons' Delete moves files into (ProfileFileOps.DeletedFolderName).</summary>
|
||||
public const string DeletedFolder = "Deleted";
|
||||
|
||||
/// <summary>The navs in <paramref name="folder"/> (see the class summary); empty when it doesn't exist.</summary>
|
||||
public static List<string> List(string folder)
|
||||
{
|
||||
var top = new List<string>();
|
||||
var sub = new List<string>();
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) return top;
|
||||
foreach (string file in Directory.GetFiles(folder, "*.nav"))
|
||||
if (IsNavFile(file)) top.Add(Path.GetFileNameWithoutExtension(file));
|
||||
top.Sort(StringComparer.OrdinalIgnoreCase);
|
||||
AddSubfolders(folder, folder, 1, sub);
|
||||
sub.Sort(StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
catch { /* an unreadable folder lists what was read */ }
|
||||
top.AddRange(sub);
|
||||
if (top.Count > MaxEntries) top.RemoveRange(MaxEntries, top.Count - MaxEntries);
|
||||
return top;
|
||||
}
|
||||
|
||||
private static void AddSubfolders(string root, string dir, int depth, List<string> into)
|
||||
{
|
||||
if (depth > MaxDepth || into.Count >= MaxEntries) return;
|
||||
string[] dirs;
|
||||
try { dirs = Directory.GetDirectories(dir); } catch { return; }
|
||||
foreach (string d in dirs)
|
||||
{
|
||||
if (!ListsFolder(d)) continue;
|
||||
try
|
||||
{
|
||||
foreach (string file in Directory.GetFiles(d, "*.nav"))
|
||||
{
|
||||
if (!IsNavFile(file) || IsVTankStateFile(file)) continue;
|
||||
into.Add(Path.GetRelativePath(root, file)[..^4]);
|
||||
if (into.Count >= MaxEntries) return;
|
||||
}
|
||||
}
|
||||
catch { continue; }
|
||||
AddSubfolders(root, d, depth + 1, into);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A subfolder whose navs are listed: not Deleted, not hidden or a dot folder.</summary>
|
||||
internal static bool ListsFolder(string dir)
|
||||
{
|
||||
string name = Path.GetFileName(dir);
|
||||
if (name.Length == 0 || name[0] == '.') return false;
|
||||
if (name.Equals(DeletedFolder, StringComparison.OrdinalIgnoreCase)) return false;
|
||||
try
|
||||
{
|
||||
var attrs = File.GetAttributes(dir);
|
||||
if ((attrs & (FileAttributes.Hidden | FileAttributes.System)) != 0) return false;
|
||||
if ((attrs & FileAttributes.ReparsePoint) != 0) return false; // never follow a junction
|
||||
}
|
||||
catch { return false; }
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>A ".nav" file (the pattern alone would also take "x.nav~" on some systems).</summary>
|
||||
private static bool IsNavFile(string file) => file.EndsWith(".nav", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>VirindiTank's own "--<character>_<server>.nav" (the route a character last had).</summary>
|
||||
internal static bool IsVTankStateFile(string file) => Path.GetFileName(file).StartsWith("--", StringComparison.Ordinal);
|
||||
|
||||
/// <summary>
|
||||
/// When <paramref name="folder"/> or a listed subfolder last changed: the latest write time of
|
||||
/// them. Adding a file to a subfolder changes only that subfolder's time, so the folder's own
|
||||
/// time alone missed it. MinValue when the folder doesn't exist.
|
||||
/// </summary>
|
||||
public static DateTime Stamp(string folder)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) return DateTime.MinValue;
|
||||
DateTime latest = Directory.GetLastWriteTimeUtc(folder);
|
||||
StampSubfolders(folder, 1, ref latest);
|
||||
return latest;
|
||||
}
|
||||
catch { return DateTime.MinValue; }
|
||||
}
|
||||
|
||||
private static void StampSubfolders(string dir, int depth, ref DateTime latest)
|
||||
{
|
||||
if (depth > MaxDepth) return;
|
||||
string[] dirs;
|
||||
try { dirs = Directory.GetDirectories(dir); } catch { return; }
|
||||
foreach (string d in dirs)
|
||||
{
|
||||
if (!ListsFolder(d)) continue;
|
||||
try
|
||||
{
|
||||
DateTime t = Directory.GetLastWriteTimeUtc(d);
|
||||
if (t > latest) latest = t;
|
||||
}
|
||||
catch { continue; }
|
||||
StampSubfolders(d, depth + 1, ref latest);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The entry of <paramref name="names"/> that /ra nav load <<paramref name="typed"/>> means
|
||||
/// (typed already tidied: no quotes, no ".nav"): the entry itself, any case, with \ or /; else,
|
||||
/// for a name without a folder, the only subfolder entry with that file name. Null when there
|
||||
/// is none; <paramref name="matches"/> is how many subfolder entries had the name (2+: the
|
||||
/// player has to say which).
|
||||
/// </summary>
|
||||
public static string? Find(IReadOnlyList<string> names, string typed, out int matches)
|
||||
{
|
||||
matches = 0;
|
||||
string want = (typed ?? string.Empty).Trim().Replace('/', '\\').Trim('\\');
|
||||
if (want.Length == 0) return null;
|
||||
foreach (string n in names)
|
||||
if (n.Equals(want, StringComparison.OrdinalIgnoreCase)) { matches = 1; return n; }
|
||||
if (want.Contains('\\')) return null;
|
||||
|
||||
string? found = null;
|
||||
foreach (string n in names)
|
||||
{
|
||||
int slash = n.LastIndexOf('\\');
|
||||
if (slash < 0) continue;
|
||||
if (!n.AsSpan(slash + 1).Equals(want, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
matches++;
|
||||
found ??= n;
|
||||
}
|
||||
return matches == 1 ? found : null;
|
||||
}
|
||||
|
||||
/// <summary>The subfolder entries named <paramref name="name"/> (for the "which one?" reply).</summary>
|
||||
public static List<string> SameName(IReadOnlyList<string> names, string name)
|
||||
{
|
||||
var list = new List<string>();
|
||||
foreach (string n in names)
|
||||
{
|
||||
int slash = n.LastIndexOf('\\');
|
||||
if (slash >= 0 && n.AsSpan(slash + 1).Equals(name, StringComparison.OrdinalIgnoreCase)) list.Add(n);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
|
@ -116,6 +116,13 @@ public sealed class NavRouteParser
|
|||
/// </summary>
|
||||
public bool OutdoorHuntWalk { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The corners of a RynthNav navmesh path laid on the fly (a script's ai.GoTo outdoors, 2026-11-18):
|
||||
/// like a hunt walk, a corner is turned early only where the navmesh shows a straight walk to the next
|
||||
/// one (NavigationEngine's corner gate). Never set on a loaded route.
|
||||
/// </summary>
|
||||
public bool NavmeshCorners { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Non-null if the last load hit an unknown waypoint type or a malformed
|
||||
/// line. The route still holds whatever points parsed cleanly before that.
|
||||
|
|
@ -227,9 +234,9 @@ public sealed class NavRouteParser
|
|||
var pt = new NavPoint
|
||||
{
|
||||
Type = (NavPointType)typeRaw,
|
||||
EW = double.Parse(lines[idx++], CultureInfo.InvariantCulture),
|
||||
NS = double.Parse(lines[idx++], CultureInfo.InvariantCulture),
|
||||
Z = double.Parse(lines[idx++], CultureInfo.InvariantCulture)
|
||||
EW = ParseNumber(lines[idx++]),
|
||||
NS = ParseNumber(lines[idx++]),
|
||||
Z = ParseNumber(lines[idx++])
|
||||
};
|
||||
// Z is in nav units (metres / 240). Waypoints added from the UI before
|
||||
// 2026-09-29 stored metres, so they drew hundreds of metres up; no real
|
||||
|
|
@ -253,18 +260,18 @@ public sealed class NavRouteParser
|
|||
pt.TargetName = lines[idx++];
|
||||
break;
|
||||
case NavPointType.Jump:
|
||||
pt.JumpHeading = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
|
||||
pt.JumpHeading = ParseNumber(lines[idx++]);
|
||||
pt.JumpShift = lines[idx++].Trim().Equals("true", StringComparison.OrdinalIgnoreCase);
|
||||
pt.JumpMs = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
|
||||
pt.JumpMs = ParseNumber(lines[idx++]);
|
||||
break;
|
||||
case NavPointType.PortalNPC:
|
||||
case NavPointType.Npc:
|
||||
pt.TargetName = lines[idx++];
|
||||
pt.ObjectClass = int.Parse(lines[idx++], CultureInfo.InvariantCulture);
|
||||
pt.IsTie = ParseTieFlag(lines[idx++]);
|
||||
pt.PortalExitEW = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
|
||||
pt.PortalExitNS = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
|
||||
pt.PortalExitZ = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
|
||||
pt.PortalExitEW = ParseNumber(lines[idx++]);
|
||||
pt.PortalExitNS = ParseNumber(lines[idx++]);
|
||||
pt.PortalExitZ = ParseNumber(lines[idx++]);
|
||||
break;
|
||||
}
|
||||
|
||||
|
|
@ -283,6 +290,19 @@ public sealed class NavRouteParser
|
|||
return route;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A number line of a nav (coordinates, jump heading and power). Written by VirindiTank and
|
||||
/// RynthAi as "12.5"; a line with a comma and no dot ("12,5", a PC set to a comma-decimal
|
||||
/// language) is read as 12.5 (it used to read as 125: the comma was taken for a thousands
|
||||
/// separator, and the point drew far off its place). No thousands separators.
|
||||
/// </summary>
|
||||
internal static double ParseNumber(string s)
|
||||
{
|
||||
s = (s ?? string.Empty).Trim();
|
||||
if (s.IndexOf(',') >= 0 && s.IndexOf('.') < 0) s = s.Replace(',', '.');
|
||||
return double.Parse(s, NumberStyles.Float, CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
private static bool ParseTieFlag(string s)
|
||||
{
|
||||
if (bool.TryParse(s, out bool b)) return b; // "True"/"False" (VTank wire format)
|
||||
|
|
|
|||
205
Plugins/RynthCore.Plugin.RynthAi/LegacyUi/StrayNavs.cs
Normal file
205
Plugins/RynthCore.Plugin.RynthAi/LegacyUi/StrayNavs.cs
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
|
||||
/// <summary>A VirindiTank-format nav outside NavProfiles, where the nav picker can't see it.</summary>
|
||||
internal readonly record struct StrayNav(string Path, string Folder, string Name);
|
||||
|
||||
/// <summary>What copying the stray navs did.</summary>
|
||||
internal readonly record struct StrayCopyResult(int Copied, int AlreadyThere, int Failed, string FirstError);
|
||||
|
||||
/// <summary>
|
||||
/// Navs put in the wrong folder (2026-11-22). Players moving VirindiTank navs over put them in
|
||||
/// "the nav folder", and the one called that is RynthNav's map data folder (C:\Games\RynthCore\
|
||||
/// NavData); others land in the RynthAi or RynthSuite folder itself. RynthAi lists NavProfiles
|
||||
/// (and its subfolders) only, so they never showed and nothing said why. Here: the folders worth a
|
||||
/// look, the VirindiTank navs at the top of each that NavProfiles has no file of that name for, a
|
||||
/// line that says where they are and where they go, and the copy into NavProfiles (never moved,
|
||||
/// never over a file; the originals stay). System and System.Text.Json only (the tests compile it in).
|
||||
/// </summary>
|
||||
internal static class StrayNavs
|
||||
{
|
||||
/// <summary>RynthNav's own default for its map data folder (NavDataConfig.DefaultDir).</summary>
|
||||
public const string DefaultNavDataDir = @"C:\Games\RynthCore\NavData";
|
||||
|
||||
/// <summary>
|
||||
/// The folders to look in: RynthNav's map data folder (as RynthNav resolves it: the
|
||||
/// RYNTHNAV_NAVDATA variable, "navDataDir" in %APPDATA%\RynthCore\rynthnav.json, else
|
||||
/// <CoreDir>\NavData and the default), the RynthCore folder, the RynthSuite folder, RynthAi's
|
||||
/// own folder and RynthNav's plugin folder. Never NavProfiles. Duplicates dropped.
|
||||
/// </summary>
|
||||
public static List<string> CandidateFolders(string coreDir, string suiteDir, string rynthAiDir,
|
||||
string? navDataEnv, string? rynthNavSettingsPath)
|
||||
{
|
||||
var list = new List<string>();
|
||||
void Add(string? dir)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(dir) || !System.IO.Path.IsPathFullyQualified(dir)) return;
|
||||
string full;
|
||||
try { full = System.IO.Path.GetFullPath(dir).TrimEnd('\\', '/'); } catch { return; }
|
||||
foreach (string have in list) if (have.Equals(full, StringComparison.OrdinalIgnoreCase)) return;
|
||||
list.Add(full);
|
||||
}
|
||||
Add(navDataEnv);
|
||||
try
|
||||
{
|
||||
if (!string.IsNullOrEmpty(rynthNavSettingsPath) && File.Exists(rynthNavSettingsPath))
|
||||
Add(ReadNavDataDir(File.ReadAllText(rynthNavSettingsPath)));
|
||||
}
|
||||
catch { }
|
||||
if (!string.IsNullOrEmpty(coreDir)) Add(System.IO.Path.Combine(coreDir, "NavData"));
|
||||
Add(DefaultNavDataDir);
|
||||
Add(coreDir);
|
||||
Add(suiteDir);
|
||||
Add(rynthAiDir);
|
||||
if (!string.IsNullOrEmpty(suiteDir)) Add(System.IO.Path.Combine(suiteDir, "RynthNav"));
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>"navDataDir" from rynthnav.json's text (the same key RynthNav reads), or null.</summary>
|
||||
internal static string? ReadNavDataDir(string json)
|
||||
{
|
||||
try
|
||||
{
|
||||
using JsonDocument doc = JsonDocument.Parse(json, new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
|
||||
if (doc.RootElement.ValueKind != JsonValueKind.Object) return null;
|
||||
foreach (JsonProperty p in doc.RootElement.EnumerateObject())
|
||||
if (p.Name.Equals("navDataDir", StringComparison.OrdinalIgnoreCase) && p.Value.ValueKind == JsonValueKind.String)
|
||||
return p.Value.GetString();
|
||||
}
|
||||
catch (JsonException) { }
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The VirindiTank-format navs (first line "uTank2 NAV") at the top of each of
|
||||
/// <paramref name="folders"/> that <paramref name="navFolder"/> has no file of that name for.
|
||||
/// VirindiTank's "--" state files are left out. A folder inside NavProfiles is skipped (it's listed).
|
||||
/// </summary>
|
||||
public static List<StrayNav> Find(IEnumerable<string> folders, string navFolder)
|
||||
{
|
||||
var found = new List<StrayNav>();
|
||||
string navFull = Full(navFolder);
|
||||
foreach (string folder in folders)
|
||||
{
|
||||
string f = Full(folder);
|
||||
if (f.Length == 0 || IsSameOrInside(f, navFull)) continue;
|
||||
string[] files;
|
||||
try { if (!Directory.Exists(f)) continue; files = Directory.GetFiles(f, "*.nav"); }
|
||||
catch { continue; }
|
||||
Array.Sort(files, StringComparer.OrdinalIgnoreCase);
|
||||
foreach (string file in files)
|
||||
{
|
||||
if (!file.EndsWith(".nav", StringComparison.OrdinalIgnoreCase) || NavFileList.IsVTankStateFile(file)) continue;
|
||||
if (!IsVTankNav(file)) continue;
|
||||
string name = System.IO.Path.GetFileNameWithoutExtension(file);
|
||||
if (navFull.Length > 0 && File.Exists(System.IO.Path.Combine(navFull, name + ".nav"))) continue;
|
||||
found.Add(new StrayNav(file, f, name));
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/// <summary>True when the file's first line is a VirindiTank nav header.</summary>
|
||||
internal static bool IsVTankNav(string file)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var reader = new StreamReader(file);
|
||||
string? first = reader.ReadLine();
|
||||
return first != null && first.Contains("uTank2 NAV", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies <paramref name="strays"/> into the top of <paramref name="navFolder"/>, where the picker
|
||||
/// lists them. A name NavProfiles already has is left alone (counted, not copied); the
|
||||
/// originals stay where they were. <paramref name="copy"/> does the write (DataWriteGuard in
|
||||
/// the plugin, File.Copy in the tests).
|
||||
/// </summary>
|
||||
public static StrayCopyResult CopyInto(IReadOnlyList<StrayNav> strays, string navFolder, Func<string, string, string?>? copy = null)
|
||||
{
|
||||
copy ??= DefaultCopy;
|
||||
int copied = 0, there = 0, failed = 0;
|
||||
string firstError = string.Empty;
|
||||
var taken = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
try { Directory.CreateDirectory(navFolder); } catch { }
|
||||
foreach (StrayNav s in strays)
|
||||
{
|
||||
string target = System.IO.Path.Combine(navFolder, s.Name + ".nav");
|
||||
if (!taken.Add(s.Name) || File.Exists(target)) { there++; continue; }
|
||||
string? error = copy(s.Path, target);
|
||||
if (error == null) copied++;
|
||||
else
|
||||
{
|
||||
failed++;
|
||||
if (firstError.Length == 0) firstError = error;
|
||||
}
|
||||
}
|
||||
return new StrayCopyResult(copied, there, failed, firstError);
|
||||
}
|
||||
|
||||
private static string? DefaultCopy(string from, string to)
|
||||
{
|
||||
try { File.Copy(from, to, overwrite: false); return null; }
|
||||
catch (Exception ex) { return ex.Message; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The line that says where the stray navs are and where they go (chat and the Nav panel), or
|
||||
/// empty when there are none. Names the folder with the most of them; "and N more in other
|
||||
/// folders" for the rest.
|
||||
/// </summary>
|
||||
public static string Notice(IReadOnlyList<StrayNav> strays, string navFolder, string? navDataDir = null)
|
||||
{
|
||||
if (strays.Count == 0) return string.Empty;
|
||||
var byFolder = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (StrayNav s in strays) byFolder[s.Folder] = byFolder.TryGetValue(s.Folder, out int n) ? n + 1 : 1;
|
||||
string top = string.Empty; int topCount = 0;
|
||||
foreach (var kv in byFolder) if (kv.Value > topCount) { top = kv.Key; topCount = kv.Value; }
|
||||
bool isNavData = IsNavDataFolder(top, navDataDir);
|
||||
string what = strays.Count == 1 ? "1 VirindiTank nav is" : $"{strays.Count} VirindiTank navs are";
|
||||
string where = byFolder.Count == 1
|
||||
? $"in {top}"
|
||||
: $"in {top} ({topCount}) and {byFolder.Count - 1} other folder{(byFolder.Count == 2 ? "" : "s")}";
|
||||
string why = isNavData ? " (RynthNav's map data folder)" : string.Empty;
|
||||
return $"{what} {where}{why}, so the nav list doesn't show {(strays.Count == 1 ? "it" : "them")}. "
|
||||
+ $"RynthAi's navs go in {navFolder} (subfolders are fine).";
|
||||
}
|
||||
|
||||
/// <summary>The chat line after a copy (/ra nav import and the Nav panel's button).</summary>
|
||||
public static string CopyReply(StrayCopyResult r, string navFolder)
|
||||
{
|
||||
if (r.Copied == 0 && r.AlreadyThere == 0 && r.Failed == 0)
|
||||
return $"No VirindiTank navs outside NavProfiles to copy. The nav list shows {navFolder} and its subfolders.";
|
||||
var parts = new List<string>();
|
||||
if (r.Copied > 0) parts.Add($"Copied {r.Copied} nav{(r.Copied == 1 ? "" : "s")} into {navFolder}; {(r.Copied == 1 ? "it is" : "they are")} in the nav list now. The originals are still where they were");
|
||||
if (r.AlreadyThere > 0) parts.Add($"{r.AlreadyThere} left alone (NavProfiles has a nav of that name)");
|
||||
if (r.Failed > 0) parts.Add($"{r.Failed} couldn't be copied: {r.FirstError}");
|
||||
return string.Join("; ", parts) + ".";
|
||||
}
|
||||
|
||||
private static bool IsNavDataFolder(string folder, string? navDataDir)
|
||||
{
|
||||
string name = System.IO.Path.GetFileName(folder.TrimEnd('\\', '/'));
|
||||
if (name.Equals("NavData", StringComparison.OrdinalIgnoreCase)) return true;
|
||||
return !string.IsNullOrEmpty(navDataDir) && Full(navDataDir).Equals(Full(folder), StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static string Full(string? dir)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(dir)) return string.Empty;
|
||||
try { return System.IO.Path.GetFullPath(dir).TrimEnd('\\', '/'); } catch { return string.Empty; }
|
||||
}
|
||||
|
||||
private static bool IsSameOrInside(string dir, string parent)
|
||||
{
|
||||
if (parent.Length == 0) return false;
|
||||
return dir.Equals(parent, StringComparison.OrdinalIgnoreCase)
|
||||
|| dir.StartsWith(parent + "\\", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
|
|
@ -73,8 +73,9 @@ internal sealed class LootEditorBridge
|
|||
}
|
||||
}
|
||||
|
||||
// The session's revision plus the popup draft's: both only grow, so the sum moves when either does.
|
||||
private long StateRevision => _session.Revision + _draftRevision;
|
||||
// The session's revision plus the popup draft's plus the Keep # per day counts' (each only
|
||||
// grows), so the sum moves when any does.
|
||||
private long StateRevision => _session.Revision + _draftRevision + Items.PerDayRevision();
|
||||
|
||||
public string StateJson()
|
||||
{
|
||||
|
|
@ -85,6 +86,12 @@ internal sealed class LootEditorBridge
|
|||
LootEditState state = _session.BuildState(inUse, ListFiles());
|
||||
state.Revision = StateRevision;
|
||||
state.ItemDraft = _draft;
|
||||
for (int i = 0; i < state.Rules.Count; i++)
|
||||
{
|
||||
LootEditRow row = state.Rules[i];
|
||||
if (row.Action == (int)VTankLootAction.KeepUpTo && row.PerDayHours > 0)
|
||||
row.PerDayStatus = PerDayStatus(row.Name, i, row.PerDayHours, row.KeepCount);
|
||||
}
|
||||
return JsonSerializer.Serialize(state, LootEditJsonContext.Default.LootEditState);
|
||||
}
|
||||
}
|
||||
|
|
@ -94,10 +101,31 @@ internal sealed class LootEditorBridge
|
|||
lock (_sync)
|
||||
{
|
||||
LootEditRule? rule = _session.BuildRule(index);
|
||||
return rule == null ? "{\"Index\":-1}" : JsonSerializer.Serialize(rule, LootEditJsonContext.Default.LootEditRule);
|
||||
if (rule == null) return "{\"Index\":-1}";
|
||||
if (rule.Action == (int)VTankLootAction.KeepUpTo && rule.PerDayHours is int h && h > 0)
|
||||
rule.PerDayStatus = PerDayStatus(rule.Name, index, h, rule.KeepCount);
|
||||
return JsonSerializer.Serialize(rule, LootEditJsonContext.Default.LootEditRule);
|
||||
}
|
||||
}
|
||||
|
||||
private string PerDayStatus(string name, int index, int hours, int cap)
|
||||
{
|
||||
try { return Items.PerDayStatus(LootPerDay.Key(name, index), hours, cap); }
|
||||
catch { return string.Empty; }
|
||||
}
|
||||
|
||||
/// <summary>The rule view's "Reset count": forgets the pickups of the rule at cmd.Index. Under the lock.</summary>
|
||||
private void PerDayResetCommand(LootEditCommand cmd)
|
||||
{
|
||||
LootEditRule? rule = _session.BuildRule(cmd.Index);
|
||||
if (rule == null || (cmd.Expect != null && !string.Equals(cmd.Expect, rule.Name, StringComparison.Ordinal)))
|
||||
{
|
||||
_session.Say("That rule is no longer there. The list has been refreshed.", ok: false);
|
||||
return;
|
||||
}
|
||||
_session.Say(Items.PerDayReset(LootPerDay.Key(rule.Name, cmd.Index)), ok: true);
|
||||
}
|
||||
|
||||
public string VocabJson() =>
|
||||
_vocabJson ??= JsonSerializer.Serialize(LootRuleText.BuildVocab(), LootEditJsonContext.Default.LootEditVocab);
|
||||
|
||||
|
|
@ -113,6 +141,11 @@ internal sealed class LootEditorBridge
|
|||
string? saved = null;
|
||||
lock (_sync)
|
||||
{
|
||||
if (cmd.Op == "perday_reset")
|
||||
{
|
||||
PerDayResetCommand(cmd);
|
||||
return;
|
||||
}
|
||||
if (cmd.Op == "open")
|
||||
{
|
||||
string inUse = InUse;
|
||||
|
|
@ -396,6 +429,12 @@ internal sealed class LootItemHooks
|
|||
/// (the looter's own classification, run as a preview), or null.
|
||||
/// </summary>
|
||||
public Func<uint, LootBuiltInKeep?> BuiltInKeep { get; set; } = _ => null;
|
||||
/// <summary>Keep # per day: (rule key, window hours, count) to "1 of 2 picked up in the last 24 h, ...".</summary>
|
||||
public Func<string, int, int, string> PerDayStatus { get; set; } = (_, _, _) => string.Empty;
|
||||
/// <summary>Keep # per day: grows whenever a count changes (and each minute while any is on record).</summary>
|
||||
public Func<long> PerDayRevision { get; set; } = () => 0;
|
||||
/// <summary>Keep # per day: forget a rule's pickups; the reply.</summary>
|
||||
public Func<string, string> PerDayReset { get; set; } = _ => "Not available.";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
|
|||
247
Plugins/RynthCore.Plugin.RynthAi/Loot/LootPerDayStore.cs
Normal file
247
Plugins/RynthCore.Plugin.RynthAi/Loot/LootPerDayStore.cs
Normal file
|
|
@ -0,0 +1,247 @@
|
|||
// ============================================================================
|
||||
// RynthAi - Loot/LootPerDayStore.cs
|
||||
// "Keep # per day" (2026-11-22, RynthCore.Loot.LootPerDay): what this
|
||||
// character picked up for each such rule, with the time of each pickup, so a
|
||||
// rule takes at most N in any rolling window (24 h by default). Counted by
|
||||
// pickups, not by the pack: treasure maps and the like get used or sold.
|
||||
//
|
||||
// One file per character and server, beside the settings profiles:
|
||||
// SettingsProfiles\<server>\<character>\loot_per_day.json
|
||||
// {"version":1,"rules":{"Treasure Maps":[{"at":"2026-11-22T10:00:00Z","n":1}]}}
|
||||
// Times are UTC (no jump when the clocks change). Pickups older than a week
|
||||
// (the longest window) are dropped on load and on every pickup.
|
||||
//
|
||||
// Pure (no host): the host tests drive it with their own clock.
|
||||
// ============================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Loot;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Loot;
|
||||
|
||||
internal sealed class LootPerDayStore
|
||||
{
|
||||
public const string FileName = "loot_per_day.json";
|
||||
public const int FileVersion = 1;
|
||||
|
||||
private readonly Dictionary<string, List<Pick>> _rules = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
internal readonly record struct Pick(DateTime AtUtc, int Units);
|
||||
|
||||
/// <summary>The file (empty: kept in memory only, nothing saved).</summary>
|
||||
public string Path { get; private set; } = string.Empty;
|
||||
|
||||
/// <summary>Grows on every change (the Loot Editor's revision follows it).</summary>
|
||||
public long Revision { get; private set; }
|
||||
|
||||
/// <summary>The last load or save problem, or empty.</summary>
|
||||
public string Problem { get; private set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Reads <paramref name="path"/> (empty: memory only). A missing file is no pickups; a
|
||||
/// broken one is no pickups too, with <see cref="Problem"/> set (and kept until the next
|
||||
/// pickup overwrites it).
|
||||
/// </summary>
|
||||
public void Load(string path, DateTime nowUtc)
|
||||
{
|
||||
Path = path ?? string.Empty;
|
||||
_rules.Clear();
|
||||
Problem = string.Empty;
|
||||
Revision++;
|
||||
if (Path.Length == 0 || !File.Exists(Path)) return;
|
||||
try
|
||||
{
|
||||
Parse(File.ReadAllText(Path));
|
||||
Prune(nowUtc);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException or FormatException)
|
||||
{
|
||||
_rules.Clear();
|
||||
Problem = $"{Path}: {ex.Message}";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A pickup of <paramref name="units"/> (at least 1) for the rule <paramref name="key"/>, saved at once.</summary>
|
||||
public void Record(string key, int units, DateTime nowUtc)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(key)) return;
|
||||
if (!_rules.TryGetValue(key, out List<Pick>? list))
|
||||
_rules[key] = list = new List<Pick>();
|
||||
list.Add(new Pick(nowUtc, Math.Max(1, units)));
|
||||
Prune(nowUtc);
|
||||
Revision++;
|
||||
Save();
|
||||
}
|
||||
|
||||
/// <summary>Units picked up for <paramref name="key"/> in the last <paramref name="hours"/>.</summary>
|
||||
public int Count(string key, int hours, DateTime nowUtc)
|
||||
{
|
||||
if (!_rules.TryGetValue(key, out List<Pick>? list)) return 0;
|
||||
DateTime from = nowUtc - TimeSpan.FromHours(hours);
|
||||
int n = 0;
|
||||
foreach (Pick p in list)
|
||||
if (p.AtUtc > from) n += p.Units;
|
||||
return n;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// How long until the count is under <paramref name="cap"/> again (zero when it is now); under
|
||||
/// the cap, how long until the oldest pickup in the window frees its place (null: none in it).
|
||||
/// </summary>
|
||||
public TimeSpan? NextFree(string key, int hours, int cap, DateTime nowUtc)
|
||||
{
|
||||
if (!_rules.TryGetValue(key, out List<Pick>? list)) return null;
|
||||
TimeSpan window = TimeSpan.FromHours(hours);
|
||||
var inWindow = new List<Pick>();
|
||||
foreach (Pick p in list)
|
||||
if (p.AtUtc > nowUtc - window) inWindow.Add(p);
|
||||
if (inWindow.Count == 0) return null;
|
||||
inWindow.Sort((a, b) => a.AtUtc.CompareTo(b.AtUtc));
|
||||
int total = 0;
|
||||
foreach (Pick p in inWindow) total += p.Units;
|
||||
if (total < cap)
|
||||
return Max0(inWindow[0].AtUtc + window - nowUtc);
|
||||
// Drop the oldest until the rest is under the cap: that pickup's expiry is when.
|
||||
int left = total;
|
||||
foreach (Pick p in inWindow)
|
||||
{
|
||||
left -= p.Units;
|
||||
if (left < cap) return Max0(p.AtUtc + window - nowUtc);
|
||||
}
|
||||
return TimeSpan.Zero;
|
||||
}
|
||||
|
||||
private static TimeSpan Max0(TimeSpan t) => t < TimeSpan.Zero ? TimeSpan.Zero : t;
|
||||
|
||||
/// <summary>Forgets the pickups of <paramref name="key"/> (null: of every rule). True when there were any.</summary>
|
||||
public bool Clear(string? key)
|
||||
{
|
||||
bool had = key == null ? _rules.Count > 0 : _rules.Remove(key);
|
||||
if (key == null) _rules.Clear();
|
||||
if (!had) return false;
|
||||
Revision++;
|
||||
Save();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Every rule with pickups on record, with its pickups (oldest first).</summary>
|
||||
public IEnumerable<(string Key, IReadOnlyList<Pick> Picks)> Rules()
|
||||
{
|
||||
var keys = new List<string>(_rules.Keys);
|
||||
keys.Sort(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (string k in keys)
|
||||
{
|
||||
var list = new List<Pick>(_rules[k]);
|
||||
list.Sort((a, b) => a.AtUtc.CompareTo(b.AtUtc));
|
||||
yield return (k, list);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"1 of 2 picked up in the last 24 h, next frees in 5 h 10 min".</summary>
|
||||
public string Status(string key, int hours, int cap, DateTime nowUtc)
|
||||
{
|
||||
int have = Count(key, hours, nowUtc);
|
||||
string s = $"{have} of {cap} picked up in the last {LootPerDay.WindowText(hours)}";
|
||||
TimeSpan? next = NextFree(key, hours, cap, nowUtc);
|
||||
if (have > 0 && next is TimeSpan t) s += (have >= cap ? ", none until " : ", next frees in ") + Duration(t);
|
||||
return s;
|
||||
}
|
||||
|
||||
/// <summary>"5 h 10 min", "45 min", "under a minute".</summary>
|
||||
public static string Duration(TimeSpan t)
|
||||
{
|
||||
long minutes = (long)Math.Ceiling(t.TotalMinutes);
|
||||
if (minutes <= 0) return "under a minute";
|
||||
long h = minutes / 60, m = minutes % 60;
|
||||
if (h == 0) return m.ToString(CultureInfo.InvariantCulture) + " min";
|
||||
return h.ToString(CultureInfo.InvariantCulture) + " h" + (m > 0 ? " " + m.ToString(CultureInfo.InvariantCulture) + " min" : string.Empty);
|
||||
}
|
||||
|
||||
private void Prune(DateTime nowUtc)
|
||||
{
|
||||
DateTime from = nowUtc - TimeSpan.FromHours(LootPerDay.MaxHours);
|
||||
var empty = new List<string>();
|
||||
foreach (var kv in _rules)
|
||||
{
|
||||
kv.Value.RemoveAll(p => p.AtUtc <= from);
|
||||
if (kv.Value.Count == 0) empty.Add(kv.Key);
|
||||
}
|
||||
foreach (string k in empty) _rules.Remove(k);
|
||||
}
|
||||
|
||||
// ── File ──────────────────────────────────────────────────────────────────
|
||||
|
||||
private void Save()
|
||||
{
|
||||
if (Path.Length == 0) return;
|
||||
try
|
||||
{
|
||||
string? dir = System.IO.Path.GetDirectoryName(Path);
|
||||
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
|
||||
string tmp = Path + ".tmp";
|
||||
File.WriteAllText(tmp, Serialize());
|
||||
File.Move(tmp, Path, overwrite: true);
|
||||
Problem = string.Empty;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Problem = $"{Path}: {ex.Message}";
|
||||
}
|
||||
}
|
||||
|
||||
internal string Serialize()
|
||||
{
|
||||
using var stream = new MemoryStream();
|
||||
using (var w = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }))
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteNumber("version", FileVersion);
|
||||
w.WriteStartObject("rules");
|
||||
foreach ((string key, IReadOnlyList<Pick> picks) in Rules())
|
||||
{
|
||||
w.WriteStartArray(key);
|
||||
foreach (Pick p in picks)
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteString("at", p.AtUtc.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture));
|
||||
w.WriteNumber("n", p.Units);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
w.WriteEndArray();
|
||||
}
|
||||
w.WriteEndObject();
|
||||
w.WriteEndObject();
|
||||
}
|
||||
return Encoding.UTF8.GetString(stream.ToArray());
|
||||
}
|
||||
|
||||
private void Parse(string json)
|
||||
{
|
||||
using JsonDocument doc = JsonDocument.Parse(json, new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
|
||||
if (doc.RootElement.ValueKind != JsonValueKind.Object
|
||||
|| !doc.RootElement.TryGetProperty("rules", out JsonElement rules) || rules.ValueKind != JsonValueKind.Object)
|
||||
return;
|
||||
foreach (JsonProperty rule in rules.EnumerateObject())
|
||||
{
|
||||
if (rule.Value.ValueKind != JsonValueKind.Array || string.IsNullOrWhiteSpace(rule.Name)) continue;
|
||||
var list = new List<Pick>();
|
||||
foreach (JsonElement e in rule.Value.EnumerateArray())
|
||||
{
|
||||
if (e.ValueKind != JsonValueKind.Object
|
||||
|| !e.TryGetProperty("at", out JsonElement at) || at.ValueKind != JsonValueKind.String
|
||||
|| !DateTime.TryParse(at.GetString(), CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime when))
|
||||
continue;
|
||||
int n = e.TryGetProperty("n", out JsonElement ne) && ne.ValueKind == JsonValueKind.Number && ne.TryGetInt32(out int v) ? v : 1;
|
||||
list.Add(new Pick(DateTime.SpecifyKind(when, DateTimeKind.Utc), Math.Max(1, n)));
|
||||
}
|
||||
if (list.Count == 0) continue;
|
||||
if (_rules.TryGetValue(rule.Name, out List<Pick>? have)) have.AddRange(list); // same name, other case
|
||||
else _rules[rule.Name] = list;
|
||||
}
|
||||
}
|
||||
}
|
||||
90
Plugins/RynthCore.Plugin.RynthAi/Loot/LootProfileList.cs
Normal file
90
Plugins/RynthCore.Plugin.RynthAi/Loot/LootProfileList.cs
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Loot;
|
||||
|
||||
/// <summary>
|
||||
/// The loot profile pickers' list and selection: the dashboard's Loaded files drawer (LOOT), the
|
||||
/// Classic look's Loot tab, Settings > Looting (the engine's and RynthAi's own) and the Mini Remote's
|
||||
/// Loot row all show this one list, built by LegacyDashboardRenderer.RefreshLootFiles (at load, and
|
||||
/// within 3 s of the LootProfiles folder changing). Pure, apart from listing the folder.
|
||||
/// </summary>
|
||||
internal static class LootProfileList
|
||||
{
|
||||
/// <summary>The first entry: no loot profile.</summary>
|
||||
public const string None = "None";
|
||||
|
||||
/// <summary>
|
||||
/// "None", then the *.utl and *.json files in <paramref name="folder"/> (file names, sorted, any case).
|
||||
/// No such folder: "None" alone.
|
||||
/// </summary>
|
||||
public static List<string> Build(string? folder)
|
||||
{
|
||||
var files = new List<string>();
|
||||
if (!string.IsNullOrEmpty(folder) && Directory.Exists(folder))
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (string f in Directory.GetFiles(folder, "*.utl")) files.Add(Path.GetFileName(f));
|
||||
foreach (string f in Directory.GetFiles(folder, "*.json")) files.Add(Path.GetFileName(f));
|
||||
}
|
||||
catch (IOException) { }
|
||||
catch (UnauthorizedAccessException) { }
|
||||
}
|
||||
files.Sort(StringComparer.OrdinalIgnoreCase);
|
||||
var list = new List<string>(files.Count + 1) { None };
|
||||
list.AddRange(files);
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The entry the pickers select for <paramref name="currentPath"/> (the loot profile in use):
|
||||
/// 0 (None) when there is none; its file's entry when it is in <paramref name="folder"/>; else
|
||||
/// (a profile a meta loaded from elsewhere) <paramref name="previous"/>, kept in the list's range.
|
||||
/// </summary>
|
||||
public static int SelectedIndex(IReadOnlyList<string> list, string? folder, string? currentPath, int previous)
|
||||
{
|
||||
string path = (currentPath ?? string.Empty).Trim().Trim('"');
|
||||
if (path.Length == 0 || list.Count == 0) return 0;
|
||||
string name = Path.GetFileName(path);
|
||||
string? dir = Path.GetDirectoryName(path);
|
||||
if (!string.IsNullOrEmpty(folder) && SameFolder(dir, folder))
|
||||
for (int i = 1; i < list.Count; i++)
|
||||
if (string.Equals(list[i], name, StringComparison.OrdinalIgnoreCase)) return i;
|
||||
return Math.Clamp(previous, 0, list.Count - 1);
|
||||
}
|
||||
|
||||
/// <summary>The name a picker shows for the profile in use: its file name, or None.</summary>
|
||||
public static string ShownName(string? currentPath)
|
||||
{
|
||||
string path = (currentPath ?? string.Empty).Trim().Trim('"');
|
||||
return path.Length == 0 ? None : Path.GetFileName(path);
|
||||
}
|
||||
|
||||
/// <summary>The index of <paramref name="fileName"/> in <paramref name="list"/> (any case), or -1.</summary>
|
||||
public static int IndexOf(IReadOnlyList<string> list, string? fileName)
|
||||
{
|
||||
if (string.IsNullOrEmpty(fileName)) return -1;
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
if (string.Equals(list[i], fileName, StringComparison.OrdinalIgnoreCase)) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/// <summary>The chat line after a picker switched the loot profile (empty path: None).</summary>
|
||||
public static string SwitchedLine(string? newPath) =>
|
||||
string.IsNullOrWhiteSpace(newPath)
|
||||
? "[RynthAi] Loot profile: None (no loot profile in use)."
|
||||
: $"[RynthAi] Loot profile: {Path.GetFileName(newPath.Trim())}.";
|
||||
|
||||
private static bool SameFolder(string? a, string b)
|
||||
{
|
||||
if (string.IsNullOrEmpty(a)) return false;
|
||||
try
|
||||
{
|
||||
return string.Equals(Path.GetFullPath(a).TrimEnd('\\', '/'), Path.GetFullPath(b).TrimEnd('\\', '/'),
|
||||
StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
catch (Exception) { return false; }
|
||||
}
|
||||
}
|
||||
|
|
@ -291,7 +291,8 @@ public sealed class SalvageManager
|
|||
public void NoteLootedForSalvage(uint itemId, string? name = null)
|
||||
{
|
||||
if (itemId == 0) return;
|
||||
if (IsSalvageBag(name ?? _cache?[unchecked((int)itemId)]?.Name)) return;
|
||||
string? noted = name ?? _cache?[unchecked((int)itemId)]?.Name;
|
||||
if (IsSalvageBag(noted) || IsFoolproof(noted)) return;
|
||||
Track(itemId, name);
|
||||
}
|
||||
|
||||
|
|
@ -314,6 +315,11 @@ public sealed class SalvageManager
|
|||
if (_settings.EnableCombineSalvage) _pendingCombineScan = true;
|
||||
return;
|
||||
}
|
||||
if (IsFoolproof(name))
|
||||
{
|
||||
Log($"[Salvage] Not salvaging 0x{itemId:X8} ({name}): {SkipFoolproof}.");
|
||||
return;
|
||||
}
|
||||
|
||||
Track(itemId, name);
|
||||
QueueItem(itemId);
|
||||
|
|
@ -650,12 +656,14 @@ public sealed class SalvageManager
|
|||
internal const string SkipItemsList = "on the Items list";
|
||||
internal const string SkipUst = "it is the UST";
|
||||
internal const string SkipBag = "already a salvage bag (the combine sweep handles bags)";
|
||||
internal const string SkipFoolproof = "a Foolproof tinkering material (salvaging it would turn it into plain salvage)";
|
||||
internal const string SkipGaveUp = "salvage failed too often";
|
||||
|
||||
/// <summary>Why <paramref name="wo"/> (in the pack) must not be salvaged, or null.</summary>
|
||||
private string? SkipReasonFor(uint id, WorldObject wo)
|
||||
{
|
||||
if (IsSalvageBag(wo.Name)) return SkipBag;
|
||||
if (IsFoolproof(wo.Name)) return SkipFoolproof;
|
||||
if (IsWornByPlayer(wo)) return SkipWorn;
|
||||
if (wo.ObjectClass == AcObjectClass.Ust || IsUst(wo.Name)
|
||||
|| (_host.HasGetObjectWcid && _host.TryGetObjectWcid(id, out uint wcid) && wcid == UstWcid))
|
||||
|
|
@ -1703,6 +1711,15 @@ public sealed class SalvageManager
|
|||
return int.TryParse(inside, out value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A Foolproof tinkering material ("Foolproof" plus its material, a bag that can't fail; TinkerPlanner.IsFoolproof
|
||||
/// uses the same name test). R-20261122-193822-831d: one looted from a chest matched the profile's
|
||||
/// "(Salv) Red Garnet" rule by its material, and the batch salvaged it into 33 plain Red Garnet. It is
|
||||
/// already the finished material: never salvaged, whatever a rule says.
|
||||
/// </summary>
|
||||
internal static bool IsFoolproof(string? name)
|
||||
=> !string.IsNullOrEmpty(name) && name.IndexOf("Foolproof", StringComparison.OrdinalIgnoreCase) >= 0;
|
||||
|
||||
private static bool IsSalvageBag(string? name)
|
||||
{
|
||||
if (string.IsNullOrEmpty(name))
|
||||
|
|
|
|||
|
|
@ -168,6 +168,17 @@ internal sealed class UseRefusalWatch
|
|||
return wasStuck ? Verdict.Recovered : Verdict.None;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="corpseId"/>'s opens say nothing about the server (a wall was in the way,
|
||||
/// RynthAiPlugin.CorpseBehindWall.cs): its pending open is dropped and its refusals are taken back.
|
||||
/// </summary>
|
||||
public void Forget(int corpseId)
|
||||
{
|
||||
if (_pending && _pendingId == corpseId) { _pending = false; _answeredAt = 0; }
|
||||
if (_refused.Remove(corpseId) && Refusals > 0 && State == Phase.Normal) Refusals--;
|
||||
if (LastRefusedCorpse == corpseId) LastRefusedCorpse = 0;
|
||||
}
|
||||
|
||||
/// <summary>Back to normal: a relog, a login, a successful open.</summary>
|
||||
public void Reset()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -253,6 +253,7 @@ public sealed partial class RynthAiPlugin
|
|||
["pickupmacrooff"] = "LootChestsMacroOff", // Settings > Looting > Pickup with macro off
|
||||
["lootchestsmacrooff"] = "LootChestsMacroOff",
|
||||
["meleethroughwalls"] = "MeleeThroughWalls", // Settings > Combat > Targeting > Melee through walls
|
||||
["debuffallbeforeattacking"] = "DebuffAllBeforeAttacking", // Settings > Combat > Targeting > Debuff every monster in range before attacking
|
||||
["lootnearbychests"] = "LootNearbyChests", // Settings > Looting > Loot Nearby Chests
|
||||
["dooropenrange"] = "OpenDoorRange",
|
||||
["autofellowmanagement"] = "AutoFellowMgmt",
|
||||
|
|
|
|||
|
|
@ -0,0 +1,32 @@
|
|||
// ExpressionEngine.RaNav.cs - ranav[]: the nav route RynthAi has loaded, as one JSON line, for a script that
|
||||
// runs routes of its own (2026-11-18: a route for a Thread where the explore can't go,
|
||||
// then a second one looped from where the first ends):
|
||||
// {"name":"Pit00C1In","points":24,"index":3,"type":"Once","finished":false,"nav":true,"macro":true}
|
||||
// name is the file's name without .nav ("" for a route made on the fly: /ra dunnav-to, a GoTo, a meta's nav);
|
||||
// finished is a Once route walked to its end (the meta's "nav route empty").
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Meta;
|
||||
|
||||
internal sealed partial class ExpressionEngine
|
||||
{
|
||||
private string EvalRaNav()
|
||||
{
|
||||
var s = _settings;
|
||||
if (s == null) return "{}";
|
||||
var route = s.CurrentRoute;
|
||||
string path = s.CurrentNavPath ?? string.Empty;
|
||||
string name = path.Length > 0 ? System.IO.Path.GetFileNameWithoutExtension(path) : string.Empty;
|
||||
var sb = new StringBuilder(160);
|
||||
sb.Append("{\"name\":\"").Append(JsonEncodedText.Encode(name).ToString()).Append('"');
|
||||
sb.Append(",\"points\":").Append((route?.Points.Count ?? 0).ToString(CultureInfo.InvariantCulture));
|
||||
sb.Append(",\"index\":").Append(s.ActiveNavIndex.ToString(CultureInfo.InvariantCulture));
|
||||
sb.Append(",\"type\":\"").Append(route?.RouteType.ToString() ?? "None").Append('"');
|
||||
sb.Append(",\"finished\":").Append(s.NavRouteFinished() ? "true" : "false");
|
||||
sb.Append(",\"nav\":").Append(s.EnableNavigation ? "true" : "false");
|
||||
sb.Append(",\"macro\":").Append(s.IsMacroRunning ? "true" : "false");
|
||||
return sb.Append('}').ToString();
|
||||
}
|
||||
}
|
||||
|
|
@ -234,6 +234,10 @@ internal sealed partial class ExpressionEngine
|
|||
// radunexploreinfo[]: the explore as JSON (state, rooms, the shut doors and the rooms behind each, the
|
||||
// lever errand, the last lever's result), "{}" before the first. For the Lua script's json.decode.
|
||||
internal Func<string>? DunExploreInfo { get; set; }
|
||||
// rabuffsdue[seconds] (RynthAi only, 2026-11-20): how many buffs a rebuff would cast if Rebuff With were
|
||||
// `seconds` (BuffManager.CountBuffsDue): the character's, the item spells' and the shield's. -1 with buffing
|
||||
// off or no buff manager. A script asks it before a Thread, since Lua sees only the character's own.
|
||||
internal Func<int, int>? BuffsDue { get; set; }
|
||||
|
||||
// ── Backward-compat shim ──────────────────────────────────────────────────
|
||||
|
||||
|
|
@ -422,6 +426,9 @@ internal sealed partial class ExpressionEngine
|
|||
"radunexplorerooms" => (DunExploreStatus?.Invoke().Rooms ?? 0).ToString(CultureInfo.InvariantCulture),
|
||||
"radunexplorevisited" => (DunExploreStatus?.Invoke().Visited ?? 0).ToString(CultureInfo.InvariantCulture),
|
||||
"radunexploreinfo" => DunExploreInfo?.Invoke() ?? "{}",
|
||||
"ranav" => EvalRaNav(),
|
||||
"rabuffsdue" => (BuffsDue?.Invoke(double.TryParse(A(0), NumberStyles.Float, CultureInfo.InvariantCulture, out double dueSec)
|
||||
? (int)Math.Clamp(dueSec, 0, int.MaxValue) : 0) ?? -1).ToString(CultureInfo.InvariantCulture),
|
||||
|
||||
// ── World object queries ──────────────────────────────────────────
|
||||
"wobjectfindnearestbytemplatetype" => EvalWobjectFindNearestByTemplateType(A(0)),
|
||||
|
|
@ -3726,6 +3733,7 @@ internal sealed partial class ExpressionEngine
|
|||
["TargetLock"] = (() => B(s.TargetLock), v => s.TargetLock = ToDouble(v) != 0),
|
||||
["FightSelectedTarget"] = (() => B(s.FightSelectedTarget), v => s.FightSelectedTarget = ToDouble(v) != 0),
|
||||
["MeleeThroughWalls"] = (() => B(s.MeleeThroughWalls), v => s.MeleeThroughWalls = ToDouble(v) != 0),
|
||||
["DebuffAllBeforeAttacking"] = (() => B(s.DebuffAllBeforeAttacking), v => s.DebuffAllBeforeAttacking = ToDouble(v) != 0),
|
||||
["RingRange"] = (() => I(s.RingRange), v => { if (int.TryParse(v, out int i)) s.RingRange = i; }),
|
||||
["ApproachRange"] = (() => I(s.ApproachRange), v => { if (int.TryParse(v, out int i)) s.ApproachRange = i; }),
|
||||
["MinRingTargets"] = (() => I(s.MinRingTargets), v => { if (int.TryParse(v, out int i)) s.MinRingTargets = i; }),
|
||||
|
|
@ -3745,6 +3753,7 @@ internal sealed partial class ExpressionEngine
|
|||
["MissileAttackPower"] = (() => I(s.MissileAttackPower), v => { if (int.TryParse(v, out int i)) s.MissileAttackPower = i; }),
|
||||
["CustomPetRange"] = (() => I(s.CustomPetRange), v => { if (int.TryParse(v, out int i)) s.CustomPetRange = i; }),
|
||||
["PetMinMonsters"] = (() => I(s.PetMinMonsters), v => { if (int.TryParse(v, out int i)) s.PetMinMonsters = i; }),
|
||||
["PetElement"] = (() => s.PetElement.Length > 0 ? s.PetElement : "Any", v => s.PetElement = PetChoice.NormalizeElement(v)),
|
||||
// VTank-meta migration (Phase 2): fields existed but weren't exposed here.
|
||||
["CorpseApproachRangeMax"] = (() => D(s.CorpseApproachRangeMax), v => { if (double.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out double d)) s.CorpseApproachRangeMax = d; }),
|
||||
["CorpseApproachRangeMin"] = (() => D(s.CorpseApproachRangeMin), v => { if (double.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out double d)) s.CorpseApproachRangeMin = d; }),
|
||||
|
|
|
|||
|
|
@ -66,7 +66,7 @@ internal sealed partial class MetaManager
|
|||
{
|
||||
DateTime now = Clock();
|
||||
_settings.CurrentState = s.State;
|
||||
_settings.IsMacroRunning = s.MacroRunning;
|
||||
_settings.SetMacroRunning(s.MacroRunning, "the meta resume after a reload");
|
||||
_lastState = s.State;
|
||||
_lastMacroRunning = s.MacroRunning; // no "macro started": that would re-arm every rule
|
||||
_settings.MetaCallStackReset = false;
|
||||
|
|
|
|||
|
|
@ -384,6 +384,7 @@ internal sealed partial class MetaManager
|
|||
engine.LastChestLooted = _lastChestLooted;
|
||||
engine.DunExploreStatus = _dunExploreStatus;
|
||||
engine.DunExploreInfo = _dunExploreInfo;
|
||||
engine.BuffsDue = sec => _buffManager?.CountBuffsDue(sec) ?? -1; // the buff manager may come later
|
||||
// vtsetsetting[] / vtgetsetting[] take VTank names and units, as '/vt opt set|get' does.
|
||||
engine.VtOptionSetter = TrySetVtOption;
|
||||
engine.VtOptionGetter = GetVtOption;
|
||||
|
|
@ -1001,6 +1002,8 @@ internal sealed partial class MetaManager
|
|||
private void ExecuteAction(MetaRule rule)
|
||||
{
|
||||
_actionDepth++;
|
||||
// A macro stop or start an action makes names the meta (LegacyUiSettings.MacroSource).
|
||||
using var source = _settings.MacroSource($"the meta (state '{_settings.CurrentState}')");
|
||||
try { ExecuteActionCore(rule); }
|
||||
finally { _actionDepth--; }
|
||||
}
|
||||
|
|
@ -1626,6 +1629,7 @@ internal sealed partial class MetaManager
|
|||
["pickupmacrooff"] = "LootChestsMacroOff", // Settings > Looting > Pickup with macro off
|
||||
["lootchestsmacrooff"] = "LootChestsMacroOff",
|
||||
["meleethroughwalls"] = "MeleeThroughWalls", // Settings > Combat > Targeting > Melee through walls
|
||||
["debuffallbeforeattacking"] = "DebuffAllBeforeAttacking", // Settings > Combat > Targeting > Debuff every monster in range before attacking
|
||||
["lootnearbychests"] = "LootNearbyChests", // Settings > Looting > Loot Nearby Chests
|
||||
["dooropenrange"] = "OpenDoorRange",
|
||||
["autofellowmanagement"] = "AutoFellowMgmt",
|
||||
|
|
|
|||
345
Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/KitAuto.cs
Normal file
345
Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/KitAuto.cs
Normal file
|
|
@ -0,0 +1,345 @@
|
|||
// KitAuto.cs - "Make kits when low" (Mini Remote > Crafting > Kits, /ra kits auto): with the macro
|
||||
// on, a kit run starts by itself when fewer than MakeKitsBelow Plentiful Healing Kits are carried
|
||||
// and nothing needs the character. Pure (System only), so RynthCore.RynthAiTests links it; the
|
||||
// plugin side (RynthAiPlugin.Kits.cs) reads the facts each tick, holds the bot while a run goes
|
||||
// (the way it holds for buffs) and KitRunner does the combines.
|
||||
//
|
||||
// A start needs every one of: the setting on, the macro on, fewer kits than the line, nothing else
|
||||
// going (buffing or healing, a fight, looting, salvaging, a portal, a vendor, following, ...),
|
||||
// vitals over their heal lines, no monster within the safe radius (35 yd, or Monster Range when
|
||||
// that is bigger), no hit for 20 s, and the pack making one kit at the Min chance % floor with
|
||||
// Healing trained. Then the bot is held still: peace mode is asked for (combat mode is the only
|
||||
// one left from a fight), and once in peace and standing still for a second the run starts.
|
||||
//
|
||||
// A run stops at once on a monster inside the radius, a hit, a heal line, buffing, the macro off,
|
||||
// or moving (KitRunner checks the last three itself). Waits after a run:
|
||||
// - a stop for danger (monster, damage, heal, moving, leaving peace): 60 s;
|
||||
// - a run that made nothing (every combine failed, the server's chance under the floor, a
|
||||
// refusal) or the player's Stop: 10 min;
|
||||
// - a run that made kits: the next look in 30 s (the count decides then).
|
||||
// Before a start, a pack that can't make a kit (out of an ingredient, under the floor, untrained)
|
||||
// is said once per reason, then looked at again every 30 s.
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.MiniRemote.Crafting;
|
||||
|
||||
/// <summary>Why a kit run ended (KitRunner sets it; the "when low" waits follow it).</summary>
|
||||
internal enum KitStopKind
|
||||
{
|
||||
/// <summary>Logged out, settings gone: no wait of its own.</summary>
|
||||
Other,
|
||||
/// <summary>Made the count asked for, or the pack ran out.</summary>
|
||||
Finished,
|
||||
/// <summary>A monster, a hit, a heal line, buffing, moving, leaving peace mode.</summary>
|
||||
Danger,
|
||||
/// <summary>The server's chance under the floor, a refusal, no answer, AC's dialog wanting a click.</summary>
|
||||
Refused,
|
||||
/// <summary>The player's Stop (the button, /ra kits stop).</summary>
|
||||
User,
|
||||
/// <summary>The macro was turned off during a "when low" run.</summary>
|
||||
MacroOff,
|
||||
}
|
||||
|
||||
/// <summary>What stops a "when low" start (the first that holds, cheap ones first).</summary>
|
||||
internal enum KitBlock { None, Off, MacroOff, Enough, Busy, Vitals, Monster, Hurt, Pack }
|
||||
|
||||
/// <summary>What the next tick does about "Make kits when low".</summary>
|
||||
internal enum KitAutoStep
|
||||
{
|
||||
/// <summary>Nothing: the bot goes on as usual.</summary>
|
||||
Wait,
|
||||
/// <summary>Hold the bot still (getting ready).</summary>
|
||||
Hold,
|
||||
/// <summary>Hold the bot and ask for peace mode.</summary>
|
||||
GoPeace,
|
||||
/// <summary>Start the run now (and hold the bot while it goes).</summary>
|
||||
Start,
|
||||
}
|
||||
|
||||
/// <summary>One look at the character for "Make kits when low" (RynthAiPlugin.Kits.cs fills it).</summary>
|
||||
internal sealed class KitAutoFacts
|
||||
{
|
||||
public bool Enabled;
|
||||
public bool MacroOn;
|
||||
/// <summary>Plentiful Healing Kits carried (main pack and side packs).</summary>
|
||||
public int Kits;
|
||||
/// <summary>A run starts with fewer kits than this.</summary>
|
||||
public int Below = KitAuto.DefaultBelow;
|
||||
/// <summary>"" when the pack makes a kit at the floor; else the planner's why (out of X, under the floor, untrained).</summary>
|
||||
public string PackWhy = string.Empty;
|
||||
public bool InPeace = true;
|
||||
/// <summary>The character moved since the last tick.</summary>
|
||||
public bool Moving;
|
||||
/// <summary>The nearest live monster (PositiveInfinity = none known).</summary>
|
||||
public double NearestMonsterYd = double.PositiveInfinity;
|
||||
public double RadiusYd = KitAuto.DefaultRadiusYd;
|
||||
/// <summary>Since health last went down (MaxValue = not this session).</summary>
|
||||
public long SinceHurtMs = long.MaxValue;
|
||||
/// <summary>"" when health, stamina and mana are over their lines; else which one.</summary>
|
||||
public string VitalsWhy = string.Empty;
|
||||
/// <summary>"" when nothing else needs the character; else what does (buffing, a fight, looting, ...).</summary>
|
||||
public string BusyWhy = string.Empty;
|
||||
}
|
||||
|
||||
internal sealed class KitAuto
|
||||
{
|
||||
public const int DefaultBelow = 2;
|
||||
public const int DefaultUpTo = 5;
|
||||
public const int MaxBelow = 50;
|
||||
public const int MaxUpTo = 100;
|
||||
/// <summary>No monster this close (or within Monster Range, when that is bigger) for a start; one coming this close stops a run.</summary>
|
||||
public const double DefaultRadiusYd = 35;
|
||||
/// <summary>No start for this long after a hit.</summary>
|
||||
public const long HurtQuietMs = 20_000;
|
||||
/// <summary>The next look while something else has the character, or the kits are enough.</summary>
|
||||
public const long CheckMs = 5_000;
|
||||
/// <summary>The next look after the pack couldn't make a kit, and after a run that made some.</summary>
|
||||
public const long PackCheckMs = 30_000;
|
||||
/// <summary>The wait after a stop for danger (a monster, a hit, a heal line, moving).</summary>
|
||||
public const long CooldownMs = 60_000;
|
||||
/// <summary>The wait after a run that made nothing, or the player's Stop.</summary>
|
||||
public const long BackoffMs = 600_000;
|
||||
/// <summary>Getting ready (peace mode, standing still) gives up after this.</summary>
|
||||
public const long ReadyTimeoutMs = 6_000;
|
||||
/// <summary>Standing still this long in peace mode before the first combine.</summary>
|
||||
public const long SettleMs = 1_000;
|
||||
/// <summary>Peace mode is asked for again after this.</summary>
|
||||
public const long PeaceResendMs = 2_000;
|
||||
|
||||
/// <summary>Clock (ms, monotonic); tests replace it.</summary>
|
||||
public Func<long> NowMs = static () => Environment.TickCount64;
|
||||
/// <summary>A chat line for the player (a reason said once).</summary>
|
||||
public Action<string>? Say;
|
||||
|
||||
private long _nextCheckAt;
|
||||
private string _waitWhy = string.Empty;
|
||||
private long _readySince = -1;
|
||||
private long _stillSince = -1;
|
||||
private long _peaceSentAt = long.MinValue / 2;
|
||||
private string _said = string.Empty;
|
||||
private volatile string _status = "off";
|
||||
|
||||
/// <summary>What it is doing, for the Kits tab and /ra kits auto status.</summary>
|
||||
public string Status => _status;
|
||||
/// <summary>Getting ready for a run (the bot is held).</summary>
|
||||
public bool Readying => _readySince >= 0;
|
||||
/// <summary>No look before this (0 = the next tick).</summary>
|
||||
public long NextCheckAt => _nextCheckAt;
|
||||
/// <summary>The reason last said in chat ("" = none since the last run that made kits).</summary>
|
||||
public string Said => _said;
|
||||
|
||||
// ── Rules ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The first thing that stops a start now (KitBlock.None and "" when it can go, peace mode aside).</summary>
|
||||
public static (KitBlock Block, string Why) Blocker(KitAutoFacts f)
|
||||
{
|
||||
if (!f.Enabled) return (KitBlock.Off, "off");
|
||||
if (!f.MacroOn) return (KitBlock.MacroOff, "the macro is off");
|
||||
int below = Math.Clamp(f.Below, 1, MaxBelow);
|
||||
if (f.Kits >= below) return (KitBlock.Enough, $"{KitsText(f.Kits)} carried (makes more under {below})");
|
||||
if (f.BusyWhy.Length > 0) return (KitBlock.Busy, f.BusyWhy);
|
||||
if (f.VitalsWhy.Length > 0) return (KitBlock.Vitals, f.VitalsWhy);
|
||||
if (f.NearestMonsterYd <= f.RadiusYd) return (KitBlock.Monster, $"monster {f.NearestMonsterYd:0} yd away");
|
||||
if (f.SinceHurtMs < HurtQuietMs) return (KitBlock.Hurt, $"hit {f.SinceHurtMs / 1000} s ago");
|
||||
if (f.PackWhy.Length > 0) return (KitBlock.Pack, f.PackWhy);
|
||||
return (KitBlock.None, string.Empty);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why a "when low" run must stop now ("" = go on): buffing or a fight, a heal line, a monster
|
||||
/// within the radius. The macro off, moving, a hit and leaving peace mode KitRunner stops on itself.
|
||||
/// </summary>
|
||||
public static string StopReason(KitAutoFacts f)
|
||||
{
|
||||
if (f.BusyWhy.Length > 0) return f.BusyWhy;
|
||||
if (f.VitalsWhy.Length > 0) return f.VitalsWhy;
|
||||
if (f.NearestMonsterYd <= f.RadiusYd) return $"a monster came within {f.NearestMonsterYd:0} yd";
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
public static string KitsText(int n) => n == 1 ? "1 kit" : $"{n} kits";
|
||||
|
||||
// ── The tick ────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// One tick with no run going. <paramref name="facts"/> is read only when a look is due (it walks
|
||||
/// the pack and the world), every tick while getting ready.
|
||||
/// </summary>
|
||||
public KitAutoStep Decide(Func<KitAutoFacts> facts)
|
||||
{
|
||||
long now = NowMs();
|
||||
if (_readySince < 0 && now < _nextCheckAt)
|
||||
{
|
||||
long left = (_nextCheckAt - now + 999) / 1000;
|
||||
_status = (_waitWhy.Length > 0 ? "waiting: " + _waitWhy + "; " : "") + $"next check in {left} s";
|
||||
return KitAutoStep.Wait;
|
||||
}
|
||||
|
||||
KitAutoFacts f = facts();
|
||||
var (block, why) = Blocker(f);
|
||||
if (block != KitBlock.None)
|
||||
{
|
||||
bool wasReady = _readySince >= 0;
|
||||
EndReady();
|
||||
switch (block)
|
||||
{
|
||||
case KitBlock.Off:
|
||||
_status = "off";
|
||||
_nextCheckAt = 0;
|
||||
break;
|
||||
case KitBlock.MacroOff:
|
||||
_status = "waiting: the macro is off";
|
||||
_nextCheckAt = 0;
|
||||
break;
|
||||
case KitBlock.Pack:
|
||||
// Said once per reason; not "can't read your skill" (the qualities arrive late after a login).
|
||||
if (_said != why && !why.StartsWith("can't read", StringComparison.Ordinal))
|
||||
{
|
||||
_said = why;
|
||||
SayLine($"[RynthAi] Make kits when low: {KitsText(f.Kits)} left, but none can be made now: {why}.");
|
||||
}
|
||||
Wait(now, PackCheckMs, why);
|
||||
break;
|
||||
case KitBlock.Enough:
|
||||
Wait(now, CheckMs, why);
|
||||
break;
|
||||
default:
|
||||
// Something came up while getting ready: the danger wait, as after a stopped run.
|
||||
bool danger = block is KitBlock.Monster or KitBlock.Hurt or KitBlock.Vitals;
|
||||
Wait(now, wasReady && danger ? CooldownMs : CheckMs, why);
|
||||
break;
|
||||
}
|
||||
if (block is not (KitBlock.Off or KitBlock.MacroOff)) _status = "waiting: " + why;
|
||||
return KitAutoStep.Wait;
|
||||
}
|
||||
|
||||
// Everything clear: hold the bot, go to peace mode, stand still, then start.
|
||||
if (_readySince < 0)
|
||||
{
|
||||
_readySince = now;
|
||||
_stillSince = -1;
|
||||
_peaceSentAt = long.MinValue / 2;
|
||||
}
|
||||
if (now - _readySince > ReadyTimeoutMs)
|
||||
{
|
||||
EndReady();
|
||||
Wait(now, CooldownMs, f.InPeace ? "couldn't stand still" : "couldn't go to peace mode");
|
||||
_status = "waiting: " + _waitWhy;
|
||||
return KitAutoStep.Wait;
|
||||
}
|
||||
if (!f.InPeace)
|
||||
{
|
||||
_stillSince = -1;
|
||||
_status = "going to peace mode";
|
||||
if (now - _peaceSentAt >= PeaceResendMs)
|
||||
{
|
||||
_peaceSentAt = now;
|
||||
return KitAutoStep.GoPeace;
|
||||
}
|
||||
return KitAutoStep.Hold;
|
||||
}
|
||||
if (f.Moving)
|
||||
{
|
||||
_stillSince = -1;
|
||||
_status = "stopping to make kits";
|
||||
return KitAutoStep.Hold;
|
||||
}
|
||||
if (_stillSince < 0) _stillSince = now;
|
||||
if (now - _stillSince < SettleMs)
|
||||
{
|
||||
_status = "getting ready";
|
||||
return KitAutoStep.Hold;
|
||||
}
|
||||
EndReady();
|
||||
_status = "starting";
|
||||
return KitAutoStep.Start;
|
||||
}
|
||||
|
||||
/// <summary>The run went out (the Kits tab shows "running made/limit").</summary>
|
||||
public void Running(int made, int limit) => _status = limit > 0 ? $"running {made}/{limit}" : $"running ({made} made)";
|
||||
|
||||
/// <summary>KitRunner refused the start after all (its own checks): look again later.</summary>
|
||||
public void StartRefused(string why)
|
||||
{
|
||||
Wait(NowMs(), PackCheckMs, why);
|
||||
_status = "waiting: " + why;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A "when low" run ended: the wait that follows it. Returns what the run's summary line adds
|
||||
/// ("" = nothing), so one line says how it went and when the next try is.
|
||||
/// </summary>
|
||||
public string RunEnded(KitStopKind kind, int made)
|
||||
{
|
||||
long now = NowMs();
|
||||
EndReady();
|
||||
switch (kind)
|
||||
{
|
||||
case KitStopKind.MacroOff:
|
||||
case KitStopKind.Other:
|
||||
_nextCheckAt = 0;
|
||||
_waitWhy = string.Empty;
|
||||
_status = kind == KitStopKind.MacroOff ? "waiting: the macro is off" : "idle";
|
||||
if (made > 0) _said = string.Empty;
|
||||
return string.Empty;
|
||||
case KitStopKind.Danger:
|
||||
if (made > 0) _said = string.Empty;
|
||||
Wait(now, CooldownMs, "the last run was stopped");
|
||||
return $" Next try in {CooldownMs / 1000} s at the earliest.";
|
||||
case KitStopKind.User:
|
||||
Wait(now, BackoffMs, "you stopped the last run");
|
||||
return $" Next try in {BackoffMs / 60_000} min (turn Make kits when low off to stop it for good).";
|
||||
default:
|
||||
if (made <= 0)
|
||||
{
|
||||
Wait(now, BackoffMs, "the last run made nothing");
|
||||
return $" Next try in {BackoffMs / 60_000} min.";
|
||||
}
|
||||
_said = string.Empty;
|
||||
Wait(now, PackCheckMs, string.Empty);
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The setting was turned on, or the player asked (/ra kits auto on): look on the next tick.</summary>
|
||||
public void LookNow()
|
||||
{
|
||||
EndReady();
|
||||
_nextCheckAt = 0;
|
||||
_waitWhy = string.Empty;
|
||||
_said = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>The setting is off (or the character logged out).</summary>
|
||||
public void Off()
|
||||
{
|
||||
EndReady();
|
||||
_nextCheckAt = 0;
|
||||
_waitWhy = string.Empty;
|
||||
_status = "off";
|
||||
}
|
||||
|
||||
/// <summary>Logout: nothing carries over to the next character.</summary>
|
||||
public void Reset()
|
||||
{
|
||||
Off();
|
||||
_said = string.Empty;
|
||||
}
|
||||
|
||||
private void Wait(long now, long ms, string why)
|
||||
{
|
||||
_nextCheckAt = now + ms;
|
||||
_waitWhy = why;
|
||||
}
|
||||
|
||||
private void EndReady()
|
||||
{
|
||||
_readySince = -1;
|
||||
_stillSince = -1;
|
||||
}
|
||||
|
||||
private void SayLine(string line)
|
||||
{
|
||||
try { Say?.Invoke(line); } catch { }
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,262 @@
|
|||
// KitPlanner.cs - "Make kits": which kits the pack's ingredients make, how many, and the next
|
||||
// combine. Pure (System only), so RynthCore.RynthAiTests links it; KitRunner does the work.
|
||||
//
|
||||
// Retail data (ACE World Database v0.9.293, recipes 4022-4025; ACE RecipeManager):
|
||||
// Treated Mandrake (22448) on Treated Hyssop (22447), either way round
|
||||
// -> Combined Hyssop and Mandrake (22446) Healing, difficulty 100
|
||||
// Combined Hyssop and Mandrake (22446) on Soft Bandages (22445), either way round
|
||||
// -> Plentiful Healing Kit (22449, 100 uses) Healing, difficulty 200
|
||||
// Each combine uses one of each item, success or failure (a failure makes nothing). The chance is
|
||||
// ACE's SkillCheck.GetSkillChance(buffed skill, difficulty) = 1 - 1/(1 + e^(0.03 (skill - diff))),
|
||||
// plus the Craftsman augmentation's skill (which only raises it: our figure is the floor). An
|
||||
// untrained skill is refused by the server.
|
||||
// That is the only Plentiful kit in the retail data: there is no Plentiful mana or stamina kit to
|
||||
// make there. Another kit chain is one more KitRecipe in Retail.
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.MiniRemote.Crafting;
|
||||
|
||||
/// <summary>An item a kit recipe uses or makes: its weenie class id and its name (the name is the fallback match).</summary>
|
||||
internal sealed record KitPart(uint Wcid, string Name);
|
||||
|
||||
/// <summary>One combine: <see cref="Source"/> used on <see cref="Target"/> makes <see cref="Product"/>.</summary>
|
||||
internal sealed record KitCombine(
|
||||
string Label, KitPart Source, KitPart Target, KitPart Product, int SkillId, int Difficulty,
|
||||
string SuccessText, string FailText);
|
||||
|
||||
/// <summary>A kit and the combines that make it (the last one makes the kit; earlier ones make its parts).</summary>
|
||||
internal sealed record KitRecipe(string Id, string Name, KitPart Product, KitCombine[] Steps)
|
||||
{
|
||||
public KitCombine Final => Steps[^1];
|
||||
|
||||
/// <summary>The combine that makes <paramref name="part"/>, or null for an ingredient you carry.</summary>
|
||||
public KitCombine? Producer(KitPart part) => Steps.FirstOrDefault(s => s.Product.Wcid == part.Wcid);
|
||||
|
||||
/// <summary>The items you carry for it (not made by an earlier step), in step order.</summary>
|
||||
public IEnumerable<KitPart> Ingredients()
|
||||
{
|
||||
var seen = new HashSet<uint>();
|
||||
foreach (var s in Steps)
|
||||
foreach (var p in new[] { s.Source, s.Target })
|
||||
if (seen.Add(p.Wcid)) yield return p;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A stack in the pack as the planner sees it (Wcid 0 = unknown: the name decides).</summary>
|
||||
internal readonly record struct KitStack(int Id, uint Wcid, string Name, int Count);
|
||||
|
||||
/// <summary>The crafting skill: its buffed value and training (2 trained, 3 specialized); Known false when the engine can't read it.</summary>
|
||||
internal readonly record struct KitSkill(bool Known, int Buffed, int Training)
|
||||
{
|
||||
public static readonly KitSkill Unknown = new(false, 0, 0);
|
||||
public bool Trained => Training >= 2;
|
||||
}
|
||||
|
||||
/// <summary>One step's chance in a plan (-1 percent = unknown).</summary>
|
||||
internal readonly record struct KitStepChance(KitCombine Step, int Percent, bool UnderFloor);
|
||||
|
||||
/// <summary>What the pack makes of one kit.</summary>
|
||||
internal sealed class KitPlanRow
|
||||
{
|
||||
public KitRecipe Recipe = null!;
|
||||
/// <summary>Kits the pack makes if every combine works.</summary>
|
||||
public int CanMake;
|
||||
/// <summary>Each item the recipe uses (and makes on the way), with the count carried.</summary>
|
||||
public List<(KitPart Part, int Count)> Parts = new();
|
||||
public List<KitStepChance> Chances = new();
|
||||
/// <summary>Why no combine can go now ("" when one can).</summary>
|
||||
public string Blocked = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>The next combine: the stacks to use, or why none (Step null).</summary>
|
||||
internal readonly record struct KitNext(KitCombine? Step, int SourceId, int TargetId, int Percent, string Why)
|
||||
{
|
||||
public static KitNext None(string why) => new(null, 0, 0, -1, why);
|
||||
}
|
||||
|
||||
internal static class KitPlanner
|
||||
{
|
||||
public const int SkillHealing = 21;
|
||||
/// <summary>The Min chance % a new character starts with.</summary>
|
||||
public const int DefaultFloorPercent = 90;
|
||||
|
||||
public static readonly KitPart SoftBandages = new(22445, "Soft Bandages");
|
||||
public static readonly KitPart CombinedHerbs = new(22446, "Combined Hyssop and Mandrake");
|
||||
public static readonly KitPart TreatedHyssop = new(22447, "Treated Hyssop");
|
||||
public static readonly KitPart TreatedMandrake = new(22448, "Treated Mandrake");
|
||||
public static readonly KitPart PlentifulHealingKit = new(22449, "Plentiful Healing Kit");
|
||||
|
||||
/// <summary>The retail kit recipes (ACE World Database).</summary>
|
||||
public static readonly KitRecipe[] Retail =
|
||||
{
|
||||
new("plentiful-healing", "Plentiful Healing Kit", PlentifulHealingKit, new[]
|
||||
{
|
||||
new KitCombine("Combine the herbs", TreatedMandrake, TreatedHyssop, CombinedHerbs, SkillHealing, 100,
|
||||
"You crumble the dried and treated leaves together.",
|
||||
"You crumble the leaves and they become useless."),
|
||||
new KitCombine("Pack the kit", CombinedHerbs, SoftBandages, PlentifulHealingKit, SkillHealing, 200,
|
||||
"You pack the bandages with the herbs. The odor is pungent and heady. The kit appears to be bulkier than any others you have seen.",
|
||||
"The herbs spill out of the bandages onto the ground. The bandages are ruined as they unravel onto the dirt."),
|
||||
}),
|
||||
};
|
||||
|
||||
public static string SkillName(int skillId) => skillId switch
|
||||
{
|
||||
SkillHealing => "Healing",
|
||||
_ => $"skill {skillId}",
|
||||
};
|
||||
|
||||
// ── Chance ──────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>ACE SkillCheck.GetSkillChance (factor 0.03), 0-1.</summary>
|
||||
public static double Chance(int skill, int difficulty)
|
||||
{
|
||||
double c = 1.0 - 1.0 / (1.0 + Math.Exp(0.03 * (skill - difficulty)));
|
||||
return Math.Clamp(c, 0.0, 1.0);
|
||||
}
|
||||
|
||||
/// <summary>The chance as the server's prompt shows it (a rounded percent).</summary>
|
||||
public static int Percent(int skill, int difficulty) => (int)Math.Round(Chance(skill, difficulty) * 100.0, MidpointRounding.AwayFromZero);
|
||||
|
||||
/// <summary>A step's percent for this skill (-1 unknown).</summary>
|
||||
public static int StepPercent(KitCombine step, Func<int, KitSkill> skill)
|
||||
{
|
||||
var s = skill(step.SkillId);
|
||||
return s.Known ? Percent(s.Buffed, step.Difficulty) : -1;
|
||||
}
|
||||
|
||||
// ── Counting ────────────────────────────────────────────────────────────
|
||||
|
||||
public static bool Matches(KitPart part, KitStack stack)
|
||||
=> stack.Wcid != 0 ? stack.Wcid == part.Wcid : string.Equals(stack.Name, part.Name, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>How many of a part the pack holds (every matching stack).</summary>
|
||||
public static int Count(KitPart part, IReadOnlyList<KitStack> pack)
|
||||
{
|
||||
int n = 0;
|
||||
foreach (var s in pack) if (Matches(part, s)) n += Math.Max(1, s.Count);
|
||||
return n;
|
||||
}
|
||||
|
||||
/// <summary>The first stack of a part (its object id), 0 when none.</summary>
|
||||
public static int FirstStack(KitPart part, IReadOnlyList<KitStack> pack)
|
||||
{
|
||||
foreach (var s in pack) if (Matches(part, s)) return s.Id;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>Carried plus what the earlier steps can still make of it.</summary>
|
||||
private static int Available(KitRecipe r, KitPart part, IReadOnlyList<KitStack> pack, int depth)
|
||||
{
|
||||
int have = Count(part, pack);
|
||||
var producer = depth < 8 ? r.Producer(part) : null;
|
||||
return producer == null ? have : have + Makeable(r, producer, pack, depth + 1);
|
||||
}
|
||||
|
||||
/// <summary>How many times a step can go with what the pack holds and makes.</summary>
|
||||
private static int Makeable(KitRecipe r, KitCombine step, IReadOnlyList<KitStack> pack, int depth = 0)
|
||||
=> Math.Min(Available(r, step.Source, pack, depth), Available(r, step.Target, pack, depth));
|
||||
|
||||
/// <summary>Kits the pack makes if every combine works.</summary>
|
||||
public static int CanMake(KitRecipe r, IReadOnlyList<KitStack> pack) => Makeable(r, r.Final, pack);
|
||||
|
||||
// ── Planning ────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>What the pack makes of each recipe, with the chances at this skill and floor.</summary>
|
||||
public static List<KitPlanRow> Plan(IReadOnlyList<KitRecipe> recipes, IReadOnlyList<KitStack> pack,
|
||||
Func<int, KitSkill> skill, int floorPercent)
|
||||
{
|
||||
var rows = new List<KitPlanRow>();
|
||||
foreach (var r in recipes)
|
||||
{
|
||||
var row = new KitPlanRow { Recipe = r, CanMake = CanMake(r, pack) };
|
||||
foreach (var p in r.Ingredients()) row.Parts.Add((p, Count(p, pack)));
|
||||
foreach (var st in r.Steps)
|
||||
{
|
||||
int pct = StepPercent(st, skill);
|
||||
row.Chances.Add(new KitStepChance(st, pct, pct >= 0 && pct < floorPercent));
|
||||
}
|
||||
var next = Next(r, pack, skill, floorPercent);
|
||||
row.Blocked = next.Step == null ? next.Why : string.Empty;
|
||||
rows.Add(row);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The next combine for <paramref name="r"/>: the kit itself when its two parts are carried, else
|
||||
/// the earlier step that makes the missing part. Nothing is combined that the kit can't use (no
|
||||
/// herbs without bandages), and nothing when a step it needs is under the floor, untrained, or
|
||||
/// its chance can't be read with a floor set.
|
||||
/// </summary>
|
||||
public static KitNext Next(KitRecipe r, IReadOnlyList<KitStack> pack, Func<int, KitSkill> skill, int floorPercent)
|
||||
=> Next(r, r.Final, pack, skill, Math.Clamp(floorPercent, 0, 100), 0);
|
||||
|
||||
private static KitNext Next(KitRecipe r, KitCombine step, IReadOnlyList<KitStack> pack, Func<int, KitSkill> skill, int floor, int depth)
|
||||
{
|
||||
if (Makeable(r, step, pack) <= 0)
|
||||
return KitNext.None("out of " + Missing(r, step, pack));
|
||||
|
||||
var s = skill(step.SkillId);
|
||||
string skillName = SkillName(step.SkillId);
|
||||
if (s.Known && !s.Trained)
|
||||
return KitNext.None($"{skillName} isn't trained (the server refuses the combine)");
|
||||
int pct = s.Known ? Percent(s.Buffed, step.Difficulty) : -1;
|
||||
if (pct < 0 && floor > 0)
|
||||
return KitNext.None($"can't read your {skillName} skill to check the {floor}% floor (set Min chance to 0 to go without it)");
|
||||
if (pct >= 0 && pct < floor)
|
||||
return KitNext.None($"{step.Label}: {pct}% at {skillName} {s.Buffed} is under your {floor}% floor");
|
||||
|
||||
int src = FirstStack(step.Source, pack), tgt = FirstStack(step.Target, pack);
|
||||
if (src != 0 && tgt != 0)
|
||||
return new KitNext(step, src, tgt, pct, string.Empty);
|
||||
|
||||
// A part has to be made first.
|
||||
var missing = src == 0 ? step.Source : step.Target;
|
||||
var producer = depth < 8 ? r.Producer(missing) : null;
|
||||
if (producer == null) return KitNext.None("out of " + missing.Name);
|
||||
return Next(r, producer, pack, skill, floor, depth + 1);
|
||||
}
|
||||
|
||||
/// <summary>The first item that runs out for a step (an ingredient you carry, not a part made on the way).</summary>
|
||||
private static string Missing(KitRecipe r, KitCombine step, IReadOnlyList<KitStack> pack, int depth = 0)
|
||||
{
|
||||
foreach (var part in new[] { step.Source, step.Target })
|
||||
{
|
||||
if (Available(r, part, pack, depth) > 0) continue;
|
||||
var producer = depth < 8 ? r.Producer(part) : null;
|
||||
return producer == null ? part.Name : Missing(r, producer, pack, depth + 1);
|
||||
}
|
||||
return step.Source.Name;
|
||||
}
|
||||
|
||||
// ── Text ────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>"Soft Bandages 3, Treated Hyssop 5, ..." (what the pack holds for a row).</summary>
|
||||
public static string PartsText(KitPlanRow row)
|
||||
=> string.Join(", ", row.Parts.Select(p => $"{p.Part.Name} {p.Count}"));
|
||||
|
||||
/// <summary>"Combine the herbs 99%, Pack the kit 95%" ("?" when the skill can't be read).</summary>
|
||||
public static string ChancesText(KitPlanRow row)
|
||||
=> string.Join(", ", row.Chances.Select(c => $"{c.Step.Label} {(c.Percent >= 0 ? c.Percent + "%" : "?")}"));
|
||||
|
||||
/// <summary>One chat line for a row (/ra kits).</summary>
|
||||
public static string Line(KitPlanRow row)
|
||||
{
|
||||
string make = row.CanMake == 1 ? "1 kit" : $"{row.CanMake} kits";
|
||||
string tail = row.Blocked.Length > 0 && row.CanMake > 0 ? $" - can't start: {row.Blocked}" : "";
|
||||
return $"{row.Recipe.Name}: {make} ({PartsText(row)}; chance {ChancesText(row)}){tail}";
|
||||
}
|
||||
|
||||
/// <summary>The run's closing line.</summary>
|
||||
public static string Summary(string kitName, int made, int failed, IReadOnlyDictionary<string, int> lost, string why)
|
||||
{
|
||||
string madeText = made == 1 ? $"made 1 {kitName}" : $"made {made} {kitName}s";
|
||||
string failText = failed == 0 ? "no combine failed"
|
||||
: (failed == 1 ? "1 combine failed" : $"{failed} combines failed")
|
||||
+ (lost.Count > 0 ? " (lost " + string.Join(", ", lost.Select(kv => $"{kv.Value} {kv.Key}")) + ")" : "");
|
||||
return $"{madeText}, {failText}. Stopped: {why}.";
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,475 @@
|
|||
// KitRunner.cs - "Make kits" (the Crafting tab's Kits sub-tab, /ra kits): makes Plentiful Healing
|
||||
// Kits from their ingredients, one combine at a time. KitPlanner picks each combine from a fresh
|
||||
// look at the pack; this does it and waits for the server.
|
||||
//
|
||||
// Pump thread only (the tab's Render reads the volatile snapshots and posts Start/Stop).
|
||||
// Only while the macro is OFF: Start refuses with the macro on, and turning it on stops the run
|
||||
// (the macro's own heals, buffs and fights would race the combines). Each step:
|
||||
// 1. stop checks: the macro turned on, out of peace mode, health dropped (something hit you), or
|
||||
// the character moved from where the run started;
|
||||
// 2. gates: not busy, ActionPacer;
|
||||
// 3. KitPlanner.Next over the pack (the floor: Min chance %, checked ahead from the buffed skill);
|
||||
// 4. arm the engine's one-shot answer for AC's chance prompt (v85: Yes at the floor, else No;
|
||||
// it goes before the Auto-confirm crafting arm) and UseObjectOn(source, target);
|
||||
// 5. wait for the result: the recipe's chat line, the product showing up or the parts going, a
|
||||
// declined prompt, "cannot be used on", or a WeenieError (YoureTooBusy retries).
|
||||
// The server only asks when the character option "show the chance of success dialog" is on;
|
||||
// without it the combine just happens, so the floor is checked here first, every step.
|
||||
// Ends with one plain chat line: made, failed, lost, and why it stopped.
|
||||
//
|
||||
// "Make kits when low" (KitAuto, RynthAiPlugin.Kits.cs) starts runs with StartAuto: the same
|
||||
// combines, only while the macro is ON (it holds the bot meanwhile); the macro turning off stops it,
|
||||
// AC's own craft dialog stops it (nobody is there to click), and each stop says what kind it was
|
||||
// (KitStopKind) so the waits after it follow. Start (the button, /ra kits make) is unchanged.
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.MiniRemote.Crafting;
|
||||
|
||||
internal sealed class KitRunner
|
||||
{
|
||||
private const uint ErrorYoureTooBusy = 0x1D;
|
||||
private const long StepTimeoutMs = 15_000;
|
||||
/// <summary>The player answers AC's own dialog: give them time.</summary>
|
||||
private const long ManualTimeoutMs = 60_000;
|
||||
private const long RetryDelayMs = 1_500;
|
||||
private const long StepGapMs = 600;
|
||||
/// <summary>After the parts went, how long to wait for the product (or the result line) before calling it a failure.</summary>
|
||||
private const long ProductGraceMs = 1_500;
|
||||
private const int MaxRetries = 3;
|
||||
/// <summary>Moving more than this from the start (same cell) stops the run.</summary>
|
||||
public const float MoveTolerance = 1.5f;
|
||||
/// <summary>The plan the tab shows is refreshed this often while the tab is drawn.</summary>
|
||||
private const long PlanRefreshMs = 1_000;
|
||||
private const long ViewedWindowMs = 2_500;
|
||||
|
||||
private readonly MiniRemoteContext _ctx;
|
||||
private readonly IReadOnlyList<KitRecipe> _recipes;
|
||||
|
||||
// Job (pump thread)
|
||||
private KitRecipe? _recipe;
|
||||
private int _limit;
|
||||
private int _made, _failed, _retries;
|
||||
private readonly Dictionary<string, int> _lost = new(StringComparer.Ordinal);
|
||||
private bool _waiting, _manual;
|
||||
private KitCombine? _step;
|
||||
private int _confSeq, _errSeq;
|
||||
private long _stepAt, _nextAt, _partsGoneAt;
|
||||
private int _srcBefore, _tgtBefore, _productBefore;
|
||||
private bool _havePose;
|
||||
private uint _startCell;
|
||||
private float _startX, _startY, _startZ;
|
||||
private uint _startHealth;
|
||||
/// <summary>A "Make kits when low" run (StartAuto); its end goes to <see cref="_autoEnded"/>.</summary>
|
||||
private bool _auto;
|
||||
private Func<KitStopKind, int, string>? _autoEnded;
|
||||
|
||||
// Render snapshots
|
||||
private volatile bool _active;
|
||||
private volatile string _status = "idle";
|
||||
private volatile string _lastSummary = string.Empty;
|
||||
private volatile KitPlanRow[] _plan = Array.Empty<KitPlanRow>();
|
||||
private long _planAt = long.MinValue / 2;
|
||||
private long _viewedAt = long.MinValue / 2;
|
||||
|
||||
public KitRunner(MiniRemoteContext ctx, IReadOnlyList<KitRecipe>? recipes = null)
|
||||
{
|
||||
_ctx = ctx;
|
||||
_recipes = recipes ?? KitPlanner.Retail;
|
||||
}
|
||||
|
||||
public bool Running => _active;
|
||||
public string Status => _status;
|
||||
/// <summary>The last run's closing line ("" before one ends).</summary>
|
||||
public string LastSummary => _lastSummary;
|
||||
/// <summary>What the pack makes (refreshed while the tab is drawn, and by /ra kits).</summary>
|
||||
public KitPlanRow[] Plan => _plan;
|
||||
public IReadOnlyList<KitRecipe> Recipes => _recipes;
|
||||
public KitRecipe? Recipe => _recipe;
|
||||
public int MadeCount => _made;
|
||||
public int FailedCount => _failed;
|
||||
/// <summary>The run going was started by "Make kits when low" (StartAuto).</summary>
|
||||
public bool Auto => _active && _auto;
|
||||
/// <summary>The run's count (0 = as many as the pack makes).</summary>
|
||||
public int Limit => _limit;
|
||||
/// <summary>How the last run ended.</summary>
|
||||
public KitStopKind LastStopKind { get; private set; } = KitStopKind.Other;
|
||||
|
||||
private RynthCoreHost Host => _ctx.Host;
|
||||
private MiniRemoteInventory Inv => _ctx.Inventory;
|
||||
private CraftingTabState C => _ctx.State.Crafting;
|
||||
public int Floor => Math.Clamp(C.KitMinChancePercent, 0, 100);
|
||||
|
||||
/// <summary>The tab was drawn (render thread): keep the plan fresh.</summary>
|
||||
public void MarkViewed(long nowMs) => System.Threading.Volatile.Write(ref _viewedAt, nowMs);
|
||||
|
||||
// ── Pack and skill ──────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The pack's stacks of anything a recipe uses or makes (equipped items left out).</summary>
|
||||
public List<KitStack> Pack()
|
||||
{
|
||||
var wanted = new HashSet<uint>();
|
||||
var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var r in _recipes)
|
||||
foreach (var st in r.Steps)
|
||||
foreach (var p in new[] { st.Source, st.Target, st.Product })
|
||||
{
|
||||
wanted.Add(p.Wcid);
|
||||
names.Add(p.Name);
|
||||
}
|
||||
var list = new List<KitStack>();
|
||||
foreach (var wo in Inv.Items())
|
||||
{
|
||||
string name = wo.Name ?? string.Empty;
|
||||
uint wcid = Inv.Wcid(wo);
|
||||
if (wcid != 0 ? !wanted.Contains(wcid) : !names.Contains(name)) continue;
|
||||
if (Inv.IsEquipped(wo)) continue;
|
||||
list.Add(new KitStack(wo.Id, wcid, name, Inv.StackSize(wo)));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>The player's buffed skill and training (Unknown when the engine can't read it).</summary>
|
||||
public KitSkill Skill(int skillId)
|
||||
{
|
||||
if (!Host.HasGetObjectSkill) return KitSkill.Unknown;
|
||||
if (!Host.TryGetObjectSkill(Inv.PlayerId, unchecked((uint)skillId), out int buffed, out int training)) return KitSkill.Unknown;
|
||||
// The engine reads 0 for a trained skill before the qualities arrive: unknown, not "can't".
|
||||
if (training >= 2 && buffed <= 0) return KitSkill.Unknown;
|
||||
return new KitSkill(true, buffed, training);
|
||||
}
|
||||
|
||||
/// <summary>Re-reads the pack into <see cref="Plan"/> (pump thread).</summary>
|
||||
public KitPlanRow[] RefreshPlan()
|
||||
{
|
||||
var rows = KitPlanner.Plan(_recipes, Pack(), Skill, Floor).ToArray();
|
||||
_plan = rows;
|
||||
_planAt = Environment.TickCount64;
|
||||
return rows;
|
||||
}
|
||||
|
||||
public KitRecipe? Find(string? id)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(id)) return _recipes.FirstOrDefault();
|
||||
string t = id.Trim();
|
||||
return _recipes.FirstOrDefault(r => r.Id.Equals(t, StringComparison.OrdinalIgnoreCase)
|
||||
|| r.Name.Equals(t, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
// ── Job control ─────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Why a run can't start now ("" when it can): the macro is on, not in the world, not in
|
||||
/// peace mode, or the pack makes none.
|
||||
/// </summary>
|
||||
public string CanStart(KitRecipe recipe)
|
||||
{
|
||||
if (Running) return "a kit run is already going (Stop it first)";
|
||||
var s = _ctx.Settings;
|
||||
if (s == null) return "not ready yet (log in first)";
|
||||
if (s.IsMacroRunning) return "turn the macro off first (kits are made only while it is off)";
|
||||
if (Inv.PlayerId == 0) return "not in the world yet";
|
||||
if (!Inv.InPeaceMode) return "go to peace mode first";
|
||||
var next = KitPlanner.Next(recipe, Pack(), Skill, Floor);
|
||||
return next.Step == null ? next.Why : string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>Starts making <paramref name="recipe"/> (limit 0 = as many as the pack makes). Returns "" or why not. Pump thread.</summary>
|
||||
public string Start(KitRecipe recipe, int limit)
|
||||
{
|
||||
string why = CanStart(recipe);
|
||||
if (why.Length > 0) { _status = why; return why; }
|
||||
Begin(recipe, limit, auto: false, ended: null);
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why a "when low" run can't start now ("" when it can): another run is going, the macro is off,
|
||||
/// not in the world, not in peace mode, or the pack makes none at the floor.
|
||||
/// </summary>
|
||||
public string CanStartAuto(KitRecipe recipe)
|
||||
{
|
||||
if (Running) return "a kit run is already going";
|
||||
var s = _ctx.Settings;
|
||||
if (s == null) return "not ready yet (log in first)";
|
||||
if (!s.IsMacroRunning) return "the macro is off";
|
||||
if (Inv.PlayerId == 0) return "not in the world yet";
|
||||
if (!Inv.InPeaceMode) return "not in peace mode";
|
||||
var next = KitPlanner.Next(recipe, Pack(), Skill, Floor);
|
||||
return next.Step == null ? next.Why : string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "Make kits when low": starts a run with the macro on (up to <paramref name="limit"/> kits).
|
||||
/// <paramref name="ended"/> hears how it ended and the kits made, and returns what the summary
|
||||
/// line adds (the next try). Returns "" or why not. Pump thread.
|
||||
/// </summary>
|
||||
public string StartAuto(KitRecipe recipe, int limit, Func<KitStopKind, int, string>? ended)
|
||||
{
|
||||
string why = CanStartAuto(recipe);
|
||||
if (why.Length > 0) return why;
|
||||
Begin(recipe, limit, auto: true, ended: ended);
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
private void Begin(KitRecipe recipe, int limit, bool auto, Func<KitStopKind, int, string>? ended)
|
||||
{
|
||||
_auto = auto;
|
||||
_autoEnded = ended;
|
||||
_recipe = recipe;
|
||||
_limit = Math.Max(0, limit);
|
||||
_made = _failed = _retries = 0;
|
||||
_lineOwedUntil = 0;
|
||||
_lost.Clear();
|
||||
_waiting = false;
|
||||
_nextAt = 0;
|
||||
_havePose = Host.TryGetPlayerPose(out _startCell, out _startX, out _startY, out _startZ, out _, out _, out _, out _);
|
||||
_startHealth = Inv.PlayerHealth().Cur;
|
||||
_active = true;
|
||||
int can = KitPlanner.CanMake(recipe, Pack());
|
||||
int target = _limit > 0 ? Math.Min(_limit, can) : can;
|
||||
_status = $"making {target} {recipe.Name}(s)" + (auto ? " (Make kits when low)" : "");
|
||||
RynthLog.Write(LogCat.Crafting, $"[Kits] start{(auto ? " (when low)" : "")}: {recipe.Name}, up to {target} (pack makes {can}), floor {Floor}%");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ends the run and prints the summary (pump thread). No-op when idle. <paramref name="kind"/>:
|
||||
/// how it ended (the player's Stop unless said), for the "when low" waits.
|
||||
/// </summary>
|
||||
public void Stop(string why, KitStopKind kind = KitStopKind.User)
|
||||
{
|
||||
if (!_active) { _status = why; return; }
|
||||
if (_waiting && Host.HasConfirmationAnswers) Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, 0);
|
||||
_waiting = false;
|
||||
_active = false;
|
||||
LastStopKind = kind;
|
||||
bool auto = _auto;
|
||||
var ended = _autoEnded;
|
||||
_auto = false;
|
||||
_autoEnded = null;
|
||||
string tail = string.Empty;
|
||||
if (auto && ended != null)
|
||||
{
|
||||
try { tail = ended(kind, _made) ?? string.Empty; }
|
||||
catch (Exception ex) { RynthLog.Exception(LogCat.Crafting, ex, "Make kits when low: the end of a run"); }
|
||||
}
|
||||
string name = _recipe?.Name ?? "kit";
|
||||
string line = KitPlanner.Summary(name, _made, _failed, _lost, why) + tail;
|
||||
_lastSummary = line;
|
||||
_status = "idle - " + why;
|
||||
_ctx.Chat((auto ? "[RynthAi] Make kits when low: " : "[RynthAi] Make kits: ") + line);
|
||||
RynthLog.Write(LogCat.Crafting, "[Kits] " + (auto ? "(when low) " : "") + line);
|
||||
RefreshPlan();
|
||||
}
|
||||
|
||||
public void OnLogout()
|
||||
{
|
||||
Stop("logged out", KitStopKind.Other);
|
||||
_plan = Array.Empty<KitPlanRow>();
|
||||
_status = "idle";
|
||||
}
|
||||
|
||||
// ── Tick (pump thread) ──────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The last tick's clock (the result handlers time the next step from it).</summary>
|
||||
private long _now;
|
||||
|
||||
public void Tick(long nowMs)
|
||||
{
|
||||
_now = nowMs;
|
||||
if (!Running)
|
||||
{
|
||||
long viewed = System.Threading.Volatile.Read(ref _viewedAt);
|
||||
if (nowMs - viewed < ViewedWindowMs && nowMs - _planAt >= PlanRefreshMs) RefreshPlan();
|
||||
return;
|
||||
}
|
||||
|
||||
var (stop, stopKind) = StopReason();
|
||||
if (stop.Length > 0) { Stop(stop, stopKind); return; }
|
||||
|
||||
if (_waiting) { Wait(nowMs); return; }
|
||||
if (nowMs < _nextAt) return;
|
||||
if (Inv.IsBusy) return;
|
||||
if (!ActionPacer.MayStart(Host, "Kits", HealNeed.None, out string pace)) { _status = "waiting: " + pace; return; }
|
||||
|
||||
var recipe = _recipe!;
|
||||
if (_limit > 0 && _made >= _limit) { Stop($"made the {_limit} asked for", KitStopKind.Finished); return; }
|
||||
|
||||
var pack = Pack();
|
||||
var next = KitPlanner.Next(recipe, pack, Skill, Floor);
|
||||
if (next.Step == null) { Stop(next.Why, KitStopKind.Finished); return; }
|
||||
var step = next.Step;
|
||||
|
||||
int floor = Floor;
|
||||
_manual = !(Host.HasConfirmationAnswers
|
||||
&& Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, floor, (int)StepTimeoutMs) == 1);
|
||||
_confSeq = Host.TryGetLastConfirmation(out int cs, out _, out _, out _, out _) ? cs : 0;
|
||||
_errSeq = Host.TryGetLastWeenieError(out int es, out _, out _, out _) ? es : 0;
|
||||
_srcBefore = KitPlanner.Count(step.Source, pack);
|
||||
_tgtBefore = KitPlanner.Count(step.Target, pack);
|
||||
_productBefore = KitPlanner.Count(step.Product, pack);
|
||||
|
||||
string pct = next.Percent >= 0 ? $" ~{next.Percent}%" : "";
|
||||
if (!Host.UseOnFor(unchecked((uint)next.SourceId), unchecked((uint)next.TargetId), "Kits",
|
||||
$"{step.Label}: {step.Source.Name} on {step.Target.Name}{pct}" + (_auto ? " (Make kits when low)" : ""),
|
||||
_auto ? UseKind.Auto : UseKind.Asked))
|
||||
{
|
||||
if (!_manual) Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, 0);
|
||||
Retry(nowMs, "the use request didn't go out");
|
||||
return;
|
||||
}
|
||||
_step = step;
|
||||
_waiting = true;
|
||||
_stepAt = nowMs;
|
||||
_partsGoneAt = 0;
|
||||
string ask = _manual && !_auto ? " - click Yes if AC asks" : "";
|
||||
_status = $"{step.Label}{pct} ({_made} made){ask}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why the run must stop now ("" to go on), and what kind of stop: the macro (on for a run by
|
||||
/// hand, off for a "when low" one), combat mode, damage, moving.
|
||||
/// </summary>
|
||||
private (string Why, KitStopKind Kind) StopReason()
|
||||
{
|
||||
var s = _ctx.Settings;
|
||||
if (s == null) return ("settings went away", KitStopKind.Other);
|
||||
if (_auto)
|
||||
{
|
||||
if (!s.IsMacroRunning) return ("the macro turned off", KitStopKind.MacroOff);
|
||||
}
|
||||
else if (s.IsMacroRunning) return ("the macro turned on", KitStopKind.Other);
|
||||
if (!Inv.InPeaceMode) return ("you left peace mode", KitStopKind.Danger);
|
||||
uint hp = Inv.PlayerHealth().Cur;
|
||||
if (_startHealth > 0 && hp > 0 && hp < _startHealth) return ("you took damage", KitStopKind.Danger);
|
||||
if (hp > _startHealth) _startHealth = hp; // healed up: the new level is the line
|
||||
if (_havePose && Host.TryGetPlayerPose(out uint cell, out float x, out float y, out float z, out _, out _, out _, out _))
|
||||
{
|
||||
float dx = x - _startX, dy = y - _startY, dz = z - _startZ;
|
||||
if (cell != _startCell || dx * dx + dy * dy + dz * dz > MoveTolerance * MoveTolerance) return ("you moved", KitStopKind.Danger);
|
||||
}
|
||||
return (string.Empty, KitStopKind.Other);
|
||||
}
|
||||
|
||||
private void Retry(long nowMs, string why)
|
||||
{
|
||||
_waiting = false;
|
||||
if (++_retries > MaxRetries) { Stop("gave up: " + why, KitStopKind.Refused); return; }
|
||||
_nextAt = nowMs + RetryDelayMs;
|
||||
_status = $"{why} - retrying ({_retries}/{MaxRetries})";
|
||||
}
|
||||
|
||||
/// <summary>A result the counts showed before its chat line: that line, when it comes, is the old step's.</summary>
|
||||
private const long LineOwedMs = 3_000;
|
||||
private long _lineOwedUntil;
|
||||
|
||||
private void Succeeded(bool byLine)
|
||||
{
|
||||
var step = _step!;
|
||||
_lineOwedUntil = byLine ? 0 : _now + LineOwedMs;
|
||||
_waiting = false;
|
||||
_retries = 0;
|
||||
_nextAt = _now + StepGapMs;
|
||||
bool kit = ReferenceEquals(step, _recipe!.Final);
|
||||
if (kit) _made++;
|
||||
_status = kit ? $"made {_made} {_recipe.Name}(s)" : $"{step.Product.Name} made";
|
||||
RynthLog.Write(LogCat.Crafting, $"[Kits] {step.Label}: ok ({_made} made)");
|
||||
}
|
||||
|
||||
private void Failed(bool byLine)
|
||||
{
|
||||
var step = _step!;
|
||||
_lineOwedUntil = byLine ? 0 : _now + LineOwedMs;
|
||||
_waiting = false;
|
||||
_retries = 0;
|
||||
_nextAt = _now + StepGapMs;
|
||||
_failed++;
|
||||
foreach (var p in new[] { step.Source, step.Target })
|
||||
_lost[p.Name] = (_lost.TryGetValue(p.Name, out int n) ? n : 0) + 1;
|
||||
_status = $"{step.Label} failed ({_failed} failed so far)";
|
||||
RynthLog.Write(LogCat.Crafting, $"[Kits] {step.Label}: failed, lost 1 {step.Source.Name} + 1 {step.Target.Name}");
|
||||
}
|
||||
|
||||
private void Wait(long nowMs)
|
||||
{
|
||||
var step = _step!;
|
||||
// Engine answer: a No (the server's own percent under the floor) uses nothing.
|
||||
if (Host.TryGetLastConfirmation(out int seq, out uint type, out int pct, out int outcome, out _)
|
||||
&& seq != _confSeq && type == RynthCoreHost.ConfirmationKind.CraftInteraction)
|
||||
{
|
||||
_confSeq = seq;
|
||||
if (outcome == RynthCoreHost.ConfirmationOutcome.Declined)
|
||||
{
|
||||
_waiting = false;
|
||||
Stop($"the server's chance for {step.Label} is {pct}%, under your {Floor}% floor", KitStopKind.Refused);
|
||||
return;
|
||||
}
|
||||
if (outcome is RynthCoreHost.ConfirmationOutcome.Shown or RynthCoreHost.ConfirmationOutcome.SendFailed)
|
||||
{
|
||||
if (_auto)
|
||||
{
|
||||
// Nobody is there to click it: a "when low" run never waits on AC's dialog.
|
||||
_waiting = false;
|
||||
Stop("AC's craft dialog came up and needs a click (Yes makes this one)", KitStopKind.Refused);
|
||||
return;
|
||||
}
|
||||
_manual = true;
|
||||
_status = $"click Yes in AC's craft dialog ({(pct >= 0 ? pct + "%" : "chance not shown")})";
|
||||
}
|
||||
}
|
||||
|
||||
if (Host.TryGetLastWeenieError(out int es, out uint error, out _, out _) && es != _errSeq)
|
||||
{
|
||||
_errSeq = es;
|
||||
if (error == ErrorYoureTooBusy) { Retry(nowMs, "server says busy"); return; }
|
||||
_waiting = false;
|
||||
Stop($"the server refused {step.Label} (error 0x{error:X})", KitStopKind.Refused);
|
||||
return;
|
||||
}
|
||||
|
||||
// Counts: the product showing up is a success; both parts going without it is a failure.
|
||||
var pack = Pack();
|
||||
if (KitPlanner.Count(step.Product, pack) > _productBefore) { Succeeded(byLine: false); return; }
|
||||
bool partsGone = KitPlanner.Count(step.Source, pack) < _srcBefore && KitPlanner.Count(step.Target, pack) < _tgtBefore;
|
||||
if (partsGone)
|
||||
{
|
||||
if (_partsGoneAt == 0) _partsGoneAt = nowMs;
|
||||
else if (nowMs - _partsGoneAt >= ProductGraceMs) { Failed(byLine: false); return; }
|
||||
}
|
||||
|
||||
// A "when low" run has no one to answer AC's dialog: the plain timeout, then retries.
|
||||
bool waitForPlayer = _manual && !_auto;
|
||||
if (nowMs - _stepAt > (waitForPlayer ? ManualTimeoutMs : StepTimeoutMs))
|
||||
{
|
||||
if (waitForPlayer) { _waiting = false; Stop("no answer to AC's craft dialog", KitStopKind.Refused); }
|
||||
else Retry(nowMs, "no result from the server");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The recipe's result lines and "cannot be used on" (never hidden).</summary>
|
||||
public void OnChat(string text)
|
||||
{
|
||||
if (!_active || string.IsNullOrEmpty(text)) return;
|
||||
string t = text.Trim();
|
||||
if (_lineOwedUntil != 0 && IsResultLine(t))
|
||||
{
|
||||
bool owed = _now < _lineOwedUntil;
|
||||
_lineOwedUntil = 0;
|
||||
if (owed) return; // the step the counts already finished
|
||||
}
|
||||
if (!_waiting || _step == null) return;
|
||||
if (t.Equals(_step.SuccessText, StringComparison.Ordinal)) { Succeeded(byLine: true); return; }
|
||||
if (t.Equals(_step.FailText, StringComparison.Ordinal)) { Failed(byLine: true); return; }
|
||||
if (t.StartsWith("The ", StringComparison.Ordinal) && t.Contains(" cannot be used on the ", StringComparison.Ordinal))
|
||||
{
|
||||
_waiting = false;
|
||||
Stop($"this server has no such recipe ({_step.Source.Name} on {_step.Target.Name})", KitStopKind.Refused);
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsResultLine(string t)
|
||||
=> _recipe != null && _recipe.Steps.Any(st => t.Equals(st.SuccessText, StringComparison.Ordinal) || t.Equals(st.FailText, StringComparison.Ordinal));
|
||||
}
|
||||
|
|
@ -12,6 +12,10 @@
|
|||
// One TinkerRunner works one tab's scan at a time.
|
||||
// Above the benches: "Auto-confirm crafting" (CraftAutoConfirm), Yes to the server's chance prompt
|
||||
// at the chosen percent for crafts the player starts by hand.
|
||||
// The Kits sub-tab: "Make kits" (KitRunner / KitPlanner) makes Plentiful Healing Kits from their
|
||||
// ingredients, one combine at a time, only while the macro is off (also /ra kits). Under it,
|
||||
// "Make kits when low" (KitAuto; the macro side is RynthAiPlugin.Kits.cs) does the same by itself
|
||||
// while the macro runs, when the kits carried fall under the line and nothing is around.
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
|
@ -31,6 +35,17 @@ internal sealed class CraftingTab
|
|||
/// <summary>Auto-confirm crafting (the sticky engine answer for hand-made crafts).</summary>
|
||||
public CraftAutoConfirm AutoConfirm { get; }
|
||||
|
||||
/// <summary>Make kits (the Kits sub-tab, /ra kits).</summary>
|
||||
public KitRunner Kits { get; }
|
||||
|
||||
/// <summary>Make kits when low: when a run may start with the macro on, and the waits (ticked by RynthAiPlugin.Kits.cs).</summary>
|
||||
public KitAuto AutoKits { get; }
|
||||
|
||||
/// <summary>A command asked for the Kits sub-tab (the next frame selects it).</summary>
|
||||
private volatile bool _selectKits;
|
||||
public void SelectKitsTab() => _selectKits = true;
|
||||
private static readonly byte[] KitsTabLabel = System.Text.Encoding.UTF8.GetBytes("Kits\0");
|
||||
|
||||
// Custom-row editor (render thread only)
|
||||
private int _newMaterial = TinkerCatalog.Steel;
|
||||
private int _newKind;
|
||||
|
|
@ -45,6 +60,8 @@ internal sealed class CraftingTab
|
|||
_ctx = ctx;
|
||||
Runner = new TinkerRunner(ctx, RowsFor, SettingsFor);
|
||||
AutoConfirm = new CraftAutoConfirm(() => ctx.Host, () => ctx.Settings, ctx.Chat);
|
||||
Kits = new KitRunner(ctx);
|
||||
AutoKits = new KitAuto { Say = ctx.Chat };
|
||||
}
|
||||
|
||||
private CraftingTabState C => _ctx.State.Crafting;
|
||||
|
|
@ -88,13 +105,20 @@ internal sealed class CraftingTab
|
|||
{
|
||||
Runner.Tick(nowMs);
|
||||
AutoConfirm.Tick(nowMs);
|
||||
Kits.Tick(nowMs);
|
||||
}
|
||||
|
||||
public void OnChat(string text) => Runner.OnChat(text);
|
||||
public void OnChat(string text)
|
||||
{
|
||||
Runner.OnChat(text);
|
||||
Kits.OnChat(text);
|
||||
}
|
||||
|
||||
public void OnLogout()
|
||||
{
|
||||
Runner.OnLogout();
|
||||
Kits.OnLogout();
|
||||
AutoKits.Reset();
|
||||
AutoConfirm.Release();
|
||||
}
|
||||
|
||||
|
|
@ -119,9 +143,185 @@ internal sealed class CraftingTab
|
|||
if (ImGui.BeginTabItem("Jewelry")) { RenderBench(TinkerBench.Jewelry); ImGui.EndTabItem(); }
|
||||
if (ImGui.BeginTabItem("Trinkets")) { RenderBench(TinkerBench.Trinkets); ImGui.EndTabItem(); }
|
||||
if (ImGui.BeginTabItem("Items")) { RenderBench(TinkerBench.Items); ImGui.EndTabItem(); }
|
||||
bool selectKits = _selectKits;
|
||||
_selectKits = false;
|
||||
if (BeginTab(KitsTabLabel, selectKits ? ImGuiTabItemFlags.SetSelected : ImGuiTabItemFlags.None)) { RenderKits(); ImGui.EndTabItem(); }
|
||||
ImGui.EndTabBar();
|
||||
}
|
||||
|
||||
/// <summary>BeginTabItem with flags and no close button (ImGui.NET only wraps flags with p_open).</summary>
|
||||
private static unsafe bool BeginTab(byte[] labelUtf8Z, ImGuiTabItemFlags flags)
|
||||
{
|
||||
fixed (byte* label = labelUtf8Z)
|
||||
return ImGuiNative.igBeginTabItem(label, null, flags) != 0;
|
||||
}
|
||||
|
||||
// ── Kits (render thread) ────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The Kits sub-tab: what the pack makes, the floor and count, Make kits / Stop.</summary>
|
||||
private void RenderKits()
|
||||
{
|
||||
var k = Kits;
|
||||
k.MarkViewed(MiniRemoteContext.NowMs);
|
||||
SafeImGui.TextWrapped("Makes kits from their ingredients, one combine at a time, waiting for each result. "
|
||||
+ "Every combine uses your Healing skill and can fail: a failure destroys one of each item. "
|
||||
+ "Runs only while the macro is off, and stops if you move, leave peace mode or take damage.");
|
||||
ImGui.Spacing();
|
||||
|
||||
int floor = Math.Clamp(C.KitMinChancePercent, 0, 100);
|
||||
ImGui.SetNextItemWidth(90);
|
||||
if (ImGui.InputInt("Min chance %##kitfloor", ref floor, 5))
|
||||
{
|
||||
int value = Math.Clamp(floor, 0, 100);
|
||||
_ctx.Post(() => C.KitMinChancePercent = value);
|
||||
}
|
||||
if (ImGui.IsItemHovered())
|
||||
SafeImGui.SetTooltip("Never try a combine whose chance is under this (0 = any chance).\n"
|
||||
+ "Worked out from your buffed Healing skill before every combine; when AC asks,\n"
|
||||
+ "RynthAi also says No to a lower server percent. Also /ra kits floor <0-100>.");
|
||||
ImGui.SameLine();
|
||||
int count = Math.Max(0, C.KitMakeCount);
|
||||
ImGui.SetNextItemWidth(90);
|
||||
if (ImGui.InputInt("Kits to make##kitcount", ref count, 1))
|
||||
{
|
||||
int value = Math.Clamp(count, 0, 1000);
|
||||
_ctx.Post(() => C.KitMakeCount = value);
|
||||
}
|
||||
if (ImGui.IsItemHovered()) ImGui.SetTooltip("How many kits one run makes (0 = as many as the pack makes).");
|
||||
|
||||
var plan = k.Plan;
|
||||
if (plan.Length == 0)
|
||||
{
|
||||
SafeImGui.TextDisabled("Reading your pack...");
|
||||
}
|
||||
else if (ImGui.BeginTable("##kits", 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.Borders | ImGuiTableFlags.SizingStretchProp))
|
||||
{
|
||||
ImGui.TableSetupColumn("Kit", ImGuiTableColumnFlags.WidthFixed, 150);
|
||||
ImGui.TableSetupColumn("Can make", ImGuiTableColumnFlags.WidthFixed, 65);
|
||||
ImGui.TableSetupColumn("In your pack");
|
||||
ImGui.TableSetupColumn("Chance");
|
||||
ImGui.TableSetupColumn("", ImGuiTableColumnFlags.WidthFixed, 80);
|
||||
ImGui.TableHeadersRow();
|
||||
bool macroOn = _ctx.Settings?.IsMacroRunning == true;
|
||||
foreach (var row in plan)
|
||||
{
|
||||
ImGui.PushID(row.Recipe.Id);
|
||||
ImGui.TableNextRow();
|
||||
ImGui.TableNextColumn();
|
||||
ImGui.TextUnformatted(row.Recipe.Name);
|
||||
ImGui.TableNextColumn();
|
||||
ImGui.TextUnformatted(row.CanMake.ToString());
|
||||
ImGui.TableNextColumn();
|
||||
SafeImGui.TextWrapped(KitPlanner.PartsText(row));
|
||||
ImGui.TableNextColumn();
|
||||
foreach (var c in row.Chances)
|
||||
{
|
||||
string text = $"{c.Step.Label}: {(c.Percent >= 0 ? c.Percent + "%" : "?")}";
|
||||
if (c.UnderFloor) SafeImGui.TextColored(LegacyDashboardRenderer.ColAmber, text + " (under the floor)");
|
||||
else SafeImGui.TextDisabled(text);
|
||||
}
|
||||
ImGui.TableNextColumn();
|
||||
string why = macroOn ? "Turn the macro off first: kits are made only while it is off."
|
||||
: k.Running ? "A kit run is going."
|
||||
: row.Blocked;
|
||||
ImGui.BeginDisabled(why.Length > 0);
|
||||
if (ImGui.SmallButton("Make kits"))
|
||||
{
|
||||
var recipe = row.Recipe;
|
||||
int ask = Math.Max(0, C.KitMakeCount);
|
||||
int n = ask > 0 ? Math.Min(ask, row.CanMake) : row.CanMake;
|
||||
int fl = Math.Clamp(C.KitMinChancePercent, 0, 100);
|
||||
_ctx.Confirm("Make kits",
|
||||
$"Make up to {n} {recipe.Name}(s)?\n\nChance: {KitPlanner.ChancesText(row)} (floor {fl}%).\n"
|
||||
+ "A failed combine destroys one of each item it used.\n"
|
||||
+ "It stops if you move, leave peace mode, take damage or turn the macro on.",
|
||||
() =>
|
||||
{
|
||||
string refused = Kits.Start(recipe, ask);
|
||||
if (refused.Length > 0) _ctx.Chat("[RynthAi] Make kits: can't start - " + refused + ".");
|
||||
}, "Make kits");
|
||||
}
|
||||
ImGui.EndDisabled();
|
||||
if (why.Length > 0 && ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) SafeImGui.SetTooltip(why);
|
||||
ImGui.PopID();
|
||||
}
|
||||
ImGui.EndTable();
|
||||
}
|
||||
|
||||
ImGui.BeginDisabled(!k.Running);
|
||||
if (ImGui.Button("Stop##kitstop")) _ctx.Post(() => Kits.Stop("stopped by you"));
|
||||
ImGui.EndDisabled();
|
||||
ImGui.SameLine();
|
||||
SafeImGui.TextDisabled(k.Status);
|
||||
if (k.LastSummary.Length > 0) SafeImGui.TextWrapped("Last run: " + k.LastSummary);
|
||||
RenderAutoKits();
|
||||
SafeImGui.TextDisabled("Ingredients: Soft Bandages, Treated Hyssop and Treated Mandrake (Healing must be trained). Also /ra kits.");
|
||||
}
|
||||
|
||||
/// <summary>Make kits when low: the checkbox, the two numbers and what it is doing.</summary>
|
||||
private void RenderAutoKits()
|
||||
{
|
||||
var settings = _ctx.Settings;
|
||||
if (settings == null) return;
|
||||
ImGui.Separator();
|
||||
bool on = settings.MakeKitsWhenLow;
|
||||
if (ImGui.Checkbox("Make kits when low##kitauto", ref on))
|
||||
{
|
||||
bool value = on;
|
||||
_ctx.Post(() =>
|
||||
{
|
||||
settings.MakeKitsWhenLow = value;
|
||||
if (value) AutoKits.LookNow();
|
||||
else
|
||||
{
|
||||
if (Kits.Auto) Kits.Stop("Make kits when low turned off", KitStopKind.Other);
|
||||
AutoKits.Off();
|
||||
}
|
||||
_ctx.SaveCombatSettings?.Invoke();
|
||||
});
|
||||
}
|
||||
if (ImGui.IsItemHovered())
|
||||
SafeImGui.SetTooltip("While the macro runs: when you carry fewer Plentiful Healing Kits than the first number,\n"
|
||||
+ "make up to the second number from your pack, at the Min chance % above.\n"
|
||||
+ $"Only when nothing is around: no monster within {KitAuto.DefaultRadiusYd:0} yd (or your Monster Range, if bigger),\n"
|
||||
+ $"no hit for {KitAuto.HurtQuietMs / 1000} s, no healing, buffing, looting or fight. The macro waits meanwhile;\n"
|
||||
+ "a monster, a hit, a heal or moving stops it at once. Also /ra kits auto on|off.");
|
||||
ImGui.SameLine();
|
||||
ImGui.AlignTextToFramePadding();
|
||||
ImGui.TextUnformatted("when fewer than");
|
||||
ImGui.SameLine();
|
||||
int below = Math.Clamp(settings.MakeKitsBelow, 1, KitAuto.MaxBelow);
|
||||
ImGui.SetNextItemWidth(80);
|
||||
if (ImGui.InputInt("##kitbelow", ref below, 1))
|
||||
{
|
||||
int value = Math.Clamp(below, 1, KitAuto.MaxBelow);
|
||||
_ctx.Post(() => { settings.MakeKitsBelow = value; _ctx.SaveCombatSettings?.Invoke(); });
|
||||
}
|
||||
if (ImGui.IsItemHovered()) ImGui.SetTooltip($"A run starts when you carry fewer kits than this (1-{KitAuto.MaxBelow}). Also /ra kits auto below N.");
|
||||
ImGui.SameLine();
|
||||
ImGui.TextUnformatted("kits, make up to");
|
||||
ImGui.SameLine();
|
||||
int upTo = Math.Clamp(settings.MakeKitsUpTo, 1, KitAuto.MaxUpTo);
|
||||
ImGui.SetNextItemWidth(80);
|
||||
if (ImGui.InputInt("##kitupto", ref upTo, 1))
|
||||
{
|
||||
int value = Math.Clamp(upTo, 1, KitAuto.MaxUpTo);
|
||||
_ctx.Post(() => { settings.MakeKitsUpTo = value; _ctx.SaveCombatSettings?.Invoke(); });
|
||||
}
|
||||
if (ImGui.IsItemHovered()) ImGui.SetTooltip($"The most kits one run makes (1-{KitAuto.MaxUpTo}); fewer when the pack runs out. Also /ra kits auto upto M.");
|
||||
if (!settings.MakeKitsWhenLow) SafeImGui.TextDisabled("Make kits when low is off.");
|
||||
else SafeImGui.TextDisabled("Make kits when low: " + AutoStatusText(settings));
|
||||
}
|
||||
|
||||
/// <summary>What Make kits when low is doing ("running 2/5", "waiting: monster 22 yd away; next check in 4 s", ...).</summary>
|
||||
public string AutoStatusText(LegacyUiSettings settings)
|
||||
{
|
||||
if (!settings.MakeKitsWhenLow) return "off";
|
||||
if (Kits.Auto) return $"running {Kits.MadeCount}/{Math.Max(1, Kits.Limit)}";
|
||||
if (!settings.IsMacroRunning) return "waiting: the macro is off";
|
||||
return AutoKits.Status;
|
||||
}
|
||||
|
||||
/// <summary>Auto-confirm crafting: the checkbox, the percent and what it has done.</summary>
|
||||
private void RenderAutoConfirm()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -95,6 +95,8 @@ internal sealed class MiniRemoteContext
|
|||
EngineServerState? st = _server.State;
|
||||
string name = st != null && st.HasActive ? st.ActiveName : string.Empty;
|
||||
_serverView = new ServerView(name, ServerSalvageView.ParseList(_server.ProfileJson), ServerTrinketRule.Parse(_server.ProfileJson));
|
||||
// The server's own summon items that hold other summons (the combat summoner and the Pets tab).
|
||||
PetElements.ServerSummons = ServerSummonView.ParseList(_server.ProfileJson);
|
||||
}
|
||||
|
||||
/// <summary>Logout: forget the server; the next login polls fresh.</summary>
|
||||
|
|
@ -103,6 +105,7 @@ internal sealed class MiniRemoteContext
|
|||
_server.Clear();
|
||||
_serverRevision = -1;
|
||||
_serverView = ServerView.None;
|
||||
PetElements.ServerSummons = Array.Empty<ServerSummonView>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
|
|||
|
|
@ -48,6 +48,10 @@ public sealed class CraftingTabState
|
|||
public int TrinketTier;
|
||||
/// <summary>Prepare a raw bag on the tier's Ammunition when no prepared bag is carried.</summary>
|
||||
public bool TrinketPrep;
|
||||
/// <summary>Kits sub-tab ("Make kits"): never try a combine whose chance is under this percent (0 = any).</summary>
|
||||
public int KitMinChancePercent = Crafting.KitPlanner.DefaultFloorPercent;
|
||||
/// <summary>Kits sub-tab: how many kits one run makes (0 = as many as the pack makes).</summary>
|
||||
public int KitMakeCount;
|
||||
// "RingRuns" (the Rings chain, now left to RynthILT) may still be in older files: it is ignored.
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -120,6 +120,7 @@ internal sealed class PetsTab
|
|||
if (w is >= 78780001 and <= 78780012) return false; // capture devices
|
||||
if (w is >= 787802001 and <= 787802072) return false; // summoned combat pet creatures
|
||||
if (w is >= 787801001 and <= 787801072) return true; // combat essence block
|
||||
if (PetElements.IsHolder(_ctx.Host, unchecked((uint)wo.Id), wo.Name)) return true; // a server's holder of summons
|
||||
|
||||
if (HasSummonGemUnderlay(wo)) return true;
|
||||
if (RequiresSummoning(wo)) return true;
|
||||
|
|
@ -661,6 +662,7 @@ internal sealed class PetsTab
|
|||
}
|
||||
|
||||
var s = PetStatsReader.Read(_ctx.Host, _ctx.Inventory, wo, unixNow);
|
||||
ShowElements(s, wo);
|
||||
s.Kind = kind.Value;
|
||||
s.KindAssigned = assigned;
|
||||
int pri = rules.FindIndex(r => r.Id == wo.Id || r.Name.Equals(wo.Name, StringComparison.OrdinalIgnoreCase));
|
||||
|
|
@ -680,6 +682,21 @@ internal sealed class PetsTab
|
|||
_pets = rows.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The row's element(s) when the server sent no damage type: "Fire", or "Fire+Cold" for a holder
|
||||
/// of two summons (PetElements), with "holds 1 of 2" for one that can't summon yet.
|
||||
/// </summary>
|
||||
private void ShowElements(PetStats s, WorldObject wo)
|
||||
{
|
||||
var info = PetElements.Describe(_ctx.Host, unchecked((uint)wo.Id), wo.Name);
|
||||
string text = s.DamageType.Length > 0 ? s.DamageType : info.ElementText;
|
||||
if (info.IsHolder && !info.Ready)
|
||||
text = (text.Length > 0 ? text + ", " : "") + $"holds {info.Held.Count} of {info.Slots}";
|
||||
if (text == s.DamageType) return;
|
||||
s.DamageType = text;
|
||||
PetStatsReader.FormatLines(s);
|
||||
}
|
||||
|
||||
// ── UI (render thread) ──────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Set from any thread: the sub-tab the next frame opens ("/ra hub open breeding"); null = none.</summary>
|
||||
|
|
@ -840,6 +857,16 @@ internal sealed class PetsTab
|
|||
if (ImGui.InputInt("Min monsters", ref minMobs)) _ctx.Post(() => { settings.PetMinMonsters = Math.Max(1, minMobs); _ctx.SaveCombatSettings?.Invoke(); });
|
||||
bool refill = settings.PetAutoRefill;
|
||||
if (ImGui.Checkbox("Refill empty essences with Encapsulated Spirit", ref refill)) _ctx.Post(() => { settings.PetAutoRefill = refill; _ctx.SaveCombatSettings?.Invoke(); });
|
||||
ImGui.TextUnformatted("Pet element");
|
||||
ImGui.SameLine();
|
||||
ImGui.SetNextItemWidth(110);
|
||||
int petElem = PetChoice.SettingIndex(settings.PetElement);
|
||||
if (ImGui.Combo("##petelement", ref petElem, PetChoice.SettingChoices, PetChoice.SettingChoices.Length))
|
||||
{
|
||||
string chosen = PetChoice.SettingValue(petElem);
|
||||
_ctx.Post(() => { settings.PetElement = chosen; _ctx.SaveCombatSettings?.Invoke(); });
|
||||
}
|
||||
if (ImGui.IsItemHovered()) ImGui.SetTooltip(PetChoice.SettingTooltip);
|
||||
ImGui.TextDisabled("Tick pets to add them to the summon list; with Sort = Priority the arrows set the order.");
|
||||
break;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -50,6 +50,43 @@ internal sealed class NavBreadcrumbTracker
|
|||
private int _recAdded, _recSinceSave;
|
||||
private (string Name, int Cls, double NS, double EW, double NavZ, long At)? _portalCandidate;
|
||||
|
||||
// ── A jump step added while recording (/ra nav addjump) ──
|
||||
/// <summary>After a jump step, no point is recorded for at least this long (you are in the air).</summary>
|
||||
internal const long JumpHoldMinMs = 1200;
|
||||
/// <summary>Nor until your height has held still this long (landed), or this much time has gone by.</summary>
|
||||
internal const long JumpLandStillMs = 500, JumpHoldMaxMs = 6000;
|
||||
/// <summary>Height change per tick under this is "still", metres.</summary>
|
||||
internal const float JumpLandStillM = 0.05f;
|
||||
private long _jumpAt = -1, _jumpStillSince;
|
||||
private float _jumpLastZ;
|
||||
|
||||
/// <summary>
|
||||
/// A Jump step went onto the route here (tick thread, from /ra nav addjump): the recording holds its next
|
||||
/// point until you have jumped and landed, so no point is laid in the air or on the edge you jumped from.
|
||||
/// </summary>
|
||||
public void JumpAdded()
|
||||
{
|
||||
_jumpAt = Environment.TickCount64;
|
||||
_jumpStillSince = 0;
|
||||
_jumpLastZ = float.NaN;
|
||||
}
|
||||
|
||||
/// <summary>True while a jump just added holds the recording (see <see cref="JumpAdded"/>).</summary>
|
||||
internal bool HoldingForJump(float z, long now)
|
||||
{
|
||||
if (_jumpAt < 0) return false;
|
||||
long since = now - _jumpAt;
|
||||
bool still = !float.IsNaN(_jumpLastZ) && Math.Abs(z - _jumpLastZ) < JumpLandStillM;
|
||||
_jumpLastZ = z;
|
||||
if (!still) _jumpStillSince = 0;
|
||||
else if (_jumpStillSince == 0) _jumpStillSince = now;
|
||||
bool landed = since >= JumpHoldMinMs && _jumpStillSince != 0 && now - _jumpStillSince >= JumpLandStillMs;
|
||||
if (!landed && since < JumpHoldMaxMs) return true;
|
||||
_jumpAt = -1;
|
||||
_recNS = double.NaN; // the landing spot is recorded straight away
|
||||
return false;
|
||||
}
|
||||
|
||||
public NavBreadcrumbTracker(RynthCoreHost host, LegacyUiSettings settings,
|
||||
Func<uint, (string Name, int ObjectClass)?> describePortal, Action<string> chat)
|
||||
{
|
||||
|
|
@ -224,6 +261,8 @@ internal sealed class NavBreadcrumbTracker
|
|||
_recNS = double.NaN;
|
||||
}
|
||||
|
||||
if (HoldingForJump(z, Environment.TickCount64)) return;
|
||||
|
||||
if (!double.IsNaN(_recNS) && NavRouteEditing.DistanceYards(_recNS, _recEW, ns, ew) < o.RecordSpacingYards)
|
||||
return;
|
||||
|
||||
|
|
|
|||
|
|
@ -42,6 +42,12 @@ internal sealed class NavRecoveryPlan
|
|||
public string Planner = string.Empty;
|
||||
/// <summary>Doorways (dungeon portals) the path goes through.</summary>
|
||||
public int Doorways;
|
||||
/// <summary>The points are RynthNav navmesh corners: the engine turns a corner early only where the
|
||||
/// navmesh shows a straight walk to the next one (NavigationEngine's corner gate).</summary>
|
||||
public bool NavmeshCorners;
|
||||
/// <summary>The route waypoint stands inside something placed (a statue's middle): the last point is the nearest
|
||||
/// spot clear of it, and reaching that reaches the waypoint (nobody gets nearer).</summary>
|
||||
public bool TargetMoved;
|
||||
}
|
||||
|
||||
/// <summary>Result of <see cref="NavRecoveryPlanner.CheckArea"/>.</summary>
|
||||
|
|
@ -76,6 +82,8 @@ internal sealed class NavRecoveryPlanner : INavRecoveryPlanner
|
|||
// when it is this close to one of its cells.
|
||||
internal const double AreaCellReachYd = 60.0;
|
||||
private const int MaxNavmeshCorners = 128;
|
||||
// A partial navmesh way must end at least this far from the character to be worth walking.
|
||||
private const double PartialMinGainYd = 2.0;
|
||||
|
||||
private readonly RynthCoreHost _host;
|
||||
private readonly Func<MainLogic?> _raycast;
|
||||
|
|
@ -181,7 +189,18 @@ internal sealed class NavRecoveryPlanner : INavRecoveryPlanner
|
|||
applicable = true;
|
||||
uint start = graph.ContainsKey(playerCell) ? playerCell : DungeonPathfinder.NearestCell(graph, pNs, pEw, pz);
|
||||
if (start == 0) { why = "can't place you on the dungeon map"; return null; }
|
||||
if (start == goal) { why = "already in the waypoint's room, the map has no way around"; return null; }
|
||||
var geo = DungeonPathfinder.GetGeometry(lb, cellDat, _raycast()?.GeometryLoader?.DungeonLOS);
|
||||
if (start == goal)
|
||||
{
|
||||
// The same cell: what it stuck on is in the room with it (a table, a statue), and the cell graph has
|
||||
// nothing to say. The dungeon map walks round it.
|
||||
string roomWhy = string.Empty;
|
||||
var inRoom = geo != null ? PlanInRoom(geo, pNs, pEw, pz, tNs, tEw, tz, out roomWhy) : null;
|
||||
if (inRoom != null) return inRoom;
|
||||
why = geo == null ? "already in the waypoint's room, the map has no way around"
|
||||
: $"already in the waypoint's room, the map has no way around ({roomWhy})";
|
||||
return null;
|
||||
}
|
||||
|
||||
var path = DungeonPathfinder.FindPath(start, goal, graph, _hazards());
|
||||
if (path.Count < 2) { why = "no walkable way on the dungeon map"; return null; }
|
||||
|
|
@ -190,7 +209,6 @@ internal sealed class NavRecoveryPlanner : INavRecoveryPlanner
|
|||
// every narrow opening (flagged, so the engine goes through straight), rooms crossed
|
||||
// directly. Without the map geometry, cell-centre midpoints.
|
||||
var plan = new NavRecoveryPlan { Planner = "dungeon map" };
|
||||
var geo = DungeonPathfinder.GetGeometry(lb, cellDat, _raycast()?.GeometryLoader?.DungeonLOS);
|
||||
plan.Points = DungeonPathfinder.BuildPathPoints(path, graph, geo, _hazards(), pNs, pEw, pz, tNs, tEw, tz, out int doorways);
|
||||
plan.Doorways = doorways;
|
||||
if (plan.Points.Count == 0) { why = "empty path"; return null; }
|
||||
|
|
@ -198,6 +216,125 @@ internal sealed class NavRecoveryPlanner : INavRecoveryPlanner
|
|||
return plan;
|
||||
}
|
||||
|
||||
// ── In one room (2026-11-18) ────────────────────────────────────────────
|
||||
// 9 of the 29 logged "no plan" recoveries were "already in the waypoint's room": the character and the
|
||||
// waypoint in one cell, with a table (0x0190 room 88, 0x020002FB), a statue (0x00C1 room 81, 0x020014A3: the
|
||||
// waypoint in its middle), an altar (0x000A) or a slab (0x01F5) between them, and the stuck escapes ran blind
|
||||
// until they gave up (about 3 minutes in 0x00C1). The dungeon map knows those objects now.
|
||||
|
||||
/// <summary>A waypoint inside something placed is moved out to this much room ...</summary>
|
||||
internal const double InRoomTargetClearance = 1.0;
|
||||
/// <summary>... at most this far (0x00C1's statue is 9 x 9 m: its waypoint came 2.5 m out).</summary>
|
||||
internal const double InRoomTargetPushMax = 8.0;
|
||||
|
||||
/// <summary>
|
||||
/// The walk from the character (pNs, pEw, pz) to the waypoint (tNs, tEw, tz) within one room, on the dungeon map:
|
||||
/// a waypoint inside a placed object is moved out of it first (PushClear to InRoomTargetClearance, at most
|
||||
/// InRoomTargetPushMax), then the straight walk is walked round the placed objects on the floor
|
||||
/// (DungeonPathfinder.WalkRoundHoles, objects only). A "dungeon map (room)" plan when that put points in (the
|
||||
/// moved waypoint is its last point, and <see cref="NavRecoveryPlan.TargetMoved"/> is set); null, with
|
||||
/// <paramref name="why"/>, when the straight walk is clear (the snag isn't on the map) or there is no way round.
|
||||
/// Only an obstacle's waypoint is moved: one up on something placed (at its own height <paramref name="tz"/>), or in a
|
||||
/// step-over or a connector, gets no plan.
|
||||
/// </summary>
|
||||
internal static NavRecoveryPlan? PlanInRoom(DungeonGeometry geo, double pNs, double pEw, double pz,
|
||||
double tNs, double tEw, double tz, out string why)
|
||||
{
|
||||
why = string.Empty;
|
||||
double px = DungeonGeometry.NavToWorld(pEw), py = DungeonGeometry.NavToWorld(pNs);
|
||||
double tx = DungeonGeometry.NavToWorld(tEw), ty = DungeonGeometry.NavToWorld(tNs);
|
||||
if (!geo.TryFloorHeight(px, py, pz, 3.0, out double ph)) ph = pz;
|
||||
if (!geo.TryFloorHeight(tx, ty, tz, 3.0, out double th)) th = tz;
|
||||
|
||||
bool moved = false;
|
||||
if (geo.InsidePlaced(tx, ty, th))
|
||||
{
|
||||
// Inside it at the map's floor is not inside it for a waypoint up on it: one recorded on a dais's top, half way
|
||||
// up a ramp or on a platform. Moved down beside the object and taken as reached (TargetMoved), it was skipped,
|
||||
// and the next waypoint, up there too, ran the character into the object's side again, stuck after stuck. Nor
|
||||
// is a step or a ramp (a step-over, a connector) something to move a waypoint out of: it is the way on. Both are
|
||||
// left to the escapes, as before the room planner (review of wf/obst-int).
|
||||
if (geo.OnTopOfPlaced(tx, ty, tz, th))
|
||||
{
|
||||
why = "the waypoint is up on something placed (the map has no floor on its top)";
|
||||
return null;
|
||||
}
|
||||
if (geo.InsidePlaced(tx, ty, Math.Max(th, tz), c => c is PlacedClass.StepOver or PlacedClass.Connector))
|
||||
{
|
||||
why = "the waypoint is in a step or a ramp placed there (climbed, not walked round)";
|
||||
return null;
|
||||
}
|
||||
double ox = tx, oy = ty;
|
||||
geo.PushClear(ref tx, ref ty, th, InRoomTargetClearance, InRoomTargetPushMax);
|
||||
if (geo.InsidePlaced(tx, ty, th) || !geo.OnWalkableFloor(tx, ty, th))
|
||||
{
|
||||
why = "the waypoint is inside something placed, with no floor clear of it within " + InRoomTargetPushMax.ToString("0", System.Globalization.CultureInfo.InvariantCulture) + " m";
|
||||
return null;
|
||||
}
|
||||
moved = Math.Abs(tx - ox) > 1e-6 || Math.Abs(ty - oy) > 1e-6;
|
||||
}
|
||||
|
||||
var target = new NavPoint { Type = NavPointType.Point, NS = DungeonGeometry.WorldToNav(ty), EW = DungeonGeometry.WorldToNav(tx), Z = th / 240.0 };
|
||||
var pts = new List<NavPoint>
|
||||
{
|
||||
new NavPoint { Type = NavPointType.Point, NS = pNs, EW = pEw, Z = ph / 240.0 },
|
||||
target,
|
||||
};
|
||||
using var count = DungeonPathfinder.CountHoles();
|
||||
int left0 = DungeonPathfinder.HolesLeft;
|
||||
int round = DungeonPathfinder.WalkRoundHoles(pts, geo, objectsOnly: true);
|
||||
if (round == 0 && DungeonPathfinder.HolesLeft > left0) { why = "no way round what is placed there"; return null; }
|
||||
if (round == 0 && !moved) { why = "the straight walk is clear on the map (the snag isn't on it)"; return null; }
|
||||
|
||||
var plan = new NavRecoveryPlan { Planner = moved ? "dungeon map (room, waypoint moved out of an object)" : "dungeon map (room)", TargetMoved = moved };
|
||||
// The character's own spot is not walked to; the waypoint is the engine's, unless it was moved.
|
||||
for (int i = 1; i < pts.Count; i++)
|
||||
if (i + 1 < pts.Count || moved) plan.Points.Add(pts[i]);
|
||||
plan.LengthYd = PathLengthYd(pNs, pEw, plan.Points, tNs, tEw);
|
||||
return plan;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// NavigationEngine.EscapeRoom: on the dungeon map, how far (metres, up to 2) the character at (wx, wy, wz) (world
|
||||
/// metres, in <paramref name="cell"/>) gets along a compass heading (0 north, clockwise) before it runs into
|
||||
/// something; NaN outside a dungeon's cell, without the map, or with no floor under the character on it.
|
||||
/// </summary>
|
||||
internal double EscapeRoom(uint cell, double wx, double wy, double wz, double headingDeg)
|
||||
{
|
||||
try
|
||||
{
|
||||
if ((cell & 0xFFFF) < 0x0100) return double.NaN;
|
||||
var cellDat = CellDat;
|
||||
if (cellDat == null || !IsDungeonLandblock(cell >> 16, cellDat)) return double.NaN;
|
||||
var geo = DungeonPathfinder.GetGeometry(cell >> 16, cellDat, _raycast()?.GeometryLoader?.DungeonLOS);
|
||||
return geo == null ? double.NaN : EscapeRoomOn(geo, wx, wy, wz, headingDeg);
|
||||
}
|
||||
catch { return double.NaN; }
|
||||
}
|
||||
|
||||
/// <summary>Along an escape heading, the character has run into something where it comes this near a wall, a floor's
|
||||
/// edge or something placed (half its 0.48 m body over it): a burst sliding along a face it stuck on gets on, one
|
||||
/// head-on into it doesn't.</summary>
|
||||
internal const double EscapeTouchMeters = 0.25;
|
||||
internal const double EscapeLookMeters = 2.0;
|
||||
|
||||
/// <summary>The map half of <see cref="EscapeRoom"/>: looked at every 0.1 m, following the floor.</summary>
|
||||
internal static double EscapeRoomOn(DungeonGeometry geo, double wx, double wy, double wz, double headingDeg)
|
||||
{
|
||||
if (!geo.TryFloorHeight(wx, wy, wz, 3.0, out double h)) return double.NaN;
|
||||
double a = headingDeg * Math.PI / 180.0, ux = Math.Sin(a), uy = Math.Cos(a);
|
||||
const double step = 0.1;
|
||||
for (double d = step; d <= EscapeLookMeters + 1e-9; d += step)
|
||||
{
|
||||
double x = wx + ux * d, y = wy + uy * d;
|
||||
if (!geo.TryFloorHeight(x, y, h, 0.6, out double hh) || !geo.OnWalkableFloor(x, y, hh)
|
||||
|| geo.ClearanceMemo(x, y, hh, EscapeTouchMeters + 0.1) < EscapeTouchMeters)
|
||||
return d - step;
|
||||
h = hh;
|
||||
}
|
||||
return EscapeLookMeters;
|
||||
}
|
||||
|
||||
private NavRecoveryPlan? PlanOutdoor(uint cell, float lx, float ly, float lz,
|
||||
double tNs, double tEw, float tz, out string why)
|
||||
{
|
||||
|
|
@ -212,10 +349,11 @@ internal sealed class NavRecoveryPlanner : INavRecoveryPlanner
|
|||
int result;
|
||||
int count = 0;
|
||||
double[] buf = new double[MaxNavmeshCorners * 3];
|
||||
double[] info = new double[RynthNavPathApiV1.InfoLength];
|
||||
bool ex;
|
||||
unsafe
|
||||
{
|
||||
// Resolved on every call: RynthNav may be missing, or reloaded since last time.
|
||||
// Version 1 (FindPath is all this needs): a RynthNav from before v2 answers it too.
|
||||
IntPtr p = _host.GetPluginInterface(RynthNavPathApiV1.PluginName, RynthNavPathApiV1.InterfaceName, 1);
|
||||
var t = (RynthNavPathApiV1*)p;
|
||||
if (t == null || t->Version < 1 || t->StructSize < RynthNavPathApiV1.SizeV1 || t->FindPath == null)
|
||||
|
|
@ -223,16 +361,42 @@ internal sealed class NavRecoveryPlanner : INavRecoveryPlanner
|
|||
why = "RynthNav isn't loaded";
|
||||
return null;
|
||||
}
|
||||
// Version 2: FindPathEx with the Outdoor Hunt's flags, so the way back keeps out of portals and
|
||||
// 1 m off the walls as the hunt's walks do (v1 FindPath does neither: a detour could run along a
|
||||
// building's wall or through a portal's circle). No PathStartOutdoors: the start is where the
|
||||
// character stands, so from inside a building RynthNav refuses it as before. A RynthNav from
|
||||
// before v2: FindPath.
|
||||
ex = t->Version >= 2 && t->StructSize >= (uint)sizeof(RynthNavPathApiV1) && t->FindPathEx != null;
|
||||
fixed (double* pts = buf)
|
||||
result = t->FindPath(sx, sy, lz, gx, gy, tz, pts, MaxNavmeshCorners, &count);
|
||||
fixed (double* inf = info)
|
||||
result = ex
|
||||
? t->FindPathEx(sx, sy, lz, gx, gy, tz, RynthAiPlugin.HuntPathFlags, 0, pts, MaxNavmeshCorners, &count, inf)
|
||||
: t->FindPath(sx, sy, lz, gx, gy, tz, pts, MaxNavmeshCorners, &count);
|
||||
}
|
||||
|
||||
if (result == RynthNavPathApiV1.ResultNoMesh) { why = "no RynthNav navmesh here"; return null; }
|
||||
if (result != RynthNavPathApiV1.ResultOk || count < 2) { why = "RynthNav found no walkable way"; return null; }
|
||||
// A partial way (the waypoint off the mesh, or past a seam between two tiles that don't link) ends at
|
||||
// the reachable point nearest the waypoint: that point is walked to as well, then the route's own leg
|
||||
// from there, as RynthNav's own walks push straight on over a seam.
|
||||
bool partial = ex && result == RynthNavPathApiV1.ResultPartial;
|
||||
if ((result != RynthNavPathApiV1.ResultOk && !partial) || count < 2) { why = "RynthNav found no walkable way"; return null; }
|
||||
// A partial way that ends where the character stands gets it nowhere: no detour, the escapes (as v1 said).
|
||||
double endX = buf[(count - 1) * 3] - sx, endY = buf[(count - 1) * 3 + 1] - sy;
|
||||
if (partial && endX * endX + endY * endY < PartialMinGainYd * PartialMinGainYd)
|
||||
{
|
||||
why = "RynthNav's way ends where you stand (the waypoint isn't reachable on its map)";
|
||||
return null;
|
||||
}
|
||||
|
||||
var plan = new NavRecoveryPlan { Planner = "RynthNav navmesh" };
|
||||
// Corners 1..count-2 are the turns; the first is our position and the last the waypoint.
|
||||
for (int i = 1; i < count - 1; i++)
|
||||
var plan = new NavRecoveryPlan
|
||||
{
|
||||
Planner = partial ? string.Create(System.Globalization.CultureInfo.InvariantCulture, $"RynthNav navmesh (partial, ends {info[5]:F0}yd short)") : "RynthNav navmesh",
|
||||
NavmeshCorners = true,
|
||||
};
|
||||
// Corners 1..count-2 are the turns; the first is our position and the last the waypoint (for a
|
||||
// partial way the last is where it ends, a point of the detour too).
|
||||
int last = partial ? count : count - 1;
|
||||
for (int i = 1; i < last; i++)
|
||||
{
|
||||
double wx = buf[i * 3], wy = buf[i * 3 + 1], wz = buf[i * 3 + 2];
|
||||
plan.Points.Add(new NavPoint
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
|
@ -131,6 +133,9 @@ internal sealed class NavigationEngine
|
|||
// ── Stuck watchdog ───────────────────────────────────────────────────────
|
||||
private double _watchdogNs = double.NaN;
|
||||
private double _watchdogEw = double.NaN;
|
||||
private long _watchdogAt; // when _watchdogNs/Ew were taken
|
||||
private double _watchdogMovedYd = double.NaN; // moved in the last watchdog window, for the stuck lines
|
||||
private double _watchdogWindowMs;
|
||||
private long _watchdogNext;
|
||||
private int _stuckCount;
|
||||
private bool _inRecovery;
|
||||
|
|
@ -155,6 +160,8 @@ internal sealed class NavigationEngine
|
|||
public int Number; // session recovery counter, for the log
|
||||
public string Reason = string.Empty;
|
||||
public string Planner = string.Empty;
|
||||
public bool Navmesh; // RynthNav navmesh corners: the corner gate applies (NavmeshRaycast)
|
||||
public bool TargetMoved; // the rejoin waypoint is inside something placed: the last point stands in for it
|
||||
public List<NavPoint> Points = new();
|
||||
public int Index; // next detour point to reach
|
||||
public int StartIdx; // ActiveNavIndex when it began (a change cancels it)
|
||||
|
|
@ -193,8 +200,14 @@ internal sealed class NavigationEngine
|
|||
|
||||
/// <summary>Every detour for the current waypoint has been tried and the character is still stuck there
|
||||
/// (only the escapes are left, for as long as it takes): the dungeon explore takes this as a way it can't
|
||||
/// get through, something the map doesn't have standing in it (a spider web spawned in a doorway).</summary>
|
||||
public bool DetoursUsedUpAndStuck => _detour == null && _detourAttempts >= MaxDetourAttempts && _stuckCount >= 2;
|
||||
/// get through, something the map doesn't have standing in it (a spider web spawned in a doorway).
|
||||
/// Only on the route walked when that was found: a route put in since (the explore laid again round that
|
||||
/// way) clears it when navigation next runs, and until then it is not yet stuck at all. Navigation doesn't
|
||||
/// run while buffing: 2026-11-17, a DreamWeave Thread in 0x0278, the explore laid its walk again five times in
|
||||
/// 2.4 s during a rebuff, each time "stuck for good" on the walk before, closing a real opening or spot each
|
||||
/// time until the walk from the start reached nothing and the explore ended as done.</summary>
|
||||
public bool DetoursUsedUpAndStuck => _detour == null && _detourAttempts >= MaxDetourAttempts && _stuckCount >= 2
|
||||
&& ReferenceEquals(_settings.CurrentRoute, _lastRoute);
|
||||
|
||||
private INavRecoveryPlanner? _planner;
|
||||
private Detour? _detour;
|
||||
|
|
@ -239,6 +252,9 @@ internal sealed class NavigationEngine
|
|||
// ── Observability (GetStateSnapshot / /ra navstate) ──────────────────────
|
||||
private double _lastDistYd = double.NaN;
|
||||
private double _lastHeadingErr = double.NaN;
|
||||
// The heading the steering last aimed at (0 = north, clockwise; NaN = not steered yet), kept from
|
||||
// HeadingErrorTo / SteerToWaypoint for the stuck lines.
|
||||
private double _lastDesiredDeg = double.NaN;
|
||||
private long _lastSteerAt;
|
||||
|
||||
// ── Derived thresholds (from settings) ──────────────────────────────────
|
||||
|
|
@ -273,8 +289,12 @@ internal sealed class NavigationEngine
|
|||
// half a metre of its centre line, at under 15 degrees. The lookahead is off at them too.
|
||||
internal const double DoorwayReachYd = 1.0; // NavMarkerRenderer draws doorway rings at this size
|
||||
private const double DoorwaySweepMult = 1.5;
|
||||
private double ReachFor(NavPoint p) => p.Doorway ? Math.Min(ArrivalYards, DoorwayReachYd) : ArrivalYards;
|
||||
private double SweepFor(NavPoint p) => ReachFor(p) * (p.Doorway ? Math.Min(SweepMult, DoorwaySweepMult) : SweepMult);
|
||||
// A Jump step is reached as tightly as a doorway, from a file too (Doorway is never saved): it stands at
|
||||
// the edge it was laid or recorded at (/ra nav addjump, 2026-11-18), and a jump a yard or two short of a
|
||||
// ledge or a stepping stone falls short.
|
||||
private static bool Tight(NavPoint p) => p.Doorway || p.Type == NavPointType.Jump;
|
||||
private double ReachFor(NavPoint p) => Tight(p) ? Math.Min(ArrivalYards, DoorwayReachYd) : ArrivalYards;
|
||||
private double SweepFor(NavPoint p) => ReachFor(p) * (Tight(p) ? Math.Min(SweepMult, DoorwaySweepMult) : SweepMult);
|
||||
|
||||
// Lookahead (corner rounding): within this distance of a waypoint, blend the aim point
|
||||
// toward the next one so corners are rounded. It used to be the Lookahead setting alone
|
||||
|
|
@ -291,15 +311,57 @@ internal sealed class NavigationEngine
|
|||
=> Math.Clamp(CornerRoundPerReachYd * (reachYd - CornerRoundFreeReachYd), 0.0, Math.Max(0.0, lookaheadSetting));
|
||||
private double LookaheadYards => CornerLookaheadYards(_settings.NavLookaheadYards, ArrivalYards);
|
||||
|
||||
// Corner gate (2026-11-18). A hunt walk is RynthNav's path, laid 1 m off the walls; nav turned toward the
|
||||
// next corner at the nav point reach (1.5 yd) without looking, and the cut across the inside of the corner
|
||||
// left the mesh's safe corridor for the building corner the path went round. A walk simulation on the live
|
||||
// tiles (0x7D64, 0xA9B4, 0x32D9, 0x64D5, 0x238E, 1,309 walks) had the centre line through baked collision on
|
||||
// 157 walks at reach 1.5, and on 10 with this gate (the body's sides, 0.48 m out, touching it: 343 to 167).
|
||||
// So on walks along RynthNav's corners (a hunt walk, a planned GoTo, a navmesh detour) a corner is reached at
|
||||
// the nav point reach, or blended toward the next one, only while RynthNav's raycast from the character to the
|
||||
// next corner is clear (RynthNav's own walker does the same: PathFollow.Advance); otherwise as tightly as a
|
||||
// doorway point (DoorwayReachYd). Meta, VTank and saved routes are never gated and keep their reach exactly.
|
||||
|
||||
/// <summary>RynthNav's navmesh raycast (RynthNav.Path v2) from (x, y, z) to (x, y, z), world units: RayClear (1)
|
||||
/// when a straight walk stays on the mesh. Set by the plugin (RynthAiPlugin.HuntRaycast); null: no corner gate.</summary>
|
||||
public Func<double, double, double, double, double, double, int>? NavmeshRaycast { get; set; }
|
||||
|
||||
private bool CornerGated(NavRouteParser route) => NavmeshRaycast != null && (route.OutdoorHuntWalk || route.NavmeshCorners);
|
||||
private double TightReachYd => Math.Min(ArrivalYards, DoorwayReachYd);
|
||||
private int _cornerHeldIdx = -1; // the route waypoint whose turn the gate has held (for the arrival line)
|
||||
|
||||
/// <summary>
|
||||
/// False when the walk may not turn the corner at <paramref name="pt"/> yet: a gated walk, the character inside
|
||||
/// the reach (or the lookahead blend) but outside the tight reach, a corner after it, and no straight walk to
|
||||
/// that corner on the navmesh. True everywhere the answer changes nothing, so the raycast is asked only there.
|
||||
/// </summary>
|
||||
private bool CornerOpen(NavPoint pt, NavPoint? next, double dist, double blendYd)
|
||||
{
|
||||
if (Tight(pt) || dist < TightReachYd || dist >= Math.Max(ReachFor(pt), blendYd)) return true;
|
||||
if (next == null || !IsWalkTarget(next.Type)) return true; // the walk's end: no corner to turn
|
||||
return NavmeshStraightTo(next);
|
||||
}
|
||||
|
||||
/// <summary>The navmesh raycast from the character to <paramref name="p"/> is clear.</summary>
|
||||
private bool NavmeshStraightTo(NavPoint p)
|
||||
{
|
||||
var ray = NavmeshRaycast;
|
||||
if (ray == null) return true;
|
||||
if (!_host.TryGetPlayerPose(out uint cell, out float lx, out float ly, out float lz, out _, out _, out _, out _) || cell == 0)
|
||||
return false;
|
||||
double ax = ((cell >> 24) & 0xFF) * 192.0 + lx, ay = ((cell >> 16) & 0xFF) * 192.0 + ly;
|
||||
double bz = p.Z != 0.0 ? p.Z * 240.0 : lz; // 0: not recorded
|
||||
return ray(ax, ay, lz, NavToWorld(p.EW), NavToWorld(p.NS), bz) == RynthNavPathApiV1.RayClear;
|
||||
}
|
||||
|
||||
// Pass-through: a plain waypoint the character has gone past (it is beyond the point along
|
||||
// the way it came, and no farther to the side than the sweep radius) counts as reached,
|
||||
// so nav doesn't turn round to walk back to it. "Beyond along the way it came" means the
|
||||
// point is behind the character: a corner cut toward the next point never qualifies.
|
||||
// Doorway points keep their own tight reach and sweep and never use it.
|
||||
// Doorway and Jump points keep their own tight reach and sweep and never use it.
|
||||
private const double PassMinLegYd = 1.0; // shorter approach: no reliable direction
|
||||
private bool PassedThrough(NavPoint pt, double ns, double ew)
|
||||
{
|
||||
if (pt.Doorway || double.IsNaN(_legStartNs)) return false;
|
||||
if (Tight(pt) || double.IsNaN(_legStartNs)) return false;
|
||||
double ux = (pt.NS - _legStartNs) * 240.0, uy = (pt.EW - _legStartEw) * 240.0;
|
||||
double len = Math.Sqrt(ux * ux + uy * uy);
|
||||
if (len < PassMinLegYd) return false;
|
||||
|
|
@ -484,6 +546,7 @@ internal sealed class NavigationEngine
|
|||
_lastRoute = route;
|
||||
_inPause = false;
|
||||
_closestDist = double.MaxValue;
|
||||
_cornerHeldIdx = -1;
|
||||
_linearDir = 1;
|
||||
if (!sameWalk)
|
||||
{
|
||||
|
|
@ -662,10 +725,20 @@ internal sealed class NavigationEngine
|
|||
}
|
||||
_campHoldAnnounced = false;
|
||||
|
||||
// Arrival check
|
||||
if (dist < ReachFor(pt))
|
||||
// Corner gate (see NavmeshRaycast): on a walk along RynthNav's corners the turn waits for a clear raycast.
|
||||
bool cornerOpen = true;
|
||||
if (CornerGated(route))
|
||||
{
|
||||
_host.Log($"Nav: arrived at [{idx}] dist={dist:F1}yd → advancing");
|
||||
int ni = PeekNext(idx, route);
|
||||
cornerOpen = CornerOpen(pt, ni >= 0 ? route.Points[ni] : null, dist, LookaheadYards);
|
||||
if (!cornerOpen) _cornerHeldIdx = idx;
|
||||
}
|
||||
|
||||
// Arrival check
|
||||
if (dist < (cornerOpen ? ReachFor(pt) : TightReachYd))
|
||||
{
|
||||
string held = _cornerHeldIdx == idx ? $" (corner held to {TightReachYd:F1}yd: no straight walk to the next on the navmesh)" : "";
|
||||
_host.Log($"Nav: arrived at [{idx}] dist={dist:F1}yd → advancing{held}");
|
||||
_closestDist = double.MaxValue;
|
||||
UpdateStatusLine(idx, dist, route, 0.0);
|
||||
// Advance before the jump: the Jumper pauses nav and later restores what it
|
||||
|
|
@ -703,7 +776,7 @@ internal sealed class NavigationEngine
|
|||
}
|
||||
_closestDist = Math.Min(_closestDist, dist);
|
||||
|
||||
SteerToWaypoint(idx, pt, route, ns, ew, dist);
|
||||
SteerToWaypoint(idx, pt, route, ns, ew, dist, cornerOpen);
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
|
|
@ -1083,14 +1156,15 @@ internal sealed class NavigationEngine
|
|||
|
||||
|
||||
private void SteerToWaypoint(int idx, NavPoint pt, NavRouteParser route,
|
||||
double ns, double ew, double dist)
|
||||
double ns, double ew, double dist, bool cornerOpen = true)
|
||||
{
|
||||
_steerDoorway = pt.Doorway;
|
||||
_steerDoorway = Tight(pt);
|
||||
// ── Lookahead blend ──────────────────────────────────────────────────
|
||||
double tNS = pt.NS, tEW = pt.EW;
|
||||
// Never at a doorway point: blending toward the next point there is exactly the corner
|
||||
// cut that meets a narrow opening at an angle.
|
||||
if (dist < LookaheadYards && !pt.Doorway)
|
||||
// cut that meets a narrow opening at an angle. Nor at a corner the gate holds (no straight
|
||||
// walk to the next one on the navmesh).
|
||||
if (dist < LookaheadYards && !Tight(pt) && cornerOpen)
|
||||
{
|
||||
int ni = PeekNext(idx, route);
|
||||
// Only blend toward the NEXT waypoint when it is a real travel target
|
||||
|
|
@ -1112,6 +1186,7 @@ internal sealed class NavigationEngine
|
|||
// ── Desired heading (0=North, clockwise) ────────────────────────────
|
||||
double desiredDeg = Math.Atan2(tEW - ew, tNS - ns) * (180.0 / Math.PI);
|
||||
if (desiredDeg < 0) desiredDeg += 360.0;
|
||||
_lastDesiredDeg = desiredDeg;
|
||||
|
||||
// ── Current heading from quaternion (always reliable) ───────────────
|
||||
double currentDeg;
|
||||
|
|
@ -1141,6 +1216,7 @@ internal sealed class NavigationEngine
|
|||
{
|
||||
double desiredDeg = Math.Atan2(tEW - ew, tNS - ns) * (180.0 / Math.PI);
|
||||
if (desiredDeg < 0) desiredDeg += 360.0;
|
||||
_lastDesiredDeg = desiredDeg;
|
||||
|
||||
if (TryGetQuaternionHeading(out float qHeading))
|
||||
{
|
||||
|
|
@ -1365,6 +1441,7 @@ internal sealed class NavigationEngine
|
|||
{
|
||||
int oldIdx = _settings.ActiveNavIndex;
|
||||
_closestDist = double.MaxValue;
|
||||
_cornerHeldIdx = -1;
|
||||
_portalState = PortalState.None;
|
||||
// Reaching a waypoint is progress: the next snag gets a fresh detour budget.
|
||||
_detourAttempts = 0;
|
||||
|
|
@ -2379,6 +2456,8 @@ internal sealed class NavigationEngine
|
|||
{
|
||||
double dN = ns - _watchdogNs, dE = ew - _watchdogEw;
|
||||
double moved = Math.Sqrt(dN * dN + dE * dE) * 240.0;
|
||||
_watchdogMovedYd = moved;
|
||||
_watchdogWindowMs = Now - _watchdogAt;
|
||||
if (moved < StuckYd)
|
||||
{
|
||||
_stuckCount++;
|
||||
|
|
@ -2391,6 +2470,7 @@ internal sealed class NavigationEngine
|
|||
}
|
||||
_watchdogNs = ns;
|
||||
_watchdogEw = ew;
|
||||
_watchdogAt = Now;
|
||||
}
|
||||
|
||||
// ── Escapes and portals (2026-11-15) ────────────────────────────────────
|
||||
|
|
@ -2430,6 +2510,55 @@ internal sealed class NavigationEngine
|
|||
return EscapeOffsetClear(px, py, lz, curDeg, near, ref offset, out note);
|
||||
}
|
||||
|
||||
// ── Room for a burst on the dungeon map (2026-11-18) ────────────────────────────────────────
|
||||
// The bursts are blind: +75, -75, then 165 degrees off the heading, whatever is there. In a dungeon the map knows
|
||||
// the walls and what the cells place, so a burst that would run head-on into one (a side step into the wall of a
|
||||
// corner, a crate beside the altar it stuck on) is turned to the side that has room. A burst sliding along the
|
||||
// face it stuck on gets on, so it is kept: the rungs still try their different sides in turn.
|
||||
|
||||
/// <summary>The dungeon map's room for an escape burst: how far (metres, up to 2) the character (cell, world x, y, z)
|
||||
/// gets along a compass heading (0 north, clockwise) before it runs into something; NaN where the map doesn't say.
|
||||
/// RynthAiPlugin sets it (NavRecoveryPlanner.EscapeRoom).</summary>
|
||||
public Func<uint, double, double, double, double, double>? EscapeRoom { get; set; }
|
||||
/// <summary>A burst that gets less than this far runs head-on into something: another heading is looked for.</summary>
|
||||
internal const double EscapeRoomTight = 0.5;
|
||||
/// <summary>The other heading is taken when it gets this much farther.</summary>
|
||||
internal const double EscapeRoomBetter = 0.5;
|
||||
private static readonly double[] EscapeRoomDeg = { +SideStepDeg, -SideStepDeg, BackOutDeg, -BackOutDeg };
|
||||
|
||||
private bool RoomiestEscapeOffset(double curDeg, ref double offset, out string? note)
|
||||
{
|
||||
note = null;
|
||||
var room = EscapeRoom;
|
||||
if (room == null || !_host.TryGetPlayerPose(out uint cell, out float lx, out float ly, out float lz, out _, out _, out _, out _) || cell == 0) return false;
|
||||
double px = ((cell >> 24) & 0xFF) * 192.0 + lx, py = ((cell >> 16) & 0xFF) * 192.0 + ly;
|
||||
return PickRoomiestEscape(curDeg, ref offset, h => room(cell, px, py, lz, h), out note);
|
||||
}
|
||||
|
||||
/// <summary>The pure half of <see cref="RoomiestEscapeOffset"/>: the rung's offset when it has EscapeRoomTight ahead
|
||||
/// (or the map doesn't say), else the side-step or back-out offset with the most room, when that is EscapeRoomBetter
|
||||
/// more. True (note says so) when it turned the burst.</summary>
|
||||
internal static bool PickRoomiestEscape(double curDeg, ref double offset, Func<double, double> roomAt, out string? note)
|
||||
{
|
||||
note = null;
|
||||
double first = offset, own = roomAt(Wrap360(curDeg + first));
|
||||
if (double.IsNaN(own) || own >= EscapeRoomTight) return false;
|
||||
double pick = first, pickRoom = double.NegativeInfinity;
|
||||
foreach (double off in EscapeRoomDeg)
|
||||
{
|
||||
if (Math.Abs(off - first) < 0.01) continue;
|
||||
double r = roomAt(Wrap360(curDeg + off));
|
||||
if (!double.IsNaN(r) && r > pickRoom) { pick = off; pickRoom = r; }
|
||||
}
|
||||
if (Math.Abs(pick - first) < 0.01 || !(pickRoom > own + EscapeRoomBetter)) return false;
|
||||
note = string.Create(CultureInfo.InvariantCulture,
|
||||
$"escape burst turned {pick:+0;-0}° instead of {first:+0;-0}° for room on the dungeon map ({pickRoom:F1} m clear ahead, {own:F1} m that way)");
|
||||
offset = pick;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static double Wrap360(double deg) { deg %= 360.0; return deg < 0 ? deg + 360.0 : deg; }
|
||||
|
||||
/// <summary>The pure half of <see cref="PortalSafeEscapeOffset"/> (world position given).</summary>
|
||||
internal static bool EscapeOffsetClear(double px, double py, double pz, double curDeg,
|
||||
IReadOnlyList<(double X, double Y, double Z)> portals, ref double offset, out string? note)
|
||||
|
|
@ -2483,6 +2612,11 @@ internal sealed class NavigationEngine
|
|||
}
|
||||
|
||||
_settings.NavIsStuck = true;
|
||||
// Where, before anything moves the character: every stuck line ends with it.
|
||||
string where = StuckWhere(route);
|
||||
_lastStuckWhere = where;
|
||||
_lastStuckAt = Now;
|
||||
_lastStuckCount = _stuckCount;
|
||||
StopMovement();
|
||||
|
||||
// Escalation ladder, keyed on how many consecutive watchdog windows have
|
||||
|
|
@ -2492,7 +2626,7 @@ internal sealed class NavigationEngine
|
|||
{
|
||||
// Nothing shook us loose. Waypoints are never skipped (2026-09-28):
|
||||
// start the ladder over (jump, side-steps, back-out) on the same one.
|
||||
_host.Log($"Nav: stuck x{_stuckCount} at [{_settings.ActiveNavIndex}] — still stuck, retrying the escapes.");
|
||||
_host.Log($"Nav: stuck x{_stuckCount} at [{_settings.ActiveNavIndex}] — still stuck, retrying the escapes | {where}");
|
||||
_stuckCount = 1;
|
||||
}
|
||||
|
||||
|
|
@ -2503,13 +2637,17 @@ internal sealed class NavigationEngine
|
|||
if (_detour != null)
|
||||
EndDetour("stuck on the detour", success: false);
|
||||
else if (TryStuckDetour(route))
|
||||
{
|
||||
_host.Log($"Nav: stuck x{_stuckCount} — detour, recovery #{_recoveryNumber} | {where}");
|
||||
return;
|
||||
}
|
||||
|
||||
// Rungs 2+ need a heading we can command. Without TurnToHeading the only
|
||||
// primitive we have is the jump, so stay on rung 1 rather than autorunning
|
||||
// blindly into whatever we happen to be facing.
|
||||
if (_stuckCount <= 1 || !_host.HasTurnToHeading || !TryGetQuaternionHeading(out float curDeg))
|
||||
{
|
||||
_host.Log($"Nav: stuck x{_stuckCount} — jump | {where}");
|
||||
_recoveryKind = RecoveryKind.Jump;
|
||||
_recoveryUntil = Now + (long)RecoveryMs;
|
||||
_inRecovery = true;
|
||||
|
|
@ -2524,23 +2662,26 @@ internal sealed class NavigationEngine
|
|||
_ => BackOutDeg,
|
||||
};
|
||||
|
||||
// In a dungeon, a burst heading straight into a wall or something placed is turned to where the map has room.
|
||||
if (RoomiestEscapeOffset(curDeg, ref offset, out string? roomNote)) _host.Log($"Nav: stuck x{_stuckCount} — {roomNote} | {where}");
|
||||
|
||||
// A burst must not run the character into a portal (it fires on touch): the rung's heading if
|
||||
// it keeps away from every portal near, else the nearest one that does; none: the jump instead.
|
||||
if (!PortalSafeEscapeOffset(curDeg, ref offset, out string? portalNote))
|
||||
{
|
||||
_host.Log($"Nav: stuck x{_stuckCount} — every escape heading runs at a portal ({portalNote}): jumping instead.");
|
||||
_host.Log($"Nav: stuck x{_stuckCount} — every escape heading runs at a portal ({portalNote}): jumping instead | {where}");
|
||||
_recoveryKind = RecoveryKind.Jump;
|
||||
_recoveryUntil = Now + (long)RecoveryMs;
|
||||
_inRecovery = true;
|
||||
_host.JumpNonAutonomous(0.5f);
|
||||
return;
|
||||
}
|
||||
if (portalNote != null) _host.Log($"Nav: stuck x{_stuckCount} — {portalNote}.");
|
||||
if (portalNote != null) _host.Log($"Nav: stuck x{_stuckCount} — {portalNote} | {where}");
|
||||
|
||||
double escapeHeading = curDeg + offset;
|
||||
if (escapeHeading >= 360.0) escapeHeading -= 360.0; else if (escapeHeading < 0.0) escapeHeading += 360.0;
|
||||
|
||||
_host.Log($"Nav: stuck x{_stuckCount} — escape burst {offset:+0;-0}° for {RecoveryBurstMs:F0}ms.");
|
||||
_host.Log($"Nav: stuck x{_stuckCount} — escape burst {offset:+0;-0}° for {RecoveryBurstMs:F0}ms | {where}");
|
||||
_host.TurnToHeadingBy("Nav", (float)escapeHeading);
|
||||
StartForward();
|
||||
_recoveryKind = RecoveryKind.Escape;
|
||||
|
|
@ -2959,9 +3100,68 @@ internal sealed class NavigationEngine
|
|||
|
||||
// ── Starting / ending a detour ───────────────────────────────────────────
|
||||
|
||||
/// <summary>Stucks at the latest stuck spot (within StuckSpotYards of each other), for the outdoor hunt: at
|
||||
/// StuckSpotRepeatHits it leaves the monster it walks to and keeps its walks off the spot. StuckSpotSeq: every stuck noted.</summary>
|
||||
internal int StuckSpotHits => _stuckSpotHits;
|
||||
internal int StuckSpotSeq { get; private set; }
|
||||
internal const int StuckSpotRepeatHits = StuckSpotRepeat;
|
||||
|
||||
// ── Where a stuck happened (2026-11-18) ──────────────────────────────────
|
||||
// Only 2 of the logged dungeon stucks had a position, and the 0x01F5 and A9B4 replays failed for want of z.
|
||||
// Every "Nav: stuck xN" line ends with " | " and the spot as key=value words, on the one line:
|
||||
// cell=0x019001A2 at=(262.00,38.00,-12.00) heading=271 desired=268 target=[5] to=(263.10,38.20,-12.00) 1.1m
|
||||
// moved=0.42m/5.0s walk=Circular
|
||||
// at/to are local to the character's landblock (a dungeon's coordinates); heading is where it faces, desired
|
||||
// where nav last steered it (0 = north, clockwise); target is the route index, "[5]/detour#3:2/4" on a detour
|
||||
// (its point 2 of 4); moved is the stuck watchdog's window; walk is hunt, navmesh (a planned GoTo) or the
|
||||
// route's type.
|
||||
private string _lastStuckWhere = string.Empty;
|
||||
private long _lastStuckAt;
|
||||
private int _lastStuckCount;
|
||||
|
||||
/// <summary>The last stuck's spot (the words after " | " on its stuck line); empty before the first stuck.</summary>
|
||||
internal string LastStuckWhere => _lastStuckWhere;
|
||||
|
||||
/// <summary>"; last nav stuck x2 4.1s ago: cell=..." for a line about the same trouble logged later (the explore's
|
||||
/// stuck for good); empty when nav hasn't been stuck.</summary>
|
||||
internal string LastStuckNote()
|
||||
=> _lastStuckWhere.Length == 0 ? string.Empty
|
||||
: string.Create(CultureInfo.InvariantCulture, $"; last nav stuck x{_lastStuckCount} {(Now - _lastStuckAt) / 1000.0:F1}s ago: {_lastStuckWhere}");
|
||||
|
||||
private string StuckWhere(NavRouteParser route)
|
||||
{
|
||||
var inv = CultureInfo.InvariantCulture;
|
||||
var sb = new StringBuilder(200);
|
||||
bool pose = _host.TryGetPlayerPose(out uint cell, out float lx, out float ly, out float lz, out _, out _, out _, out _) && cell != 0;
|
||||
if (pose) sb.Append(inv, $"cell=0x{cell:X8} at=({lx:F2},{ly:F2},{lz:F2})");
|
||||
else sb.Append("cell=? at=?");
|
||||
sb.Append(TryGetQuaternionHeading(out float heading) ? string.Create(inv, $" heading={heading:F0}") : " heading=?");
|
||||
sb.Append(double.IsNaN(_lastDesiredDeg) ? " desired=?" : string.Create(inv, $" desired={_lastDesiredDeg:F0}"));
|
||||
|
||||
// The point it was heading for: a detour's when one is walked, else the route's.
|
||||
int idx = _settings.ActiveNavIndex;
|
||||
NavPoint? t = null;
|
||||
string which = $"[{idx}]";
|
||||
var d = _detour;
|
||||
if (d != null && d.Index < d.Points.Count) { t = d.Points[d.Index]; which = $"[{idx}]/detour#{d.Number}:{d.Index + 1}/{d.Points.Count}"; }
|
||||
else if (IndexValid(idx, route)) t = route.Points[idx];
|
||||
sb.Append(" target=").Append(which);
|
||||
if (t != null && pose)
|
||||
{
|
||||
double ox = ((cell >> 24) & 0xFF) * 192.0, oy = ((cell >> 16) & 0xFF) * 192.0;
|
||||
double tx = NavToWorld(t.EW) - ox, ty = NavToWorld(t.NS) - oy, tz = t.Z * 240.0;
|
||||
double off = Math.Sqrt((tx - lx) * (tx - lx) + (ty - ly) * (ty - ly));
|
||||
sb.Append(inv, $" to=({tx:F2},{ty:F2},{tz:F2}) {off:F1}m");
|
||||
}
|
||||
sb.Append(double.IsNaN(_watchdogMovedYd) ? " moved=?" : string.Create(inv, $" moved={_watchdogMovedYd:F2}m/{_watchdogWindowMs / 1000.0:F1}s"));
|
||||
sb.Append(" walk=").Append(route.OutdoorHuntWalk ? "hunt" : route.NavmeshCorners ? "navmesh" : route.RouteType.ToString());
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private void NoteStuckSpot()
|
||||
{
|
||||
if (!TryGetPos(out double ns, out double ew)) return;
|
||||
StuckSpotSeq++;
|
||||
if (!double.IsNaN(_stuckSpotNs) && NavYd(ns - _stuckSpotNs, ew - _stuckSpotEw) <= StuckSpotYards)
|
||||
{
|
||||
_stuckSpotHits++;
|
||||
|
|
@ -3018,6 +3218,8 @@ internal sealed class NavigationEngine
|
|||
Number = number,
|
||||
Reason = reason,
|
||||
Planner = plan.Planner,
|
||||
Navmesh = plan.NavmeshCorners,
|
||||
TargetMoved = plan.TargetMoved && plan.Points.Count > 0,
|
||||
Points = plan.Points,
|
||||
StartIdx = idx,
|
||||
RejoinIdx = rejoin,
|
||||
|
|
@ -3105,7 +3307,11 @@ internal sealed class NavigationEngine
|
|||
|
||||
var p = d.Points[d.Index];
|
||||
double dist = NavYd(p.NS - ns, p.EW - ew);
|
||||
if (dist < ReachFor(p) || (d.ClosestDist < SweepFor(p) && dist > d.ClosestDist + 0.3))
|
||||
double look = Math.Min(LookaheadYards, 2.0);
|
||||
var next = d.Index + 1 < d.Points.Count ? d.Points[d.Index + 1] : route.Points[d.RejoinIdx];
|
||||
// A navmesh detour is RynthNav's path too: its corners wait for a clear raycast (the corner gate).
|
||||
bool cornerOpen = !d.Navmesh || NavmeshRaycast == null || CornerOpen(p, next, dist, look);
|
||||
if (dist < (cornerOpen ? ReachFor(p) : TightReachYd) || (d.ClosestDist < SweepFor(p) && dist > d.ClosestDist + 0.3))
|
||||
{
|
||||
d.Index++;
|
||||
d.ClosestDist = double.MaxValue;
|
||||
|
|
@ -3113,6 +3319,15 @@ internal sealed class NavigationEngine
|
|||
{
|
||||
// Back on the route: resume at the rejoin waypoint; normal nav walks the last leg.
|
||||
_settings.ActiveNavIndex = d.RejoinIdx;
|
||||
if (d.TargetMoved)
|
||||
{
|
||||
// The waypoint is inside something placed (0x00C1 room 81: a statue's middle) and the detour's last
|
||||
// point is the nearest spot clear of it: that is reaching it. Walking on at it ran into the
|
||||
// statue again, stuck after stuck, until the detours were used up.
|
||||
Advance(route);
|
||||
EndDetour($"reached the spot nearest [{d.RejoinIdx}] (it is inside something placed), on to [{_settings.ActiveNavIndex}]", success: true);
|
||||
return;
|
||||
}
|
||||
EndDetour($"rejoined the route at [{d.RejoinIdx}]", success: true);
|
||||
}
|
||||
return;
|
||||
|
|
@ -3120,12 +3335,10 @@ internal sealed class NavigationEngine
|
|||
d.ClosestDist = Math.Min(d.ClosestDist, dist);
|
||||
|
||||
// Aim point: blend toward the following point near arrival, but less than the
|
||||
// route does (doorways are narrow).
|
||||
// route does (doorways are narrow), and not at a corner the gate holds.
|
||||
double tNS = p.NS, tEW = p.EW;
|
||||
double look = Math.Min(LookaheadYards, 2.0);
|
||||
if (look > 0.0 && dist < look && !p.Doorway)
|
||||
if (look > 0.0 && dist < look && !p.Doorway && cornerOpen)
|
||||
{
|
||||
var next = d.Index + 1 < d.Points.Count ? d.Points[d.Index + 1] : route.Points[d.RejoinIdx];
|
||||
double t = 1.0 - dist / look;
|
||||
tNS = Lerp(p.NS, next.NS, t);
|
||||
tEW = Lerp(p.EW, next.EW, t);
|
||||
|
|
@ -3154,6 +3367,8 @@ internal sealed class NavigationEngine
|
|||
d.Points = plan.Points;
|
||||
d.Index = 0;
|
||||
d.Planner = plan.Planner;
|
||||
d.Navmesh = plan.NavmeshCorners;
|
||||
d.TargetMoved = plan.TargetMoved && plan.Points.Count > 0;
|
||||
d.LengthYd = plan.LengthYd;
|
||||
d.Doorways = plan.Doorways;
|
||||
d.DoorRequests.Clear();
|
||||
|
|
|
|||
|
|
@ -224,6 +224,8 @@ internal sealed class OutdoorHunt
|
|||
Anchor = at;
|
||||
TargetId = 0;
|
||||
_skip.Clear();
|
||||
_skipCells.Clear();
|
||||
_snags.Clear();
|
||||
_lastPlan = _lastPick = _arrivedSince = DateTime.MinValue;
|
||||
Note = $"started at {at.X:0},{at.Y:0}";
|
||||
}
|
||||
|
|
@ -239,6 +241,24 @@ internal sealed class OutdoorHunt
|
|||
/// <summary>Left out of the hunt for a while (no way to it, or combat gave up on it).</summary>
|
||||
public void Skip(int id, DateTime now, double sec = -1) => _skip[id] = now.AddSeconds(sec < 0 ? SkipSec : sec);
|
||||
|
||||
/// <summary>A building's cell a walk ended a floor under: every monster in it is left out this long.</summary>
|
||||
public double SkipCellSec { get; set; } = 600;
|
||||
private readonly Dictionary<uint, DateTime> _skipCells = new();
|
||||
/// <summary>Under the monster being walked to (this near, a floor apart) this long in all: the walk can't get up there.</summary>
|
||||
public double UnderItSec { get; set; } = 3;
|
||||
public double UnderItYd { get; set; } = 4;
|
||||
private double _underSec; // time under the target so far (UnderItSec)
|
||||
private DateTime _underLast = DateTime.MinValue; // the last tick under it (MinValue: not under it)
|
||||
private void NewTarget() { _underSec = 0; _underLast = DateTime.MinValue; }
|
||||
|
||||
internal bool CellSkipped(uint cell, DateTime now)
|
||||
{
|
||||
if (cell == 0 || !_skipCells.TryGetValue(cell, out var until)) return false;
|
||||
if (now < until) return true;
|
||||
_skipCells.Remove(cell);
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool IsSkipped(int id, DateTime now)
|
||||
{
|
||||
if (!_skip.TryGetValue(id, out var until)) return false;
|
||||
|
|
@ -292,16 +312,31 @@ internal sealed class OutdoorHunt
|
|||
// rooms" to one on the floor above went to the spot under it; it moved about up there, so each walk
|
||||
// planned again ended a yard or two off, and it was walked again every half second for 20 s; nav's
|
||||
// points count as reached by the flat distance).
|
||||
bool floorApart = t is Candidate under && routeDone && !IsSkipped(under.Id, now)
|
||||
&& me.FlatDistanceTo(_plannedTo) <= ReachYd && Math.Abs(under.Pos.Z - me.Z) > ReachRiseYd;
|
||||
// Or, walk over or not, it has been under the monster (a floor apart) for UnderItSec in all: the
|
||||
// monster moving about up there made each walk planned again a fresh one, so the walk never ran
|
||||
// out and the character circled under it (2026-11-17 10:55:43, Thread E74E, 16 s: "doing circles").
|
||||
if (t is Candidate near && me.FlatDistanceTo(near.Pos) <= UnderItYd && Math.Abs(near.Pos.Z - me.Z) > ReachRiseYd)
|
||||
{
|
||||
if (_underLast != DateTime.MinValue) _underSec += Math.Min(1.0, (now - _underLast).TotalSeconds);
|
||||
_underLast = now;
|
||||
}
|
||||
else _underLast = DateTime.MinValue;
|
||||
bool floorApart = t is Candidate under && !IsSkipped(under.Id, now) && Math.Abs(under.Pos.Z - me.Z) > ReachRiseYd
|
||||
&& ((routeDone && me.FlatDistanceTo(_plannedTo) <= ReachYd) || _underSec >= UnderItSec);
|
||||
if (floorApart)
|
||||
{
|
||||
var u = t!.Value;
|
||||
Skip(u.Id, now);
|
||||
// The spot too (a building's cell): the others up there are no nearer (2026-11-17, Thread
|
||||
// E74E: a Tormentor, a Reaver and an Excruciator on one platform were walked under one after
|
||||
// another, 10:15 to 10:17, and each again 120 s later).
|
||||
bool spot = IsIndoorCell(u.Cell);
|
||||
if (spot) _skipCells[u.Cell] = now.AddSeconds(SkipCellSec);
|
||||
Note = $"'{u.Name}': the walk to it ended {Math.Abs(u.Pos.Z - me.Z):0} yd {(u.Pos.Z > me.Z ? "below" : "above")} it "
|
||||
+ $"(another floor, no way there found): left out for {SkipSec:0} s";
|
||||
+ $"(another floor, no way there found): left out for {SkipSec:0} s"
|
||||
+ (spot ? $", and every monster in its cell {u.Cell & 0xFFFF:X4} for {SkipCellSec / 60:0} min" : "");
|
||||
}
|
||||
else if (t is Candidate target && InArea(target.Pos) && !IsSkipped(target.Id, now) && Plannable(target))
|
||||
else if (t is Candidate target && InArea(target.Pos) && !IsSkipped(target.Id, now) && !CellSkipped(target.Cell, now) && Plannable(target))
|
||||
{
|
||||
double since = (now - _lastPlan).TotalSeconds;
|
||||
bool moved = target.Pos.DistanceTo(_plannedTo) > ReplanMovedYd && since >= ReplanMinSec;
|
||||
|
|
@ -334,6 +369,7 @@ internal sealed class OutdoorHunt
|
|||
}
|
||||
TargetId = 0;
|
||||
_arrivedSince = DateTime.MinValue;
|
||||
NewTarget();
|
||||
}
|
||||
|
||||
// Choosing (at most once every PickEverySec): the few nearest, by the walk to them.
|
||||
|
|
@ -347,7 +383,7 @@ internal sealed class OutdoorHunt
|
|||
{
|
||||
if (asked >= PickCandidates) break;
|
||||
if (c.Distance > RangeYd) break; // nearest first
|
||||
if (!InArea(c.Pos) || IsSkipped(c.Id, now) || !Plannable(c)) continue;
|
||||
if (!InArea(c.Pos) || IsSkipped(c.Id, now) || CellSkipped(c.Cell, now) || !Plannable(c)) continue;
|
||||
asked++;
|
||||
var w = PlanWalk(me, meCell, c.Pos, c.Cell);
|
||||
var p = w.P;
|
||||
|
|
@ -377,7 +413,9 @@ internal sealed class OutdoorHunt
|
|||
/// <summary>The chosen monster becomes the target: walked to, or stood by when the walk's end is already here.</summary>
|
||||
private Decision Go(DateTime now, Candidate c, HuntWalk w, string pack = "")
|
||||
{
|
||||
if (TargetId != c.Id) NewTarget();
|
||||
TargetId = c.Id;
|
||||
_targetName = c.Name;
|
||||
_plannedTo = c.Pos;
|
||||
_lastPlan = now;
|
||||
Note = NextNote(c, w, pack);
|
||||
|
|
@ -393,7 +431,7 @@ internal sealed class OutdoorHunt
|
|||
/// <summary>Nothing to hunt: wait where it is (no walk back to the start: Tom 10-23, "it shouldn't bother").</summary>
|
||||
private Decision Waiting()
|
||||
{
|
||||
string wait = $"nothing within Hunt Range ({RangeYd:0} yd){(RadiusYd > 0 ? $" inside Hunt Radius ({RadiusYd:0} yd)" : "")}: waiting here";
|
||||
string wait = $"nothing within Hunt Range ({RangeYd:0} yd){(RadiusYd > 0 ? $" inside Hunt Radius ({RadiusYd:0} yd)" : "")}{(Fence != null ? " inside the fence" : "")}: waiting here";
|
||||
if (_note != wait) Note = wait;
|
||||
return new Decision(Act.Idle);
|
||||
}
|
||||
|
|
@ -415,7 +453,7 @@ internal sealed class OutdoorHunt
|
|||
foreach (var c in candidates)
|
||||
{
|
||||
if (c.Distance > RangeYd) break; // nearest first
|
||||
if (!InArea(c.Pos) || IsSkipped(c.Id, now) || !Plannable(c)) continue;
|
||||
if (!InArea(c.Pos) || IsSkipped(c.Id, now) || CellSkipped(c.Cell, now) || !Plannable(c)) continue;
|
||||
_eligible.Add(c);
|
||||
if (_eligible.Count >= MaxPackCandidates) break;
|
||||
}
|
||||
|
|
@ -621,7 +659,10 @@ internal sealed class OutdoorHunt
|
|||
return new Decision(Act.Walk, way, TargetId, Note);
|
||||
}
|
||||
|
||||
private bool InArea(Vec p) => RadiusYd <= 0 || p.FlatDistanceTo(Anchor) <= RadiusYd;
|
||||
private bool InArea(Vec p) => (RadiusYd <= 0 || p.FlatDistanceTo(Anchor) <= RadiusYd) && (Fence == null || Fence(p));
|
||||
|
||||
/// <summary>The hunt fence (RynthAiPlugin.HuntFence.cs): a monster it says no to is left out of the picks. Null: no fence.</summary>
|
||||
public Func<Vec, bool>? Fence { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The walk ends where the character stands already (within ArrivedYd, across): nothing to walk, whatever
|
||||
|
|
@ -632,7 +673,75 @@ internal sealed class OutdoorHunt
|
|||
|
||||
private bool Reaches(PathResult p, Vec goal) =>
|
||||
p.Corners.Count > 0 && (p.Status == PathStatus.Ok || (p.Status == PathStatus.Partial && p.Gap <= ReachYd))
|
||||
&& p.Length <= RangeYd * MaxWalkFactor && Math.Abs(EndRise(p, goal)) <= ReachRiseYd;
|
||||
&& p.Length <= RangeYd * MaxWalkFactor && !TooFarRound(p, goal) && Math.Abs(EndRise(p, goal)) <= ReachRiseYd
|
||||
&& WalkInFence(p) && !BySnag(p);
|
||||
|
||||
/// <summary>
|
||||
/// A walk longer than DetourFactor times the straight line to the monster, plus DetourSlackYd, is too far
|
||||
/// round for it. 2026-11-17 11:13:58, the fort Thread 3073: a Threadbound Rynthid Slayer 68 yd away got a
|
||||
/// 425 yd walk, up onto the fort's wall, where the character stuck on a piece of wall for 90 s and then died
|
||||
/// ("It's running into a small piece of fort wall, it did climb the wall to find a monster").
|
||||
/// </summary>
|
||||
public double DetourFactor { get; set; } = 3;
|
||||
public double DetourSlackYd { get; set; } = 60;
|
||||
private bool TooFarRound(PathResult p, Vec goal) => p.Length > DetourFactor * _meNow.DistanceTo(goal) + DetourSlackYd;
|
||||
|
||||
// ── Snags: where navigation stuck on a hunt walk again and again ───────────────────────────────
|
||||
// RynthNav's map doesn't hold every obstacle (a piece of the fort wall in Thread 3073: "RynthNav sees a
|
||||
// clear straight line (the snag isn't on its map)"), and the hunt planned the same walk through it again
|
||||
// every 8 s while navigation's stuck escapes went round for 90 s. The plugin tells the hunt (Snagged) when
|
||||
// a spot has stuck the walk StuckSpotRepeat times: the monster walked to is left out, and no walk passes
|
||||
// within SnagYd of the spot for SnagSec.
|
||||
|
||||
public double SnagYd { get; set; } = 4;
|
||||
public double SnagSec { get; set; } = 600;
|
||||
private readonly List<(Vec At, DateTime Until)> _snags = new();
|
||||
private string _targetName = "";
|
||||
internal int SnagCount => _snags.Count;
|
||||
|
||||
/// <summary>Navigation stuck at <paramref name="at"/> again and again on the hunt's walk.</summary>
|
||||
public void Snagged(DateTime now, Vec at)
|
||||
{
|
||||
_snags.RemoveAll(s => s.Until <= now);
|
||||
int i = _snags.FindIndex(s => s.At.FlatDistanceTo(at) <= SnagYd && Math.Abs(s.At.Z - at.Z) <= ReachRiseYd);
|
||||
if (i >= 0) _snags[i] = (_snags[i].At, now.AddSeconds(SnagSec));
|
||||
else _snags.Add((at, now.AddSeconds(SnagSec)));
|
||||
if (TargetId == 0) return;
|
||||
Skip(TargetId, now);
|
||||
Note = $"stuck at {at.X:0},{at.Y:0} again and again on the walk to '{_targetName}': it is left out for {SkipSec:0} s, "
|
||||
+ $"and no walk goes by that spot for {SnagSec / 60:0} min";
|
||||
TargetId = 0;
|
||||
_arrivedSince = DateTime.MinValue;
|
||||
NewTarget();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The walk passes within SnagYd of a snag (at its height). Not one at the walk's start: standing at a
|
||||
/// snag, every walk would start "by" it, and the hunt would stand there.
|
||||
/// </summary>
|
||||
private bool BySnag(PathResult p)
|
||||
{
|
||||
if (_snags.Count == 0) return false;
|
||||
Vec a = _meNow;
|
||||
foreach (var b in p.Corners)
|
||||
{
|
||||
foreach (var (s, until) in _snags)
|
||||
{
|
||||
if (until <= _now || s.FlatDistanceTo(_meNow) <= SnagYd) continue;
|
||||
double dx = b.X - a.X, dy = b.Y - a.Y, l2 = dx * dx + dy * dy;
|
||||
double t = l2 < 1e-9 ? 0 : Math.Clamp(((s.X - a.X) * dx + (s.Y - a.Y) * dy) / l2, 0, 1);
|
||||
var q = new Vec(a.X + dx * t, a.Y + dy * t, a.Z + (b.Z - a.Z) * t);
|
||||
if (q.FlatDistanceTo(s) <= SnagYd && Math.Abs(q.Z - s.Z) <= ReachRiseYd) return true;
|
||||
}
|
||||
a = b;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>The hunt fence's walk test (RynthAiPlugin.HuntFence.cs): false when the walk's corners go out past
|
||||
/// what it allows (a monster inside the fence with the way to it round the outside). Null: any walk.</summary>
|
||||
public Func<Vec, IReadOnlyList<Vec>, bool>? WalkFence { get; set; }
|
||||
private bool WalkInFence(PathResult p) => WalkFence == null || WalkFence(_meNow, p.Corners);
|
||||
|
||||
/// <summary>How far the monster is above (+) or below (-) the walk's end.</summary>
|
||||
private static double EndRise(PathResult p, Vec goal) => p.Corners.Count > 0 ? goal.Z - p.Corners[^1].Z : 0;
|
||||
|
|
@ -645,6 +754,12 @@ internal sealed class OutdoorHunt
|
|||
: $"{-EndRise(p, goal):0} yd below the walk's end",
|
||||
_ when p.Corners.Count > 0 && p.Length > RangeYd * MaxWalkFactor
|
||||
&& (p.Status == PathStatus.Ok || p.Status == PathStatus.Partial) => $"a {p.Length:0} yd walk, too far round",
|
||||
_ when p.Corners.Count > 0 && TooFarRound(p, goal)
|
||||
&& (p.Status == PathStatus.Ok || p.Status == PathStatus.Partial) => $"a {p.Length:0} yd walk, too far round for one {_meNow.DistanceTo(goal):0} yd away",
|
||||
_ when p.Corners.Count > 0 && !WalkInFence(p)
|
||||
&& (p.Status == PathStatus.Ok || p.Status == PathStatus.Partial) => "the walk goes out past the fence",
|
||||
_ when p.Corners.Count > 0 && BySnag(p)
|
||||
&& (p.Status == PathStatus.Ok || p.Status == PathStatus.Partial) => "the walk goes by a spot it got stuck at",
|
||||
_ when why.Length > 0 => why,
|
||||
PathStatus.Partial => $"the walk ends {p.Gap:0} yd short",
|
||||
PathStatus.NoPath => "no walkable way",
|
||||
|
|
|
|||
734
Plugins/RynthCore.Plugin.RynthAi/PlacedSolid.cs
Normal file
734
Plugins/RynthCore.Plugin.RynthAi/PlacedSolid.cs
Normal file
|
|
@ -0,0 +1,734 @@
|
|||
// PlacedSolid: the space a placed object fills, column by column (2026-11-18).
|
||||
//
|
||||
// The dungeon map's placed objects (an altar, a table, a statue: the EnvCells' stabs, as physics triangles)
|
||||
// were cut at three heights over their floor (0.5, 1.0 and 1.5 m). What lay between or above the cuts was
|
||||
// missed: the tops of the 0x01003694 tables (1.5 of their 2.4 m2), the 0x020003B3 rails at 0.79-0.92 m,
|
||||
// beams between 1.5 m and the body's top. And a cut that came out as an open line (a lone plane, a fence, a
|
||||
// web) read as filled on one side: 0x02001A58 was 31.5 m2 inside against an 11.3 m2 real footprint.
|
||||
//
|
||||
// This is the object as solid columns instead: the ground under it in 0.1 m squares, each square with the
|
||||
// height ranges where something is. They come from
|
||||
// - a cross-section every 0.1 m up the object: a closed one (a box's sides cut round) is filled, an open
|
||||
// one (a plane, a web's strands) counts as its line only and is never filled;
|
||||
// - every sloped or flat polygon at its own height over each square it covers (a table top, a ramp).
|
||||
// Something is in a body's way where its column has anything between the body's feet + 0.45 and its top.
|
||||
//
|
||||
// A model is made once per setup and kept: the same object placed again, turned about the vertical and moved,
|
||||
// is the same solid in its own frame, so later copies only turn a query point into that frame. A copy that is
|
||||
// tilted or scaled otherwise (the triangles don't match once turned) gets a model of its own.
|
||||
//
|
||||
// Any triangle set is taken, closed or open; the frame's axes follow the object's own edges (the commonest
|
||||
// edge direction), so a box's sides fall along the columns however it is turned in the world.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthAi.Raycasting;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
/// <summary>One object's solid model, in its own frame (metres from its first vertex, turned by <see cref="Yaw"/>).</summary>
|
||||
internal sealed class PlacedSolid
|
||||
{
|
||||
/// <summary>Column size and cross-section spacing (metres).</summary>
|
||||
internal const double Res = 0.1;
|
||||
// Bigger objects than this many columns (50 x 50 m) get coarser columns; taller than this many sections, coarser sections.
|
||||
private const int MaxColumns = 250_000, MaxLevels = 1200;
|
||||
// A copy is the same model when every vertex is within this of the model's, once turned and moved.
|
||||
private const double MatchTolerance = 0.02;
|
||||
// A walkable face (WalkableNz either way up) is exposed when nothing of the object is this far over it.
|
||||
private const double ExposedFrom = 0.15, ExposedTo = 0.6;
|
||||
|
||||
/// <summary>The frame's turn from world east, for the copy it was made from (radians).</summary>
|
||||
public readonly double Yaw;
|
||||
/// <summary>Column size (<see cref="Res"/> unless the object is huge).</summary>
|
||||
public readonly double Step;
|
||||
/// <summary>The raster's corner in the model frame, and its size in columns (with one empty column round).</summary>
|
||||
public readonly double U0, V0;
|
||||
public readonly int NU, NV;
|
||||
/// <summary>Its lowest and highest point (model frame: height over the first vertex).</summary>
|
||||
public readonly double MinW, MaxW;
|
||||
/// <summary>A walkable face at its top (a bench's seat, a dais), for the step-over class.</summary>
|
||||
public readonly bool WalkableTop;
|
||||
|
||||
private readonly int[] _start; // per column, its first range in _ranges (NU * NV + 1)
|
||||
private readonly float[] _ranges; // lo, hi pairs, model frame
|
||||
private readonly float[] _ref; // the triangles' vertices in the model frame (u, v, w), to match a copy
|
||||
private readonly int _far; // the vertex farthest from the first, across: sets a copy's turn
|
||||
private readonly int[] _walkFaces; // exposed walkable faces (triangle index)
|
||||
private readonly float[] _walkArea;
|
||||
private readonly Dictionary<long, PlacedBand> _bands = new();
|
||||
|
||||
public int VertexCount => _ref.Length / 3;
|
||||
public int WalkFaceCount => _walkFaces.Length;
|
||||
internal double WalkFaceArea(int k) => _walkArea[k];
|
||||
|
||||
/// <summary>Roughly what the model holds in memory (bytes).</summary>
|
||||
public long Bytes => 160 + 4L * (_start.Length + _ranges.Length + _ref.Length + _walkFaces.Length + _walkArea.Length);
|
||||
|
||||
// ── Cache ───────────────────────────────────────────────────────────────
|
||||
|
||||
private static readonly Dictionary<uint, List<PlacedSolid>> _cache = new();
|
||||
private static long _cacheBytes;
|
||||
// Past this the cache starts again (a long session through many dungeons): the maps made keep their models.
|
||||
private const long CacheBytesMax = 64L << 20;
|
||||
|
||||
internal static int CachedModels { get { lock (_cache) { int n = 0; foreach (var l in _cache.Values) n += l.Count; return n; } } }
|
||||
internal static long CachedBytes { get { lock (_cache) return _cacheBytes; } }
|
||||
internal static void ClearCache() { lock (_cache) { _cache.Clear(); _cacheBytes = 0; } }
|
||||
|
||||
/// <summary>
|
||||
/// The object <paramref name="setup"/> as placed: its triangles (world metres, three vertices a triangle) as a
|
||||
/// model turned and moved into place, the model made now or taken from the cache. Null for fewer than one triangle.
|
||||
/// </summary>
|
||||
internal static PlacedShape? Place(uint setup, Vector3[] tris)
|
||||
{
|
||||
if (tris == null || tris.Length < 3) return null;
|
||||
int n = tris.Length - tris.Length % 3;
|
||||
double ax = tris[0].X, ay = tris[0].Y, az = tris[0].Z;
|
||||
double minX = double.MaxValue, minY = double.MaxValue, minZ = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue, maxZ = double.MinValue;
|
||||
for (int k = 0; k < n; k++)
|
||||
{
|
||||
var p = tris[k];
|
||||
if (p.X < minX) minX = p.X; if (p.X > maxX) maxX = p.X;
|
||||
if (p.Y < minY) minY = p.Y; if (p.Y > maxY) maxY = p.Y;
|
||||
if (p.Z < minZ) minZ = p.Z; if (p.Z > maxZ) maxZ = p.Z;
|
||||
}
|
||||
PlacedSolid? model = null;
|
||||
double yaw = 0;
|
||||
lock (_cache)
|
||||
{
|
||||
if (_cache.TryGetValue(setup, out var list))
|
||||
foreach (var m in list)
|
||||
if (m.VertexCount == n && m.Match(tris, n, ax, ay, az, out yaw)) { model = m; break; }
|
||||
}
|
||||
if (model == null)
|
||||
{
|
||||
model = Build(tris, n, ax, ay, az);
|
||||
yaw = model.Yaw;
|
||||
lock (_cache)
|
||||
{
|
||||
if (_cacheBytes + model.Bytes > CacheBytesMax) { _cache.Clear(); _cacheBytes = 0; }
|
||||
if (!_cache.TryGetValue(setup, out var list)) _cache[setup] = list = new List<PlacedSolid>(1);
|
||||
list.Add(model);
|
||||
_cacheBytes += model.Bytes;
|
||||
}
|
||||
}
|
||||
return new PlacedShape(model, ax, ay, az, yaw, minX, minY, minZ, maxX, maxY, maxZ);
|
||||
}
|
||||
|
||||
// The copy's turn from the far vertex, then every vertex checked.
|
||||
private bool Match(Vector3[] t, int n, double ax, double ay, double az, out double yaw)
|
||||
{
|
||||
double rx = t[_far].X - ax, ry = t[_far].Y - ay;
|
||||
double fu = _ref[3 * _far], fv = _ref[3 * _far + 1];
|
||||
yaw = fu * fu + fv * fv > 0.0025 && rx * rx + ry * ry > 0.0025 ? Math.Atan2(ry, rx) - Math.Atan2(fv, fu) : Yaw;
|
||||
double c = Math.Cos(yaw), s = Math.Sin(yaw);
|
||||
for (int k = 0; k < n; k++)
|
||||
{
|
||||
double dx = t[k].X - ax, dy = t[k].Y - ay;
|
||||
if (Math.Abs(dx * c + dy * s - _ref[3 * k]) > MatchTolerance
|
||||
|| Math.Abs(-dx * s + dy * c - _ref[3 * k + 1]) > MatchTolerance
|
||||
|| Math.Abs(t[k].Z - az - _ref[3 * k + 2]) > MatchTolerance) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static PlacedSolid Build(Vector3[] t, int n, double ax, double ay, double az)
|
||||
{
|
||||
// The frame follows the commonest horizontal edge direction (mod 90 degrees): a box's sides along the columns.
|
||||
double cs = 0, sn = 0;
|
||||
for (int i = 0; i + 2 < n; i += 3)
|
||||
for (int e = 0; e < 3; e++)
|
||||
{
|
||||
var p = t[i + e]; var q = t[i + (e + 1) % 3];
|
||||
double dx = q.X - p.X, dy = q.Y - p.Y, h = Math.Sqrt(dx * dx + dy * dy);
|
||||
if (h < 1e-4) continue;
|
||||
double c = dx / h, s = dy / h, c2 = c * c - s * s, s2 = 2 * c * s;
|
||||
cs += h * (c2 * c2 - s2 * s2);
|
||||
sn += h * 2 * c2 * s2;
|
||||
}
|
||||
double yaw = cs * cs + sn * sn > 1e-12 ? Math.Atan2(sn, cs) / 4 : 0;
|
||||
double co = Math.Cos(yaw), si = Math.Sin(yaw);
|
||||
var refv = new float[n * 3];
|
||||
for (int k = 0; k < n; k++)
|
||||
{
|
||||
double dx = t[k].X - ax, dy = t[k].Y - ay;
|
||||
refv[3 * k] = (float)(dx * co + dy * si);
|
||||
refv[3 * k + 1] = (float)(-dx * si + dy * co);
|
||||
refv[3 * k + 2] = (float)(t[k].Z - az);
|
||||
}
|
||||
return new PlacedSolid(refv, yaw);
|
||||
}
|
||||
|
||||
// ── Making the columns ──────────────────────────────────────────────────
|
||||
|
||||
private readonly struct Piece : IComparable<Piece>
|
||||
{
|
||||
public readonly int Col; public readonly float Lo, Hi;
|
||||
public Piece(int col, float lo, float hi) { Col = col; Lo = lo; Hi = hi; }
|
||||
public int CompareTo(Piece o) => Col != o.Col ? Col.CompareTo(o.Col) : Lo.CompareTo(o.Lo);
|
||||
}
|
||||
|
||||
private PlacedSolid(float[] refv, double yaw)
|
||||
{
|
||||
_ref = refv;
|
||||
Yaw = yaw;
|
||||
int nv = refv.Length / 3, nt = nv / 3;
|
||||
double minU = double.MaxValue, minV = double.MaxValue, minW = double.MaxValue, maxU = double.MinValue, maxV = double.MinValue, maxW = double.MinValue, far = -1;
|
||||
for (int k = 0; k < nv; k++)
|
||||
{
|
||||
double u = refv[3 * k], v = refv[3 * k + 1], w = refv[3 * k + 2];
|
||||
minU = Math.Min(minU, u); maxU = Math.Max(maxU, u);
|
||||
minV = Math.Min(minV, v); maxV = Math.Max(maxV, v);
|
||||
minW = Math.Min(minW, w); maxW = Math.Max(maxW, w);
|
||||
if (u * u + v * v > far) { far = u * u + v * v; _far = k; }
|
||||
}
|
||||
MinW = minW; MaxW = maxW;
|
||||
double step = Res;
|
||||
while (((maxU - minU) / step + 3) * ((maxV - minV) / step + 3) > MaxColumns) step *= 2;
|
||||
Step = step;
|
||||
U0 = Math.Floor(minU / step) * step - step;
|
||||
V0 = Math.Floor(minV / step) * step - step;
|
||||
NU = (int)Math.Floor((maxU - U0) / step) + 2;
|
||||
NV = (int)Math.Floor((maxV - V0) / step) + 2;
|
||||
int ncol = NU * NV;
|
||||
var pieces = new List<Piece>();
|
||||
|
||||
// Cross-sections at z_k = (k + 0.5) * lstep, the ones with a vertex under and one at or over them.
|
||||
double lstep = step;
|
||||
if ((maxW - minW) / lstep > MaxLevels) lstep = (maxW - minW) / MaxLevels;
|
||||
int kFirst = (int)Math.Floor(minW / lstep - 0.5) + 1, kLast = (int)Math.Floor(maxW / lstep - 0.5);
|
||||
int nl = Math.Max(0, kLast - kFirst + 1);
|
||||
if (nl > 0)
|
||||
{
|
||||
var off = new int[nl + 1];
|
||||
void Span(int tri, out int k0, out int k1)
|
||||
{
|
||||
double z0 = Math.Min(refv[9 * tri + 2], Math.Min(refv[9 * tri + 5], refv[9 * tri + 8]));
|
||||
double z1 = Math.Max(refv[9 * tri + 2], Math.Max(refv[9 * tri + 5], refv[9 * tri + 8]));
|
||||
k0 = Math.Max(kFirst, (int)Math.Floor(z0 / lstep - 0.5) + 1);
|
||||
k1 = Math.Min(kLast, (int)Math.Floor(z1 / lstep - 0.5));
|
||||
}
|
||||
for (int tri = 0; tri < nt; tri++)
|
||||
{
|
||||
Span(tri, out int k0, out int k1);
|
||||
for (int k = k0; k <= k1; k++) off[k - kFirst + 1]++;
|
||||
}
|
||||
for (int l = 0; l < nl; l++) off[l + 1] += off[l];
|
||||
var byLevel = new int[off[nl]];
|
||||
var fillAt = (int[])off.Clone();
|
||||
for (int tri = 0; tri < nt; tri++)
|
||||
{
|
||||
Span(tri, out int k0, out int k1);
|
||||
for (int k = k0; k <= k1; k++) byLevel[fillAt[k - kFirst]++] = tri;
|
||||
}
|
||||
|
||||
var runLo = new float[ncol];
|
||||
var runHi = new float[ncol];
|
||||
for (int c = 0; c < ncol; c++) runHi[c] = float.NaN;
|
||||
var stamp = new int[ncol];
|
||||
var marked = new List<int>();
|
||||
var section = new Section(this);
|
||||
for (int l = 0; l < nl; l++)
|
||||
{
|
||||
double z = (kFirst + l + 0.5) * lstep;
|
||||
section.Begin(l + 1, stamp, marked);
|
||||
for (int q = off[l]; q < off[l + 1]; q++) section.Cut(refv, byLevel[q], z);
|
||||
section.Mark();
|
||||
float zf = (float)z;
|
||||
foreach (int c in marked)
|
||||
{
|
||||
if (!float.IsNaN(runHi[c]) && zf - runHi[c] <= lstep * 1.01) { runHi[c] = zf; continue; }
|
||||
if (!float.IsNaN(runHi[c])) pieces.Add(new Piece(c, runLo[c], runHi[c]));
|
||||
runLo[c] = runHi[c] = zf;
|
||||
}
|
||||
}
|
||||
for (int c = 0; c < ncol; c++)
|
||||
if (!float.IsNaN(runHi[c])) pieces.Add(new Piece(c, runLo[c], runHi[c]));
|
||||
}
|
||||
|
||||
// Sloped and flat polygons at their own height over every column centre they cover.
|
||||
for (int tri = 0; tri < nt; tri++)
|
||||
{
|
||||
double au = refv[9 * tri], av = refv[9 * tri + 1], aw = refv[9 * tri + 2];
|
||||
double bu = refv[9 * tri + 3], bv = refv[9 * tri + 4], bw = refv[9 * tri + 5];
|
||||
double cu = refv[9 * tri + 6], cv = refv[9 * tri + 7], cw = refv[9 * tri + 8];
|
||||
double d = (bv - cv) * (au - cu) + (cu - bu) * (av - cv);
|
||||
if (Math.Abs(d) < 1e-9) continue; // upright: its cross-sections have it
|
||||
int i0 = Math.Max(0, (int)Math.Ceiling((Math.Min(au, Math.Min(bu, cu)) - U0) / step - 0.5));
|
||||
int i1 = Math.Min(NU - 1, (int)Math.Floor((Math.Max(au, Math.Max(bu, cu)) - U0) / step - 0.5));
|
||||
int j0 = Math.Max(0, (int)Math.Ceiling((Math.Min(av, Math.Min(bv, cv)) - V0) / step - 0.5));
|
||||
int j1 = Math.Min(NV - 1, (int)Math.Floor((Math.Max(av, Math.Max(bv, cv)) - V0) / step - 0.5));
|
||||
for (int j = j0; j <= j1; j++)
|
||||
{
|
||||
double y = V0 + (j + 0.5) * step;
|
||||
for (int i = i0; i <= i1; i++)
|
||||
{
|
||||
double x = U0 + (i + 0.5) * step;
|
||||
double l1 = ((bv - cv) * (x - cu) + (cu - bu) * (y - cv)) / d;
|
||||
double l2 = ((cv - av) * (x - cu) + (au - cu) * (y - cv)) / d;
|
||||
double l3 = 1 - l1 - l2;
|
||||
if (l1 < -1e-9 || l2 < -1e-9 || l3 < -1e-9) continue;
|
||||
float w = (float)(l1 * aw + l2 * bw + l3 * cw);
|
||||
pieces.Add(new Piece(j * NU + i, w, w));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Each column's pieces sorted and joined where less than a section apart (a body can't be between).
|
||||
pieces.Sort();
|
||||
_start = new int[ncol + 1];
|
||||
var ranges = new List<float>(pieces.Count);
|
||||
double gap = lstep * 1.01 + 1e-4;
|
||||
int at = 0;
|
||||
for (int c = 0; c < ncol; c++)
|
||||
{
|
||||
_start[c] = ranges.Count / 2;
|
||||
if (at >= pieces.Count || pieces[at].Col != c) continue;
|
||||
float lo = pieces[at].Lo, hi = pieces[at].Hi;
|
||||
for (at++; at < pieces.Count && pieces[at].Col == c; at++)
|
||||
{
|
||||
if (pieces[at].Lo <= hi + gap) { if (pieces[at].Hi > hi) hi = pieces[at].Hi; continue; }
|
||||
ranges.Add(lo); ranges.Add(hi);
|
||||
lo = pieces[at].Lo; hi = pieces[at].Hi;
|
||||
}
|
||||
ranges.Add(lo); ranges.Add(hi);
|
||||
}
|
||||
_start[ncol] = ranges.Count / 2;
|
||||
_ranges = ranges.ToArray();
|
||||
|
||||
// Walkable faces (steep enough to stand on, either way up) with nothing of the object just over them.
|
||||
var walk = new List<int>();
|
||||
var walkArea = new List<float>();
|
||||
double topArea = 0;
|
||||
for (int tri = 0; tri < nt; tri++)
|
||||
{
|
||||
double au = refv[9 * tri], av = refv[9 * tri + 1], aw = refv[9 * tri + 2];
|
||||
double bu = refv[9 * tri + 3] - au, bv = refv[9 * tri + 4] - av, bw = refv[9 * tri + 5] - aw;
|
||||
double cu = refv[9 * tri + 6] - au, cv = refv[9 * tri + 7] - av, cw = refv[9 * tri + 8] - aw;
|
||||
double nx = bv * cw - bw * cv, ny = bw * cu - bu * cw, nz = bu * cv - bv * cu;
|
||||
double len = Math.Sqrt(nx * nx + ny * ny + nz * nz);
|
||||
if (len < 1e-9 || Math.Abs(nz) / len < DungeonGeometry.WalkableNz) continue;
|
||||
double mu = au + (bu + cu) / 3, mv = av + (bv + cv) / 3, mw = aw + (bw + cw) / 3;
|
||||
if (SolidAt(mu, mv, mw + ExposedFrom, mw + ExposedTo)) continue;
|
||||
walk.Add(tri);
|
||||
walkArea.Add((float)(Math.Abs(nz) / 2));
|
||||
double top = Math.Max(aw, Math.Max(aw + bw, aw + cw));
|
||||
if (top >= maxW - 0.1) topArea += Math.Abs(nz) / 2;
|
||||
}
|
||||
_walkFaces = walk.ToArray();
|
||||
_walkArea = walkArea.ToArray();
|
||||
WalkableTop = topArea >= 0.05;
|
||||
}
|
||||
|
||||
// One cross-section: its segments, which of them close round (filled) and which are open lines.
|
||||
private sealed class Section
|
||||
{
|
||||
private readonly PlacedSolid _m;
|
||||
private readonly List<double> _seg = new(); // u0, v0, u1, v1 per segment
|
||||
private readonly List<int> _segNode = new(); // the two node ids per segment
|
||||
private readonly Dictionary<long, int> _nodeAt = new();
|
||||
private readonly List<double> _nodeU = new(), _nodeV = new();
|
||||
private readonly List<int> _parent = new(), _degree = new();
|
||||
private readonly List<double> _cross = new();
|
||||
private int _stampValue;
|
||||
private int[] _stamp = null!;
|
||||
private List<int> _marked = null!;
|
||||
private const double NodeSnap = 1e-3; // ends this close are one point (a T-joint's rounding)
|
||||
|
||||
public Section(PlacedSolid m) { _m = m; }
|
||||
|
||||
public void Begin(int stampValue, int[] stamp, List<int> marked)
|
||||
{
|
||||
_stampValue = stampValue; _stamp = stamp; _marked = marked;
|
||||
marked.Clear();
|
||||
_seg.Clear(); _segNode.Clear(); _nodeAt.Clear(); _nodeU.Clear(); _nodeV.Clear(); _parent.Clear(); _degree.Clear();
|
||||
}
|
||||
|
||||
// Where triangle `tri` crosses z (a vertex at z counts as over it). Each edge is interpolated from its lower
|
||||
// end, so the two triangles sharing an edge meet at the very same point.
|
||||
public void Cut(float[] r, int tri, double z)
|
||||
{
|
||||
double au = 0, av = 0, bu = 0, bv = 0;
|
||||
int n = 0;
|
||||
for (int e = 0; e < 3; e++)
|
||||
{
|
||||
int p = 9 * tri + 3 * e, q = 9 * tri + 3 * ((e + 1) % 3);
|
||||
bool pUp = r[p + 2] >= z, qUp = r[q + 2] >= z;
|
||||
if (pUp == qUp) continue;
|
||||
if (pUp) (p, q) = (q, p);
|
||||
double t = (z - r[p + 2]) / (r[q + 2] - r[p + 2]);
|
||||
double u = r[p] + (r[q] - r[p]) * t, v = r[p + 1] + (r[q + 1] - r[p + 1]) * t;
|
||||
if (n == 0) { au = u; av = v; } else { bu = u; bv = v; }
|
||||
n++;
|
||||
}
|
||||
if (n != 2 || (au - bu) * (au - bu) + (av - bv) * (av - bv) < 1e-10) return;
|
||||
int a = Node(au, av), b = Node(bu, bv);
|
||||
if (a == b) return;
|
||||
_seg.Add(au); _seg.Add(av); _seg.Add(bu); _seg.Add(bv);
|
||||
_segNode.Add(a); _segNode.Add(b);
|
||||
_degree[a]++; _degree[b]++;
|
||||
Union(a, b);
|
||||
}
|
||||
|
||||
private int Node(double u, double v)
|
||||
{
|
||||
long qu = (long)Math.Floor(u / NodeSnap), qv = (long)Math.Floor(v / NodeSnap);
|
||||
for (long du = -1; du <= 1; du++)
|
||||
for (long dv = -1; dv <= 1; dv++)
|
||||
if (_nodeAt.TryGetValue(Key(qu + du, qv + dv), out int id)
|
||||
&& Math.Abs(_nodeU[id] - u) <= NodeSnap && Math.Abs(_nodeV[id] - v) <= NodeSnap) return id;
|
||||
int nid = _nodeU.Count;
|
||||
_nodeU.Add(u); _nodeV.Add(v); _parent.Add(nid); _degree.Add(0);
|
||||
_nodeAt[Key(qu, qv)] = nid;
|
||||
return nid;
|
||||
}
|
||||
|
||||
private static long Key(long a, long b) => (a << 32) ^ (b & 0xFFFFFFFFL);
|
||||
|
||||
private int Find(int a)
|
||||
{
|
||||
while (_parent[a] != a) { _parent[a] = _parent[_parent[a]]; a = _parent[a]; }
|
||||
return a;
|
||||
}
|
||||
|
||||
private void Union(int a, int b) { int ra = Find(a), rb = Find(b); if (ra != rb) _parent[ra] = rb; }
|
||||
|
||||
// Closed pieces filled (each on its own, so two overlapping parts don't cancel out), open ones drawn as lines.
|
||||
public void Mark()
|
||||
{
|
||||
int ns = _segNode.Count / 2;
|
||||
if (ns == 0) return;
|
||||
var open = new HashSet<int>();
|
||||
for (int i = 0; i < _degree.Count; i++) if ((_degree[i] & 1) != 0) open.Add(Find(i));
|
||||
var byComp = new Dictionary<int, List<int>>();
|
||||
for (int s = 0; s < ns; s++)
|
||||
{
|
||||
int root = Find(_segNode[2 * s]);
|
||||
if (!byComp.TryGetValue(root, out var l)) byComp[root] = l = new List<int>();
|
||||
l.Add(s);
|
||||
}
|
||||
foreach (var (root, segs) in byComp)
|
||||
{
|
||||
if (open.Contains(root)) { foreach (int s in segs) Line(s); continue; }
|
||||
double u0 = double.MaxValue, v0 = double.MaxValue, u1 = double.MinValue, v1 = double.MinValue;
|
||||
foreach (int s in segs)
|
||||
{
|
||||
u0 = Math.Min(u0, Math.Min(_seg[4 * s], _seg[4 * s + 2])); u1 = Math.Max(u1, Math.Max(_seg[4 * s], _seg[4 * s + 2]));
|
||||
v0 = Math.Min(v0, Math.Min(_seg[4 * s + 1], _seg[4 * s + 3])); v1 = Math.Max(v1, Math.Max(_seg[4 * s + 1], _seg[4 * s + 3]));
|
||||
}
|
||||
int filled = Fill(segs, v0, v1);
|
||||
// A closed piece thinner than two columns (a rail, a thin slab's edge) may cover no column centre: its line too.
|
||||
if (filled == 0 || Math.Min(u1 - u0, v1 - v0) < 2 * _m.Step) foreach (int s in segs) Line(s);
|
||||
}
|
||||
}
|
||||
|
||||
// Even-odd over the piece's own segments, by column centre; how many centres are inside.
|
||||
private int Fill(List<int> segs, double vMin, double vMax)
|
||||
{
|
||||
var m = _m;
|
||||
int count = 0;
|
||||
int j0 = Math.Max(0, (int)Math.Ceiling((vMin - m.V0) / m.Step - 0.5)), j1 = Math.Min(m.NV - 1, (int)Math.Floor((vMax - m.V0) / m.Step - 0.5));
|
||||
for (int j = j0; j <= j1; j++)
|
||||
{
|
||||
double vc = m.V0 + (j + 0.5) * m.Step;
|
||||
_cross.Clear();
|
||||
foreach (int s in segs)
|
||||
{
|
||||
double sv0 = _seg[4 * s + 1], sv1 = _seg[4 * s + 3];
|
||||
if ((sv0 > vc) == (sv1 > vc)) continue;
|
||||
double su0 = _seg[4 * s], su1 = _seg[4 * s + 2];
|
||||
_cross.Add(su0 + (vc - sv0) * (su1 - su0) / (sv1 - sv0));
|
||||
}
|
||||
if (_cross.Count < 2) continue;
|
||||
_cross.Sort();
|
||||
for (int c = 0; c + 1 < _cross.Count; c += 2)
|
||||
{
|
||||
int i0 = Math.Max(0, (int)Math.Ceiling((_cross[c] - m.U0) / m.Step - 0.5));
|
||||
int i1 = Math.Min(m.NU - 1, (int)Math.Floor((_cross[c + 1] - m.U0) / m.Step - 0.5));
|
||||
for (int i = i0; i <= i1; i++) { Mark(j * m.NU + i); count++; }
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
// Every column the segment passes through (sampled at a quarter column).
|
||||
private void Line(int s)
|
||||
{
|
||||
var m = _m;
|
||||
double u0 = _seg[4 * s], v0 = _seg[4 * s + 1], u1 = _seg[4 * s + 2], v1 = _seg[4 * s + 3];
|
||||
double len = Math.Sqrt((u1 - u0) * (u1 - u0) + (v1 - v0) * (v1 - v0));
|
||||
int n = Math.Max(1, (int)Math.Ceiling(len / (m.Step * 0.25)));
|
||||
for (int k = 0; k <= n; k++)
|
||||
{
|
||||
double u = u0 + (u1 - u0) * k / n, v = v0 + (v1 - v0) * k / n;
|
||||
int i = Math.Clamp((int)Math.Floor((u - m.U0) / m.Step), 0, m.NU - 1), j = Math.Clamp((int)Math.Floor((v - m.V0) / m.Step), 0, m.NV - 1);
|
||||
Mark(j * m.NU + i);
|
||||
}
|
||||
}
|
||||
|
||||
private void Mark(int c)
|
||||
{
|
||||
if (_stamp[c] == _stampValue) return;
|
||||
_stamp[c] = _stampValue;
|
||||
_marked.Add(c);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Queries (model frame) ───────────────────────────────────────────────
|
||||
|
||||
/// <summary>The column holding (u, v), or -1 off the raster.</summary>
|
||||
public int ColumnAt(double u, double v)
|
||||
{
|
||||
int i = (int)Math.Floor((u - U0) / Step), j = (int)Math.Floor((v - V0) / Step);
|
||||
return i < 0 || j < 0 || i >= NU || j >= NV ? -1 : j * NU + i;
|
||||
}
|
||||
|
||||
/// <summary>Something solid in the column at (u, v) between heights lo and hi (model frame).</summary>
|
||||
public bool SolidAt(double u, double v, double lo, double hi)
|
||||
{
|
||||
int c = ColumnAt(u, v);
|
||||
return c >= 0 && SolidIn(c, lo, hi);
|
||||
}
|
||||
|
||||
private bool SolidIn(int c, double lo, double hi)
|
||||
{
|
||||
for (int r = _start[c]; r < _start[c + 1]; r++)
|
||||
if (_ranges[2 * r] <= hi && _ranges[2 * r + 1] >= lo) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>The highest top of something solid in the column at (u, v) that is no higher than wMax (model
|
||||
/// frame), or -infinity: what a body could stand on there.</summary>
|
||||
public double TopAtMost(double u, double v, double wMax)
|
||||
{
|
||||
int c = ColumnAt(u, v);
|
||||
double best = double.NegativeInfinity;
|
||||
if (c < 0) return best;
|
||||
for (int r = _start[c]; r < _start[c + 1]; r++)
|
||||
if (_ranges[2 * r + 1] <= wMax && _ranges[2 * r + 1] > best) best = _ranges[2 * r + 1];
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>The centre of column c (model frame).</summary>
|
||||
public void ColumnCentre(int c, out double u, out double v)
|
||||
{
|
||||
u = U0 + (c % NU + 0.5) * Step;
|
||||
v = V0 + (c / NU + 0.5) * Step;
|
||||
}
|
||||
|
||||
/// <summary>Walkable face k's three corners (model frame).</summary>
|
||||
public void WalkFace(int k, out double au, out double av, out double aw, out double bu, out double bv, out double bw, out double cu, out double cv, out double cw)
|
||||
{
|
||||
int t = 9 * _walkFaces[k];
|
||||
au = _ref[t]; av = _ref[t + 1]; aw = _ref[t + 2];
|
||||
bu = _ref[t + 3]; bv = _ref[t + 4]; bw = _ref[t + 5];
|
||||
cu = _ref[t + 6]; cv = _ref[t + 7]; cw = _ref[t + 8];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What is in a body's way between heights lo and hi (model frame): the columns, and their outline as
|
||||
/// segments (model frame) round every filled patch. Remembered per band (copies on like floors share it).
|
||||
/// </summary>
|
||||
public PlacedBand Band(double lo, double hi)
|
||||
{
|
||||
long key = ((long)Math.Round(lo * 100) << 32) ^ (uint)(int)Math.Round(hi * 100);
|
||||
lock (_bands) if (_bands.TryGetValue(key, out var have)) return have;
|
||||
int ncol = NU * NV;
|
||||
var mask = new bool[ncol];
|
||||
var cells = new List<int>();
|
||||
for (int c = 0; c < ncol; c++)
|
||||
if (SolidIn(c, lo, hi)) { mask[c] = true; cells.Add(c); }
|
||||
var band = new PlacedBand(cells.ToArray(), cells.Count == 0 ? Array.Empty<double>() : Outline(mask), cells.Count * Step * Step);
|
||||
lock (_bands) if (_bands.Count < 32) _bands[key] = band;
|
||||
return band;
|
||||
}
|
||||
|
||||
// Marching squares over the column centres (each filled patch's edge runs half way between a filled centre and
|
||||
// an empty one: the patch's own side), chained into loops and thinned to within 0.4 of a column.
|
||||
private double[] Outline(bool[] mask)
|
||||
{
|
||||
int nu = NU;
|
||||
bool M(int i, int j) => mask[j * nu + i];
|
||||
int H(int i, int j) => 2 * (j * nu + i); // the edge between centres (i, j) and (i + 1, j)
|
||||
int Vt(int i, int j) => 2 * (j * nu + i) + 1; // between (i, j) and (i, j + 1)
|
||||
var link = new Dictionary<int, (int A, int B)>();
|
||||
void Link(int a, int b)
|
||||
{
|
||||
link[a] = link.TryGetValue(a, out var la) ? (la.A, b) : (b, -1);
|
||||
link[b] = link.TryGetValue(b, out var lb) ? (lb.A, a) : (a, -1);
|
||||
}
|
||||
for (int j = 0; j + 1 < NV; j++)
|
||||
for (int i = 0; i + 1 < NU; i++)
|
||||
{
|
||||
int code = (M(i, j) ? 1 : 0) | (M(i + 1, j) ? 2 : 0) | (M(i + 1, j + 1) ? 4 : 0) | (M(i, j + 1) ? 8 : 0);
|
||||
if (code == 0 || code == 15) continue;
|
||||
int b = H(i, j), r = Vt(i + 1, j), t = H(i, j + 1), l = Vt(i, j);
|
||||
switch (code)
|
||||
{
|
||||
case 1: case 14: Link(l, b); break;
|
||||
case 2: case 13: Link(b, r); break;
|
||||
case 3: case 12: Link(l, r); break;
|
||||
case 4: case 11: Link(r, t); break;
|
||||
case 6: case 9: Link(b, t); break;
|
||||
case 7: case 8: Link(t, l); break;
|
||||
case 5: Link(l, b); Link(r, t); break; // two corners apart: each its own loop
|
||||
case 10: Link(b, r); Link(t, l); break;
|
||||
}
|
||||
}
|
||||
void At(int id, out double u, out double v)
|
||||
{
|
||||
int idx = id >> 1, i = idx % nu, j = idx / nu;
|
||||
if ((id & 1) == 0) { u = U0 + (i + 1) * Step; v = V0 + (j + 0.5) * Step; }
|
||||
else { u = U0 + (i + 0.5) * Step; v = V0 + (j + 1) * Step; }
|
||||
}
|
||||
var outSegs = new List<double>();
|
||||
var done = new HashSet<int>();
|
||||
var loopU = new List<double>(); var loopV = new List<double>();
|
||||
foreach (int start in link.Keys)
|
||||
{
|
||||
if (done.Contains(start)) continue;
|
||||
loopU.Clear(); loopV.Clear();
|
||||
int prev = -1, cur = start;
|
||||
while (true)
|
||||
{
|
||||
done.Add(cur);
|
||||
At(cur, out double u, out double v);
|
||||
loopU.Add(u); loopV.Add(v);
|
||||
var (a, b) = link[cur];
|
||||
int next = a != prev ? a : b;
|
||||
if (next < 0 || next == start || done.Contains(next)) break;
|
||||
prev = cur; cur = next;
|
||||
}
|
||||
Thin(loopU, loopV, 0.4 * Step, outSegs);
|
||||
}
|
||||
return outSegs.ToArray();
|
||||
}
|
||||
|
||||
// A closed loop thinned (Douglas-Peucker on its two halves) and added as segments.
|
||||
private static void Thin(List<double> u, List<double> v, double tol, List<double> outSegs)
|
||||
{
|
||||
int n = u.Count;
|
||||
if (n < 2) return;
|
||||
if (n <= 3)
|
||||
{
|
||||
for (int i = 0; i < n; i++) { int k = (i + 1) % n; outSegs.Add(u[i]); outSegs.Add(v[i]); outSegs.Add(u[k]); outSegs.Add(v[k]); }
|
||||
return;
|
||||
}
|
||||
int far = 0; double best = -1;
|
||||
for (int i = 1; i < n; i++) { double d = (u[i] - u[0]) * (u[i] - u[0]) + (v[i] - v[0]) * (v[i] - v[0]); if (d > best) { best = d; far = i; } }
|
||||
var keep = new bool[n];
|
||||
keep[0] = keep[far] = true;
|
||||
void Dp(int a, int b) // indices along the loop, b > a (b may be n: the start again)
|
||||
{
|
||||
if (b - a < 2) return;
|
||||
double ax = u[a % n], ay = v[a % n], bx = u[b % n], by = v[b % n];
|
||||
double dx = bx - ax, dy = by - ay, len = Math.Sqrt(dx * dx + dy * dy);
|
||||
int at = -1; double worst = tol;
|
||||
for (int i = a + 1; i < b; i++)
|
||||
{
|
||||
double px = u[i % n] - ax, py = v[i % n] - ay;
|
||||
double d = len < 1e-12 ? Math.Sqrt(px * px + py * py) : Math.Abs(px * dy - py * dx) / len;
|
||||
if (d > worst) { worst = d; at = i; }
|
||||
}
|
||||
if (at < 0) return;
|
||||
keep[at % n] = true;
|
||||
Dp(a, at); Dp(at, b);
|
||||
}
|
||||
Dp(0, far); Dp(far, n);
|
||||
int first = -1, last = -1;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
if (!keep[i]) continue;
|
||||
if (first < 0) first = i;
|
||||
if (last >= 0) { outSegs.Add(u[last]); outSegs.Add(v[last]); outSegs.Add(u[i]); outSegs.Add(v[i]); }
|
||||
last = i;
|
||||
}
|
||||
if (first >= 0 && last != first) { outSegs.Add(u[last]); outSegs.Add(v[last]); outSegs.Add(u[first]); outSegs.Add(v[first]); }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What of an object is in a body's way at one band: its columns, outline (u0, v0, u1, v1 per
|
||||
/// segment, model frame) and area.</summary>
|
||||
internal sealed class PlacedBand
|
||||
{
|
||||
public readonly int[] Cells;
|
||||
public readonly double[] Outline;
|
||||
public readonly double Area;
|
||||
public PlacedBand(int[] cells, double[] outline, double area) { Cells = cells; Outline = outline; Area = area; }
|
||||
public bool Empty => Cells.Length == 0;
|
||||
}
|
||||
|
||||
/// <summary>One placed copy of a <see cref="PlacedSolid"/>: the model turned by its yaw and moved to its first
|
||||
/// vertex, with the world box of its triangles.</summary>
|
||||
internal sealed class PlacedShape
|
||||
{
|
||||
public readonly PlacedSolid Model;
|
||||
public readonly double Ox, Oy, Oz, Yaw, Cos, Sin;
|
||||
public readonly double MinX, MinY, MinZ, MaxX, MaxY, MaxZ;
|
||||
|
||||
public PlacedShape(PlacedSolid model, double ox, double oy, double oz, double yaw,
|
||||
double minX, double minY, double minZ, double maxX, double maxY, double maxZ)
|
||||
{
|
||||
Model = model; Ox = ox; Oy = oy; Oz = oz; Yaw = yaw; Cos = Math.Cos(yaw); Sin = Math.Sin(yaw);
|
||||
MinX = minX; MinY = minY; MinZ = minZ; MaxX = maxX; MaxY = maxY; MaxZ = maxZ;
|
||||
}
|
||||
|
||||
public void ToModel(double x, double y, out double u, out double v)
|
||||
{
|
||||
double dx = x - Ox, dy = y - Oy;
|
||||
u = dx * Cos + dy * Sin;
|
||||
v = -dx * Sin + dy * Cos;
|
||||
}
|
||||
|
||||
public void ToWorld(double u, double v, out double x, out double y)
|
||||
{
|
||||
x = Ox + u * Cos - v * Sin;
|
||||
y = Oy + u * Sin + v * Cos;
|
||||
}
|
||||
|
||||
/// <summary>Something of it at (x, y) between world heights zLo and zHi.</summary>
|
||||
public bool SolidIn(double x, double y, double zLo, double zHi)
|
||||
{
|
||||
if (x < MinX - 0.1 || x > MaxX + 0.1 || y < MinY - 0.1 || y > MaxY + 0.1 || zHi < MinZ || zLo > MaxZ) return false;
|
||||
ToModel(x, y, out double u, out double v);
|
||||
return Model.SolidAt(u, v, zLo - Oz, zHi - Oz);
|
||||
}
|
||||
|
||||
/// <summary>The highest top of it at (x, y) no higher than world height zMax, or -infinity.</summary>
|
||||
public double TopAtMost(double x, double y, double zMax)
|
||||
{
|
||||
if (x < MinX - 0.1 || x > MaxX + 0.1 || y < MinY - 0.1 || y > MaxY + 0.1 || zMax < MinZ) return double.NegativeInfinity;
|
||||
ToModel(x, y, out double u, out double v);
|
||||
return Model.TopAtMost(u, v, zMax - Oz) + Oz;
|
||||
}
|
||||
|
||||
/// <summary>What of it is in the way between world heights zLo and zHi.</summary>
|
||||
public PlacedBand Band(double zLo, double zHi) => Model.Band(zLo - Oz, zHi - Oz);
|
||||
|
||||
public void CellCentre(int c, out double x, out double y)
|
||||
{
|
||||
Model.ColumnCentre(c, out double u, out double v);
|
||||
ToWorld(u, v, out x, out y);
|
||||
}
|
||||
|
||||
/// <summary>Walkable face k: its world box and height range.</summary>
|
||||
public void WalkFace(int k, out double minX, out double minY, out double maxX, out double maxY, out double z0, out double z1)
|
||||
{
|
||||
Model.WalkFace(k, out double au, out double av, out double aw, out double bu, out double bv, out double bw, out double cu, out double cv, out double cw);
|
||||
ToWorld(au, av, out double ax, out double ay);
|
||||
ToWorld(bu, bv, out double bx, out double by);
|
||||
ToWorld(cu, cv, out double cx, out double cy);
|
||||
minX = Math.Min(ax, Math.Min(bx, cx)); maxX = Math.Max(ax, Math.Max(bx, cx));
|
||||
minY = Math.Min(ay, Math.Min(by, cy)); maxY = Math.Max(ay, Math.Max(by, cy));
|
||||
z0 = Oz + Math.Min(aw, Math.Min(bw, cw)); z1 = Oz + Math.Max(aw, Math.Max(bw, cw));
|
||||
}
|
||||
|
||||
/// <summary>Walkable face k's centre (world).</summary>
|
||||
public void WalkFaceCentre(int k, out double x, out double y, out double z)
|
||||
{
|
||||
Model.WalkFace(k, out double au, out double av, out double aw, out double bu, out double bv, out double bw, out double cu, out double cv, out double cw);
|
||||
ToWorld((au + bu + cu) / 3, (av + bv + cv) / 3, out x, out y);
|
||||
z = Oz + (aw + bw + cw) / 3;
|
||||
}
|
||||
}
|
||||
|
|
@ -36,6 +36,9 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
public Vector3 Max { get; set; } // Maximum bounds
|
||||
public bool IsDoor { get; set; } // Whether this is a door (passable)
|
||||
public bool NoAabbFallback { get; set; } // If true, only count actual triangle hits (no AABB fallback)
|
||||
// A cylinder's or a sphere's solid the loader made (GeometryLoader.PlaceCollision), not a model's own polygons:
|
||||
// round, so never a stair, whatever its ring faces look like (BuildingMap.FurnitureFilter).
|
||||
public bool Round { get; set; }
|
||||
|
||||
public BoundingVolume()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -226,6 +226,13 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
foreach (var poly in cellGeo.Polygons)
|
||||
{
|
||||
if (poly.Vertices.Count < 3) continue;
|
||||
// A portal is an opening, never floor. Only the render-polygon fallback has any
|
||||
// (a cell with no physics polygons keeps its render ones, portals tagged): an
|
||||
// open-air cell, all openings. DreamWeave Thread 0x0169's 20 m shaft is four such
|
||||
// cells (0159/015A/015F/0160, open on every side, a floor portal at 0 down to the
|
||||
// cave 9-12 m below). Its floor portals read as floor, so the map walked straight
|
||||
// over the shaft and never saw the drop (2026-11-17).
|
||||
if (poly.IsPortal) continue;
|
||||
var worldVerts = new Vector3[poly.Vertices.Count];
|
||||
for (int i = 0; i < poly.Vertices.Count; i++)
|
||||
worldVerts[i] = TransformVertex(poly.Vertices[i], envCell, gx, gy);
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -340,12 +340,66 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
// Collision cylinders
|
||||
public List<CollisionCylinder> Cylinders = new List<CollisionCylinder>();
|
||||
|
||||
// Default pose part frames (from first placement in Setup)
|
||||
// Used to compute composite building bounding volumes.
|
||||
/// <summary>Every placement in the file (the parts' frames for one pose), by key: 0 Default,
|
||||
/// 0x65 Resting, and the animation poses.</summary>
|
||||
public Dictionary<int, Frame[]> Placements = new Dictionary<int, Frame[]>();
|
||||
|
||||
/// <summary>The key of the placement <see cref="PartFrames"/> is, or -1 when the file has none.</summary>
|
||||
public int PartFramesKey = -1;
|
||||
|
||||
/// <summary>The key of the first placement in the file.</summary>
|
||||
public int FirstPlacementKey;
|
||||
|
||||
// The parts' frames in the pose AC puts a placed object in: Resting (0x65) when the setup has it,
|
||||
// else Default (0), else the first in the file (ACE PartArray.SetPlacementFrame: the server and
|
||||
// client both ask for 0x65 when they make a static). This was the first placement in the file:
|
||||
// all 5,935 setups of today's portal.dat have a Default pose, 2,629 also have a Resting one and it
|
||||
// is never the first, so 0x0200016C's parts stood 0.41 m too low (z -0.41..0.41, AC 0..0.82) and
|
||||
// 0x02000183's a metre off (measured 2026-11-18).
|
||||
public Frame[] PartFrames;
|
||||
|
||||
/// <summary>Each part's DefaultScale (applied to its GfxObj before its frame, as ACE PartArray
|
||||
/// does), or null when the setup has none (scale 1). 330 setups have one.</summary>
|
||||
public Vector3[] DefaultScale;
|
||||
|
||||
public float StepUpHeight, StepDownHeight;
|
||||
|
||||
/// <summary>A placement carried animation hooks, which this reader can't step over: placements after
|
||||
/// it and the collision volumes come from the fallback parse. None in today's portal.dat.</summary>
|
||||
public bool PlacementHooks;
|
||||
|
||||
public bool HasBounds;
|
||||
|
||||
/// <summary>Part <paramref name="part"/>'s scale (1, 1, 1 when the setup has none).</summary>
|
||||
public Vector3 PartScale(int part)
|
||||
{
|
||||
if (DefaultScale == null || part < 0 || part >= DefaultScale.Length) return new Vector3(1, 1, 1);
|
||||
return DefaultScale[part];
|
||||
}
|
||||
|
||||
/// <summary>A point of part <paramref name="part"/>'s GfxObj in the setup's space: scaled by the
|
||||
/// part's DefaultScale, then posed by its frame in <see cref="PartFrames"/>.</summary>
|
||||
public Vector3 PartToSetup(int part, Vector3 local)
|
||||
{
|
||||
var s = PartScale(part);
|
||||
var scaled = new Vector3(local.X * s.X, local.Y * s.Y, local.Z * s.Z);
|
||||
var f = PartFrames != null && part >= 0 && part < PartFrames.Length ? PartFrames[part] : null;
|
||||
return f != null ? f.TransformPoint(scaled) : scaled;
|
||||
}
|
||||
|
||||
// Resting (0x65), else Default (0), else the first in the file.
|
||||
private void ChoosePartFrames()
|
||||
{
|
||||
if (PartFrames != null) return;
|
||||
foreach (int key in new[] { 0x65, 0, FirstPlacementKey })
|
||||
if (Placements.TryGetValue(key, out var frames))
|
||||
{
|
||||
PartFrames = frames;
|
||||
PartFramesKey = key;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
public bool Unpack(byte[] data)
|
||||
{
|
||||
if (data == null || data.Length < 16)
|
||||
|
|
@ -373,9 +427,15 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
if ((Flags & 0x01) != 0)
|
||||
ms.Seek(numParts * 4, SeekOrigin.Current);
|
||||
|
||||
// HasDefaultScale = 0x02
|
||||
// HasDefaultScale = 0x02: one Vector3 per part (setups such as 0x0200187B and
|
||||
// 0x02000D96 shrink or stretch parts with it; skipping it left them at size 1)
|
||||
if ((Flags & 0x02) != 0)
|
||||
ms.Seek(numParts * 12, SeekOrigin.Current); // Vector3 = 12 bytes
|
||||
{
|
||||
if (ms.Position + numParts * 12 > ms.Length) return TryFallbackParse(data);
|
||||
DefaultScale = new Vector3[numParts];
|
||||
for (int i = 0; i < numParts; i++)
|
||||
DefaultScale[i] = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle());
|
||||
}
|
||||
|
||||
// --- Skip HoldingLocations: uint32 count + count × (key(4) + PartId(4) + Frame(28)) ---
|
||||
if (!SkipHashTable(reader, ms, 36)) return TryFallbackParse(data);
|
||||
|
|
@ -383,41 +443,39 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
// --- Skip ConnectionPoints: same format ---
|
||||
if (!SkipHashTable(reader, ms, 36)) return TryFallbackParse(data);
|
||||
|
||||
// --- Skip PlacementFrames ---
|
||||
// --- PlacementFrames: every one kept by its key ---
|
||||
if (ms.Position + 4 > ms.Length) return TryFallbackParse(data);
|
||||
int placementsCount = reader.ReadInt32();
|
||||
if (placementsCount < 0 || placementsCount > 100) return TryFallbackParse(data);
|
||||
|
||||
for (int p = 0; p < placementsCount; p++)
|
||||
{
|
||||
if (ms.Position + 4 > ms.Length) return TryFallbackParse(data);
|
||||
reader.ReadInt32(); // key
|
||||
if (ms.Position + 4 > ms.Length) { ChoosePartFrames(); return TryFallbackParse(data); }
|
||||
int key = reader.ReadInt32();
|
||||
if (p == 0) FirstPlacementKey = key;
|
||||
|
||||
// AnimationFrame: numParts × Frame(28 bytes) + uint32 numHooks
|
||||
if (ms.Position + numParts * 28L > ms.Length) { ChoosePartFrames(); return TryFallbackParse(data); }
|
||||
var frames = new Frame[numParts];
|
||||
for (int part = 0; part < numParts; part++)
|
||||
{
|
||||
if (ms.Position + 28 > ms.Length) return TryFallbackParse(data);
|
||||
if (p == 0) // Store default pose part frames for composite bounds
|
||||
{
|
||||
if (PartFrames == null) PartFrames = new Frame[numParts];
|
||||
PartFrames[part] = new Frame();
|
||||
PartFrames[part].Unpack(reader);
|
||||
}
|
||||
else
|
||||
{
|
||||
ms.Seek(28, SeekOrigin.Current);
|
||||
}
|
||||
frames[part] = new Frame();
|
||||
frames[part].Unpack(reader);
|
||||
}
|
||||
Placements[key] = frames;
|
||||
|
||||
if (ms.Position + 4 > ms.Length) return TryFallbackParse(data);
|
||||
if (ms.Position + 4 > ms.Length) { ChoosePartFrames(); return TryFallbackParse(data); }
|
||||
uint numHooks = reader.ReadUInt32();
|
||||
if (numHooks > 0)
|
||||
{
|
||||
// AnimationHooks are variable-size; can't easily skip
|
||||
// But we already stored PartFrames from the default placement above
|
||||
// AnimationHooks are variable-size and this reader can't step over them: the
|
||||
// placements read so far are kept, the volumes come from the fallback.
|
||||
PlacementHooks = true;
|
||||
ChoosePartFrames();
|
||||
return TryFallbackParse(data);
|
||||
}
|
||||
}
|
||||
ChoosePartFrames();
|
||||
|
||||
// --- NOW we're at the good stuff! ---
|
||||
return ReadBoundsData(reader, ms, data);
|
||||
|
|
@ -425,6 +483,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
}
|
||||
catch
|
||||
{
|
||||
ChoosePartFrames();
|
||||
return TryFallbackParse(data);
|
||||
}
|
||||
}
|
||||
|
|
@ -471,8 +530,8 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
if (ms.Position + 16 > ms.Length) return false;
|
||||
Height = reader.ReadSingle();
|
||||
Radius = reader.ReadSingle();
|
||||
float stepUp = reader.ReadSingle();
|
||||
float stepDown = reader.ReadSingle();
|
||||
StepUpHeight = reader.ReadSingle();
|
||||
StepDownHeight = reader.ReadSingle();
|
||||
|
||||
// SortingSphere: Vector3 center + float radius
|
||||
if (ms.Position + 16 > ms.Length) return false;
|
||||
|
|
|
|||
|
|
@ -76,6 +76,40 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
public bool LineBlocked;
|
||||
public bool ArcChecked;
|
||||
public RaycastEngine.ArcLosResult Arc;
|
||||
public bool TerrainBlocked; // outdoors: the ground rises above the path (a hill between)
|
||||
public float TerrainAlong; // where along the path, in meters from the shooter
|
||||
}
|
||||
|
||||
// ── Hills (2026-11-22, R-20261122-203611-ff3d) ─────────────────────────────────────────
|
||||
// The verdict tested objects and buildings only, never the ground: on the Withered Tumerok
|
||||
// hills a caster 56-68 m below its targets (11 m lower) cast Blade Arc after Blade Arc into
|
||||
// the hillside ("stopped short of the target"), three no-damage casts and a blacklist per
|
||||
// monster, round the whole group. Outdoors the path is now sampled every TerrainStepMeters
|
||||
// against the landscape: the ground above it by TerrainClearance anywhere past the first and
|
||||
// before the last TerrainEndSkipMeters (the slopes the two stand on) blocks the shot.
|
||||
private const float TerrainStepMeters = 1.5f, TerrainEndSkipMeters = 2.0f, TerrainClearance = 0.25f;
|
||||
|
||||
/// <summary>
|
||||
/// Outdoors, whether the ground rises above the path from <paramref name="a"/> to <paramref name="b"/>
|
||||
/// (chest heights, global meters); with <paramref name="sag"/> > 0 the path bows up by that much at
|
||||
/// its middle (an arc). <paramref name="along"/>: where, in meters from <paramref name="a"/>.
|
||||
/// </summary>
|
||||
public bool TerrainBetween(Vector3 a, Vector3 b, float sag, out float along)
|
||||
{
|
||||
along = 0f;
|
||||
float dx = b.X - a.X, dy = b.Y - a.Y;
|
||||
float flat = (float)Math.Sqrt(dx * dx + dy * dy);
|
||||
if (flat <= 2 * TerrainEndSkipMeters) return false;
|
||||
for (float s = TerrainEndSkipMeters; s <= flat - TerrainEndSkipMeters; s += TerrainStepMeters)
|
||||
{
|
||||
float f = s / flat;
|
||||
float x = a.X + dx * f, y = a.Y + dy * f;
|
||||
float ground = _geoLoader.GetTerrainZWorld(x, y);
|
||||
if (float.IsNaN(ground)) continue;
|
||||
float pathZ = a.Z + (b.Z - a.Z) * f + (sag > 0 ? 4f * sag * f * (1f - f) : 0f);
|
||||
if (ground > pathZ + TerrainClearance) { along = s; return true; }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool IsMissileArc(AttackType t) =>
|
||||
|
|
@ -259,6 +293,20 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
arcHeadroom = arc.ApexAboveLaunch + (launch.Z - origin.Z) + Math.Max(0f, MissileArcClearance) + 0.5f;
|
||||
}
|
||||
|
||||
// Outdoors: a hill between (TerrainBetween). Before the pre-filter below, which only
|
||||
// knows objects: open hillsides have none near the path.
|
||||
if (!isDungeon)
|
||||
{
|
||||
float sag = missileArc && arc.Valid ? arc.MaxRiseAboveChord : 0f;
|
||||
if (TerrainBetween(missileArc ? launch : origin, targetPos, sag, out float along))
|
||||
{
|
||||
detail.Checked = true;
|
||||
detail.TerrainBlocked = true;
|
||||
detail.TerrainAlong = along;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Pre-filter: skip full ray test if no geometry near the path
|
||||
float margin = Math.Min(flatDist * 0.3f, 15.0f);
|
||||
margin = Math.Max(margin, 3.0f);
|
||||
|
|
|
|||
|
|
@ -74,6 +74,7 @@ public sealed partial class RynthAiPlugin
|
|||
ChatLine("[RynthAi] /ra power <0-100|auto> — set attack power (auto = recklessness-aware)");
|
||||
ChatLine("[RynthAi] /ra dfheight [on|off|status|window] — Dirty Fighting rotation: attack heights by the effects on the target");
|
||||
ChatLine("[RynthAi] /ra meleewalls [on|off] — Melee through walls: melee reaches a monster within 4 m behind a wall (not a building's)");
|
||||
ChatLine("[RynthAi] /ra debuffall [on|off] — Debuff every monster in range before attacking (toggle)");
|
||||
ChatLine("[RynthAi] /ra cast <spellId> — cast spell on current target");
|
||||
ChatLine("[RynthAi] /ra buffs — show active buff timers");
|
||||
ChatLine("[RynthAi] /ra buffitems [list|allow|block|add|addselected|remove|repeat|open] — the buff items RynthAi may use");
|
||||
|
|
@ -117,6 +118,9 @@ public sealed partial class RynthAiPlugin
|
|||
ChatLine("[RynthAi] /ra items fill — add weapons, healing kits, lockpicks and pet essences from your pack");
|
||||
ChatLine("[RynthAi] /ra aetheria [status|unbox|on|off] — unbox Coalesced Aetheria with an Aetheria Mana Stone (Unbox Aetheria When Idle)");
|
||||
ChatLine("[RynthAi] /ra autoconfirm [status|on|off|<50-100>] — Yes to the craft-chance prompt at that % or better (Mini Remote > Crafting)");
|
||||
ChatLine("[RynthAi] /ra kits [status|make [N]|stop|floor <0-100>|show] — make Plentiful Healing Kits from their ingredients, macro off (Mini Remote > Crafting > Kits)");
|
||||
ChatLine("[RynthAi] /ra kits auto [status|on|off|below N|upto M] — Make kits when low: with the macro on and nothing around, make kits when fewer than N are carried");
|
||||
ChatLine("[RynthAi] /ra petelement [status|any|fire|cold|acid|lightning|nether|slash|pierce|bludgeon] — the element combat pets are summoned for (Mini Remote > Pets)");
|
||||
ChatLine("[RynthAi] /ra offhand [auto|shield|weapon|none] [rule] — the off hand (shield / dual wield), global or for a Monsters rule; dual on|off");
|
||||
ChatLine("[RynthAi] /ra dunnav <NS> <EW> — navigate to NS/EW coords through dungeon (no nav file needed)");
|
||||
ChatLine("[RynthAi] /ra dunnav-to <object id> — walk to an object in this dungeon, any floor (a monster, say)");
|
||||
|
|
@ -141,6 +145,7 @@ public sealed partial class RynthAiPlugin
|
|||
ChatLine("[RynthAi] /ra chests — Loot Nearby Chests: on or off, what it is doing, and the chests it is leaving alone and why");
|
||||
ChatLine("[RynthAi] /ra loot why — which loot rule takes the selected item, and why the rules above it didn't");
|
||||
ChatLine("[RynthAi] /ra loot mode [profile|rares] — loot by the loot profile, or rares and needed mana stones only");
|
||||
ChatLine("[RynthAi] /ra loot today — Keep # per day rules: what this character picked up in each one's window (clear <rule>|all)");
|
||||
ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [preview] — add a loot rule for the selected item");
|
||||
ChatLine("[RynthAi] /ra dumpinv — dump all inventory items (cache + direct)");
|
||||
ChatLine("[RynthAi] /ra combat — dump combat state machine snapshot");
|
||||
|
|
@ -1302,6 +1307,14 @@ public sealed partial class RynthAiPlugin
|
|||
var names = _dashboard.NavFileNames();
|
||||
ChatLine(names.Count == 0 ? "[RynthAi] No navs in NavProfiles." : $"[RynthAi] Navs ({names.Count}): {string.Join(", ", names)}");
|
||||
break;
|
||||
case "import":
|
||||
{
|
||||
// VirindiTank navs put in another folder (RynthNav's NavData, the RynthAi folder...):
|
||||
// copied into NavProfiles, as the Nav panel's button does.
|
||||
string msg = _dashboard.CopyStrayNavs(out bool ok);
|
||||
if (ok) ReplyOk("[RynthAi] " + msg); else ReplyFail("[RynthAi] " + msg);
|
||||
break;
|
||||
}
|
||||
case "new":
|
||||
case "saveas":
|
||||
case "rename":
|
||||
|
|
@ -1310,6 +1323,9 @@ public sealed partial class RynthAiPlugin
|
|||
// The Loaded files drawer's NAV buttons (RynthAiPlugin.ProfileFiles.cs).
|
||||
TryProfileVerb(ProfileKind.Nav, sub, rest, NavUsage);
|
||||
break;
|
||||
case "addjump":
|
||||
AddJumpHere(rest);
|
||||
break;
|
||||
case "restart":
|
||||
{
|
||||
// Stopping and starting the macro keeps the route where it was (a finished Once
|
||||
|
|
@ -1335,7 +1351,48 @@ public sealed partial class RynthAiPlugin
|
|||
}
|
||||
|
||||
private const string NavUsage =
|
||||
"/ra nav save [name] | /ra nav load <name> | /ra nav new <name> | /ra nav saveas <name> | /ra nav rename <name> | /ra nav delete | /ra nav folder | /ra nav list | /ra nav restart";
|
||||
"/ra nav save [name] | /ra nav load <name> | /ra nav new <name> | /ra nav saveas <name> | /ra nav rename <name> | /ra nav delete | /ra nav folder | /ra nav list | /ra nav import | /ra nav restart | /ra nav addjump [ms] [shift]";
|
||||
|
||||
/// <summary>The hold a recorded jump gets when none is given: the dungeon walk's own hop.</summary>
|
||||
internal const int AddJumpDefaultMs = DungeonPathfinder.JumpHoldMs;
|
||||
|
||||
/// <summary>
|
||||
/// /ra nav addjump [ms] [shift]: a Jump step where you stand, facing the way you face, added to the end of
|
||||
/// the loaded route (and saved to its file). Recording doesn't see a jump (the client tells a plugin
|
||||
/// nothing of one), and some places can only be reached by one: 2026-11-18, Thread 0x00C1's pit, where the
|
||||
/// fighting is, is dropped into from a ledge. ms is how long the jump is held (0-1000, the power; 300 by
|
||||
/// default), shift a walking jump. While recording, the next point waits until you have landed.
|
||||
/// </summary>
|
||||
private void AddJumpHere(string args)
|
||||
{
|
||||
var settings = _dashboard?.Settings;
|
||||
if (settings == null) { ReplyFail("[RynthAi] Settings not ready."); return; }
|
||||
int ms = AddJumpDefaultMs;
|
||||
bool shift = false;
|
||||
foreach (string word in args.Split(' ', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
if (word.Equals("shift", StringComparison.OrdinalIgnoreCase)) shift = true;
|
||||
else if (int.TryParse(word, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out int n)) ms = Math.Clamp(n, 0, 1000);
|
||||
else { ReplyFail("[RynthAi] Usage: /ra nav addjump [ms] [shift] (ms: 0-1000, how long the jump is held)"); return; }
|
||||
}
|
||||
if (!NavCoordinateHelper.TryGetNavPosition(Host, out double ns, out double ew, out double z)
|
||||
|| !PlayerCompass.TryGet(Host, out float heading))
|
||||
{
|
||||
ReplyFail("[RynthAi] Could not read your position and heading.");
|
||||
return;
|
||||
}
|
||||
var pt = new NavPoint
|
||||
{
|
||||
Type = NavPointType.Jump, NS = ns, EW = ew, Z = z,
|
||||
JumpHeading = Math.Round(heading, 1), JumpMs = ms, JumpShift = shift,
|
||||
};
|
||||
NavRouteEditing.Apply(settings, list => { list.Add(pt); return list; });
|
||||
if (settings.IsRecordingNav) _navBreadcrumbs?.JumpAdded();
|
||||
_dashboard?.AutoSaveRoute();
|
||||
string navName = string.IsNullOrEmpty(settings.CurrentNavPath) ? "(unsaved)" : System.IO.Path.GetFileName(settings.CurrentNavPath);
|
||||
ReplyOk($"[RynthAi] Added a jump [{settings.CurrentRoute.Points.Count - 1}] facing {heading:F0}°, held {ms} ms{(shift ? ", walking" : "")}, to {navName}"
|
||||
+ (settings.IsRecordingNav ? ": jump now; recording goes on once you land." : "."));
|
||||
}
|
||||
private const string MetaUsage =
|
||||
"/ra meta load <name> | new <name> | save | saveas <name> | rename <name> | delete | folder | list | repair";
|
||||
private const string SettingsUsage =
|
||||
|
|
@ -1692,6 +1749,9 @@ public sealed partial class RynthAiPlugin
|
|||
FirstMatchNative = FirstLootRuleFor,
|
||||
Added = OnLootRuleAdded,
|
||||
BuiltInKeep = LootBuiltInKeepFor,
|
||||
PerDayStatus = PerDayStatusFor,
|
||||
PerDayRevision = PerDayRevision,
|
||||
PerDayReset = PerDayReset,
|
||||
},
|
||||
};
|
||||
|
||||
|
|
@ -1858,6 +1918,11 @@ public sealed partial class RynthAiPlugin
|
|||
HandleLootModeCommand(parts);
|
||||
return;
|
||||
}
|
||||
if (sub == "today")
|
||||
{
|
||||
HandleLootTodayCommand(parts); // Keep # per day (RynthAiPlugin.LootPerDay.cs)
|
||||
return;
|
||||
}
|
||||
// The Loaded files drawer's LOOT buttons (RynthAiPlugin.ProfileFiles.cs).
|
||||
if (TryProfileVerb(ProfileKind.Loot, sub, parts.Length > 3 ? string.Join(" ", parts, 3, parts.Length - 3) : string.Empty, LootFileUsage))
|
||||
return;
|
||||
|
|
@ -1865,6 +1930,7 @@ public sealed partial class RynthAiPlugin
|
|||
{
|
||||
ChatLine("[RynthAi] /ra loot mode [profile|rares] — what is looted: the loot profile, or rares and needed mana stones only");
|
||||
ChatLine("[RynthAi] /ra loot why [window] — which loot rule takes the selected item, and why the rules above it didn't (window: in the Loot why window)");
|
||||
ChatLine("[RynthAi] /ra loot today [clear <rule>|clear all] — Keep # per day rules: what this character picked up in each one's window");
|
||||
ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [t11] [preview] — add a loot rule for the selected item to the loot profile in use");
|
||||
ChatLine("[RynthAi] " + LootFileUsage + " — the loot profile's file: a new one in the Loot Editor, a copy, rename, move to Deleted, its folder, the editor");
|
||||
ChatLine("[RynthAi] default: exact name + class; Read for scrolls, Keep # (one full stack) for stacks, else Keep. name = name only, like = items like this. t11 = also require its T11 tier, grade and modifiers (at least this good). preview = show it, add nothing.");
|
||||
|
|
@ -2340,11 +2406,14 @@ public sealed partial class RynthAiPlugin
|
|||
/// had this via TogglePanelMacro). Routed through the same TogglePanelMacro the
|
||||
/// button and the remote use, so there's still one write path for the flag.
|
||||
/// </summary>
|
||||
private void HandleMacroRunCommand(string verb, string[] parts)
|
||||
private void HandleMacroRunCommand(string verb, string[] parts, string? source = null)
|
||||
{
|
||||
var dash = _dashboard;
|
||||
if (dash == null) { ReplyFail("[RynthAi] Settings not ready."); return; }
|
||||
bool running = dash.Settings.IsMacroRunning;
|
||||
source ??= "the command /ra " + verb + (MetaCommandActive ? $" from the meta (state '{dash.Settings.CurrentState}')"
|
||||
: Reply.FromScript ? " from a script, a route or a timed command"
|
||||
: " (typed, or a hotkey or alias)");
|
||||
|
||||
switch (verb)
|
||||
{
|
||||
|
|
@ -2353,14 +2422,14 @@ public sealed partial class RynthAiPlugin
|
|||
_macroResumeAt = 0;
|
||||
if (running) { ReplyOk("[RynthAi] Macro already RUNNING."); return; }
|
||||
if (RefuseMacroStartForVTank()) return; // one bot per client (Decal bridge)
|
||||
dash.TogglePanelMacro();
|
||||
dash.TogglePanelMacro(source);
|
||||
ReplyOk("[RynthAi] Macro STARTED.");
|
||||
return;
|
||||
|
||||
case "stop":
|
||||
_macroResumeAt = 0;
|
||||
if (!running) { ReplyOk("[RynthAi] Macro already STOPPED."); return; }
|
||||
dash.TogglePanelMacro();
|
||||
dash.TogglePanelMacro(source);
|
||||
// Kill autorun now rather than waiting out the nav engine's stop
|
||||
// debounce — a /ra stop is usually issued because the box is
|
||||
// running somewhere you don't want it to.
|
||||
|
|
@ -2375,7 +2444,7 @@ public sealed partial class RynthAiPlugin
|
|||
sec = Math.Clamp(parsed, 1, 3600);
|
||||
if (running)
|
||||
{
|
||||
dash.TogglePanelMacro();
|
||||
dash.TogglePanelMacro(source);
|
||||
_navigationEngine?.Stop();
|
||||
}
|
||||
_macroResumeAt = CorpseNowMs + sec * 1000L;
|
||||
|
|
@ -3172,14 +3241,16 @@ public sealed partial class RynthAiPlugin
|
|||
: $"[RynthAi] No items in inventory matched profile '{System.IO.Path.GetFileName(profilePath)}'");
|
||||
}
|
||||
|
||||
internal const string DunNavToUsage ="[RynthAi] Usage: /ra dunnav-to <object id> — walk to an object in this dungeon (any floor), e.g. a monster: /ra dunnav-to 0x80123456";
|
||||
internal const string DunNavToUsage = "[RynthAi] Usage: /ra dunnav-to <object id> [jump] — walk to an object in this dungeon (any floor), e.g. a monster: /ra dunnav-to 0x80123456; with jump, a jump down a ledge may be taken when there's no walk (one way: no climbing back)";
|
||||
|
||||
/// <summary>
|
||||
/// /ra dunnav-to <object id> (2026-11-15): walks to an object in the dungeon the character is in,
|
||||
/// by the dungeon map (ledges closed: DungeonPathfinder.Ledges.cs), from the player's cell to the
|
||||
/// /ra dunnav-to <object id> [jump] (2026-11-15): walks to an object in the dungeon the character is
|
||||
/// in, by the dungeon map (ledges closed: DungeonPathfinder.Ledges.cs), from the player's cell to the
|
||||
/// object's own cell, so another floor works too (/ra dunnav aims at the player's floor). For
|
||||
/// a script: after an explore, the monsters still to be killed are walked to one by
|
||||
/// one; the fight is RynthAi's, as on any route. The macro goes on; the route is a Once walk.
|
||||
/// With "jump" (2026-11-17), when there's no walk the path may jump down ledges
|
||||
/// (DungeonPathfinder.Jumps.cs): a Jump point at each edge. One way, so only on request.
|
||||
/// </summary>
|
||||
private void HandleDunNavToCommand(string[] parts)
|
||||
{
|
||||
|
|
@ -3225,20 +3296,41 @@ public sealed partial class RynthAiPlugin
|
|||
var hazards = _objectCache?.GetHazardCells();
|
||||
var path = startCell != 0 && goalCell != 0 ? DungeonPathfinder.FindPath(startCell, goalCell, graph, hazards) : new List<uint>();
|
||||
Host.TryGetObjectName(target, out string name);
|
||||
bool mayJump = parts.Skip(3).Any(p => p.Trim().Equals("jump", StringComparison.OrdinalIgnoreCase));
|
||||
NavRouteParser route;
|
||||
string how;
|
||||
if (path.Count == 0)
|
||||
{
|
||||
ReplyFail($"[RynthAi] DunNav-To: no walk from {startCell:X8} to '{name}' 0x{target:X8} in {goalCell:X8} on the dungeon map (behind a ledge or a hazard?).");
|
||||
return;
|
||||
// No walk: with "jump", down a ledge (or several) if that gets there.
|
||||
var jumpPath = mayJump && geo != null && startCell != 0 && goalCell != 0
|
||||
? DungeonPathfinder.FindPathWithJumps(startCell, goalCell, graph, DungeonPathfinder.FindJumps(graph, geo), hazards)
|
||||
: new List<(uint Cell, DungeonJump? Jump)>();
|
||||
if (jumpPath.Count == 0)
|
||||
{
|
||||
ReplyFail($"[RynthAi] DunNav-To: no walk from {startCell:X8} to '{name}' 0x{target:X8} in {goalCell:X8} on the dungeon map (behind a ledge or a hazard?)"
|
||||
+ (mayJump ? ", and no jump down gets there either." : "."));
|
||||
return;
|
||||
}
|
||||
route = new NavRouteParser { RouteType = NavRouteType.Once };
|
||||
route.Points.AddRange(DungeonPathfinder.BuildJumpPathPoints(jumpPath, graph, geo, hazards, playerNS, playerEW, playerZ, destNS, destEW, oz, out int jumps));
|
||||
route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = destNS, EW = destEW, Z = oz / 240.0 });
|
||||
var first = jumpPath.First(p => p.Jump != null).Jump!.Value;
|
||||
how = $"{jumpPath.Count} cells, {jumps} jump{(jumps == 1 ? "" : "s")} down (the first {first.Drop:F1} m off {first.From:X8} into {first.Land:X8})";
|
||||
Host.Log($"[RynthAi] DunNav-To: no walk to 0x{target:X8}; jumping down: {how}.");
|
||||
}
|
||||
else
|
||||
{
|
||||
route = DungeonPathfinder.BuildNavRoute(path, graph, destNS, destEW, geo, hazards, playerNS, playerEW, playerZ, oz);
|
||||
how = $"{path.Count} cells";
|
||||
}
|
||||
var route = DungeonPathfinder.BuildNavRoute(path, graph, destNS, destEW, geo, hazards, playerNS, playerEW, playerZ, oz);
|
||||
if (route.Points.Count == 0) { ReplyFail($"[RynthAi] DunNav-To: no walk laid to '{name}' 0x{target:X8}."); return; }
|
||||
|
||||
if (!settings.IsMacroRunning && RefuseMacroStartForVTank()) return; // one bot per client (Decal bridge)
|
||||
settings.IsMacroRunning = true;
|
||||
settings.SetMacroRunning(true, "/ra dunnav-to");
|
||||
settings.CurrentRoute = route;
|
||||
settings.ActiveNavIndex = 0;
|
||||
settings.EnableNavigation = true;
|
||||
ReplyOk($"[RynthAi] DunNav-To: '{name}' 0x{target:X8} in {goalCell:X8}: {path.Count} cells, {route.Points.Count} points → walking there");
|
||||
ReplyOk($"[RynthAi] DunNav-To: '{name}' 0x{target:X8} in {goalCell:X8}: {how}, {route.Points.Count} points → walking there");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -3302,7 +3394,7 @@ public sealed partial class RynthAiPlugin
|
|||
}
|
||||
|
||||
if (!settings.IsMacroRunning && RefuseMacroStartForVTank()) return; // one bot per client (Decal bridge)
|
||||
settings.IsMacroRunning = true;
|
||||
settings.SetMacroRunning(true, "/ra dunnav");
|
||||
settings.CurrentRoute = route;
|
||||
settings.ActiveNavIndex = 0;
|
||||
settings.EnableNavigation = true;
|
||||
|
|
@ -3667,7 +3759,7 @@ public sealed partial class RynthAiPlugin
|
|||
// "patrol immediately runs into a wall on login" failure mode. (From where the character
|
||||
// walks out of a portal's circle to, when it stands in one.)
|
||||
// (The explore only looks a few points ahead: past those it would skip rooms, a loop comes round again.)
|
||||
int startIdx = FindFirstLineOfSightWaypoint(route, losCell, losX, losY, losZ, explore != null ? ExploreSightLookahead : int.MaxValue);
|
||||
int startIdx = FindFirstLineOfSightWaypoint(route, losCell, losX, losY, losZ, explore != null ? ExploreSightLookahead : int.MaxValue, walkMap: geometry);
|
||||
// The way to that waypoint: out of a portal's circle first, round any portal in between.
|
||||
if (portals.Count > 0 && route.Points.Count > 0)
|
||||
{
|
||||
|
|
@ -3738,7 +3830,7 @@ public sealed partial class RynthAiPlugin
|
|||
_dunPatrolActive = false;
|
||||
return;
|
||||
}
|
||||
settings.IsMacroRunning = true;
|
||||
settings.SetMacroRunning(true, "the dungeon patrol");
|
||||
// The patrol picked its own start (the first waypoint in sight). Starting the macro
|
||||
// here must not also trigger the macro-start "nearest waypoint" pick on the next
|
||||
// tick: on a loop that is often a waypoint near the END (it comes back to the start),
|
||||
|
|
@ -4298,10 +4390,13 @@ public sealed partial class RynthAiPlugin
|
|||
/// world position has clear line of sight from the player. Returns 0 if no LOS check
|
||||
/// is possible (no raycast subsystem / no geometry) or if no waypoint clears — at
|
||||
/// worst we behave like the old "always start at 0" code, so this is a strict win.
|
||||
/// <paramref name="walkMap"/> (the dungeon map, in a dungeon): a waypoint in sight is taken only when the straight
|
||||
/// walk to it passes at a body's height too (DungeonPathfinder.StraightWalkClear). In sight at chest height, a
|
||||
/// later waypoint skipped the corners laid round an altar or a table, and the first leg went through it (2026-11-18).
|
||||
/// </summary>
|
||||
private int FindFirstLineOfSightWaypoint(NavRouteParser route, uint playerCell,
|
||||
float playerLocalX, float playerLocalY, float playerZ,
|
||||
int lookahead = int.MaxValue)
|
||||
int lookahead = int.MaxValue, DungeonGeometry? walkMap = null)
|
||||
{
|
||||
if (route?.Points == null || route.Points.Count == 0) return 0;
|
||||
var geo = _raycast?.GeometryLoader;
|
||||
|
|
@ -4316,6 +4411,11 @@ public sealed partial class RynthAiPlugin
|
|||
var origin = new Vector3(pBlockX * 192f + playerLocalX,
|
||||
pBlockY * 192f + playerLocalY,
|
||||
playerZ + 1.0f);
|
||||
// The walk test only where the map has a floor under the character (in a dungeon's cell).
|
||||
NavPoint? from = null;
|
||||
if (walkMap != null && (playerCell & 0xFFFF) >= 0x0100
|
||||
&& walkMap.TryFloorHeight(origin.X, origin.Y, playerZ, 3.0, out _))
|
||||
from = new NavPoint { Type = NavPointType.Point, EW = DungeonGeometry.WorldToNav(origin.X), NS = DungeonGeometry.WorldToNav(origin.Y), Z = playerZ / 240.0 };
|
||||
|
||||
for (int i = 0; i < route.Points.Count && i < lookahead; i++)
|
||||
{
|
||||
|
|
@ -4333,8 +4433,9 @@ public sealed partial class RynthAiPlugin
|
|||
|
||||
// multiRay=true matches dungeon LOS used elsewhere (TargetingFSM) so thin
|
||||
// corner walls don't slip between the center ray.
|
||||
if (!RaycastEngine.IsLinearPathBlocked(origin, target, geometry, multiRay: true))
|
||||
return i;
|
||||
if (RaycastEngine.IsLinearPathBlocked(origin, target, geometry, multiRay: true)) continue;
|
||||
if (from != null && !DungeonPathfinder.StraightWalkClear(walkMap!, from, p)) continue;
|
||||
return i;
|
||||
}
|
||||
|
||||
return 0;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,36 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - RynthAiPlugin.BoostLootFirst.cs
|
||||
// Boost Loot Priority: corpses first, then the hunt (2026-11-22: "boost loot should loot any
|
||||
// new corpse available and hunt after looting is complete").
|
||||
//
|
||||
// R-20261122-010831-9488 (Shadowfang Keep, Conquest): fast spawns, and Boost Loot "is not looting
|
||||
// every corpse before moving along to the next". It gave way to any monster within 5 yd twice over:
|
||||
// the arbiter gave Looting the tick only while combat wasn't engaged (a target locked, or a monster
|
||||
// within CloseAttackYards), and combat's hold on its next target (BoostLootHoldsNewTarget) ended the
|
||||
// moment a monster came that close. In a room that refills at once one always is, so the next
|
||||
// monster was locked 1 ms after each kill and the corpses waited for a lull that rarely came.
|
||||
//
|
||||
// Now, with Boost Loot on, while there is loot work (a corpse claimed, open, lootable in range, or
|
||||
// the kill's corpse still forming) neither gives way to a close monster: the corpses are looted,
|
||||
// then the fight and the hunt go on. One exception kept for safety: with health under Heal At (the
|
||||
// line a fight heals at) a monster on you is fought as before, so looting never stands still while
|
||||
// the character is being killed.
|
||||
// ============================================================================
|
||||
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
public sealed partial class RynthAiPlugin
|
||||
{
|
||||
/// <summary>
|
||||
/// Boost Loot Priority puts corpses ahead of a monster that is close or already fought: Boost Loot
|
||||
/// can run, and health is at or above Heal At (or not known yet).
|
||||
/// </summary>
|
||||
private bool BoostLootFirst(LegacyUiSettings settings)
|
||||
=> BoostLootCanRun(settings) && (_vitals.MaxHealth == 0 || _vitals.HealthPct >= settings.HealAt);
|
||||
|
||||
/// <summary>CombatManager.HoldNewTargetThroughThreat: the hold on the next target applies with a monster close.</summary>
|
||||
private bool BoostLootHoldsThroughThreat()
|
||||
=> _dashboard?.Settings is { } s && BoostLootFirst(s);
|
||||
}
|
||||
|
|
@ -240,7 +240,7 @@ public sealed partial class RynthAiPlugin
|
|||
ResetCurrentLootItem();
|
||||
_processedCorpseItems.Clear();
|
||||
_corpseItemAttempts.Clear();
|
||||
_pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear();
|
||||
_pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear(); _pendingPerDay.Clear();
|
||||
_targetCorpseId = id;
|
||||
_corpseTargetSince = now;
|
||||
_lastCorpseOpenAttemptAt = 0;
|
||||
|
|
@ -261,7 +261,11 @@ public sealed partial class RynthAiPlugin
|
|||
if (why == "completed")
|
||||
_lastChestLootedId = unchecked((uint)chestId); // ralastchestlooted[]
|
||||
// Pickup with macro off > Leave the chest open: a chest the player opened stays open, and chat says so.
|
||||
bool leaveOpen = close && chestId == _manualChestLootId && (_dashboard?.Settings?.LootChestsMacroOffLeaveOpen ?? false);
|
||||
// So does one the pickup took nothing from (R-20261120-173459-ea5d): it was closed about 1 ms after
|
||||
// the player opened it, before they could take what the profile leaves, and some chests lock on close.
|
||||
bool manual = chestId == _manualChestLootId;
|
||||
bool leaveOpen = close && manual
|
||||
&& ((_dashboard?.Settings?.LootChestsMacroOffLeaveOpen ?? false) || _corpseItemsLooted == 0);
|
||||
if (chestId == _manualChestLootId)
|
||||
_manualChestLootId = 0;
|
||||
if (close && !leaveOpen)
|
||||
|
|
@ -281,7 +285,7 @@ public sealed partial class RynthAiPlugin
|
|||
|
||||
_processedCorpseItems.Clear();
|
||||
_corpseItemAttempts.Clear();
|
||||
_pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear();
|
||||
_pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear(); _pendingPerDay.Clear();
|
||||
_corpseIdsRequested = false;
|
||||
ResetCurrentLootItem();
|
||||
if (_openedContainerId == chestId)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,82 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - RynthAiPlugin.CorpseBehindWall.cs
|
||||
// A corpse behind a wall (2026-11-21, R-20261121-190950-ee4e, 2026.11.19.1): "I keep trying to loot
|
||||
// through walls" in a dungeon (Shadowfang Keep, 0x005A). Corpses 3.4-3.7 m away on the far side of a
|
||||
// wall: every open came back UseDone 0 and nothing opened (the server walks the character straight
|
||||
// at the corpse, and the wall stops it). Each one cost about 11 s (four opens, the use check's clean
|
||||
// stop, a jump and its pause), then came back 30 s later for two more rounds, while other corpses
|
||||
// waited, and the stops and jumps read as the character fighting the wall.
|
||||
//
|
||||
// Now an open that is about to be re-sent for a corpse that didn't open checks the straight line to
|
||||
// it (the raycast's single chest-height ray, as melee uses): a wall in the way sets the corpse aside
|
||||
// instead. Set aside is not an abandon (it never counts toward the three), its failed open is not a
|
||||
// use refusal, and it gets another look every CorpseWallRecheckMs: once the line is clear (the
|
||||
// character moved, the hunt walked round) it is a corpse like any other. Only a failed open leads
|
||||
// here, so a corpse the ray reads behind a wall that still opens is looted as before.
|
||||
// ============================================================================
|
||||
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthAi.Raycasting;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
public sealed partial class RynthAiPlugin
|
||||
{
|
||||
/// <summary>A corpse set aside behind a wall is looked at again this often.</summary>
|
||||
internal const long CorpseWallRecheckMs = 3000;
|
||||
|
||||
private readonly HashSet<int> _corpsesBehindWall = new();
|
||||
|
||||
/// <summary>Tests: whether a wall stands between the character and the corpse (else the raycast decides).</summary>
|
||||
internal System.Func<int, bool>? CorpseWallOverride { get; set; }
|
||||
|
||||
/// <summary>The straight line to <paramref name="corpseId"/> crosses a wall. False when the raycast can't say.</summary>
|
||||
private bool CorpseBehindWall(int corpseId)
|
||||
{
|
||||
if (CorpseWallOverride != null) return CorpseWallOverride(corpseId);
|
||||
var raycast = _raycastReady;
|
||||
if (raycast == null || !raycast.IsInitialized) return false;
|
||||
try { return raycast.IsTargetBlocked(Host, unchecked((uint)corpseId), TargetingFSM.AttackType.Melee); }
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Before an open is re-sent for <paramref name="corpseId"/> (one already went out and nothing
|
||||
/// opened): true when it was set aside behind a wall instead, and nothing is sent.
|
||||
/// </summary>
|
||||
private bool SetAsideBehindWall(int corpseId, long now)
|
||||
{
|
||||
if (corpseId == 0 || _lastOpenAttemptCorpseId != corpseId || _openedContainerId == corpseId) return false;
|
||||
if (!CorpseBehindWall(corpseId)) return false;
|
||||
_useRefusals.Forget(corpseId);
|
||||
if (_corpsesBehindWall.Count >= 256) _corpsesBehindWall.Clear(); // a bound: corpses go in minutes
|
||||
_corpsesBehindWall.Add(corpseId);
|
||||
_corpseCooldownUntil[corpseId] = now + CorpseWallRecheckMs;
|
||||
string name = _objectCache?[corpseId]?.Name ?? $"0x{(uint)corpseId:X8}";
|
||||
double d = _objectCache?.Distance(unchecked((int)_playerId), corpseId) ?? double.MaxValue;
|
||||
LootDiag($"[RynthAi] Corpse loot: 0x{(uint)corpseId:X8} '{name}'{(d < 1000 ? $" ({d:0.0} m)" : "")} didn't open and a wall " +
|
||||
"stands between: set aside (not a refusal or an abandon) until the line to it is clear.");
|
||||
StopCorpseMovement();
|
||||
ResetCorpseTarget();
|
||||
_lastOpenAttemptCorpseId = 0;
|
||||
_lastCorpseOpenAttemptAt = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// HasUnlootedCorpsesInRange, for a corpse set aside behind a wall whose look-again time came:
|
||||
/// true while the wall is still there (it waits another CorpseWallRecheckMs).
|
||||
/// </summary>
|
||||
private bool StillBehindWall(int corpseId, long now)
|
||||
{
|
||||
if (!_corpsesBehindWall.Contains(corpseId)) return false;
|
||||
if (CorpseBehindWall(corpseId))
|
||||
{
|
||||
_corpseCooldownUntil[corpseId] = now + CorpseWallRecheckMs;
|
||||
return true;
|
||||
}
|
||||
_corpsesBehindWall.Remove(corpseId);
|
||||
LootDiag($"[RynthAi] Corpse loot: the line to 0x{(uint)corpseId:X8} is clear now: it can be looted.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -321,6 +321,7 @@ internal sealed class DashboardBridge : IDashboardHost
|
|||
public int AutoSort => _p.DashAutoSort;
|
||||
public bool AutoSortMoving => _p.DashSortMoving;
|
||||
public bool FightSelectedTarget => _p.DashboardRenderer?.Settings.FightSelectedTarget == true;
|
||||
public bool DebuffAllBeforeAttacking => _p.DashboardRenderer?.Settings.DebuffAllBeforeAttacking == true;
|
||||
public void SetAutoSort(bool on) => Queue(() => _p.SetDashAutoSort(on));
|
||||
public void ToggleSortWindow() => Queue(() => _p.SendSortCommand(string.Empty));
|
||||
public void StartPatrol() => Queue(_p.HandleDungeonNavPatrol);
|
||||
|
|
|
|||
|
|
@ -39,6 +39,8 @@ public sealed partial class RynthAiPlugin
|
|||
{
|
||||
// A meta file that lost data (CallState rules with no target): its load warning.
|
||||
_dashboard?.DrainMetaNotices(line => Host.WriteToChat(line, CommandReply.FailColor));
|
||||
// VirindiTank navs in a folder the nav list doesn't show (LegacyUi/StrayNavs.cs): where they go.
|
||||
_dashboard?.DrainStrayNavNotice(line => Host.WriteToChat(line, CommandReply.FailColor));
|
||||
if (DataWriteGuard.PendingCount == 0) return;
|
||||
DataWriteGuard.DrainChat(line => Host.WriteToChat(line, 2));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,8 +27,16 @@
|
|||
// when it has targets, so the hold could only ever wait on a looter that waits for the fight. The corpse
|
||||
// is looted after the fight, as every corpse is with Boost Loot off; the wait still keeps nav and the
|
||||
// hunt from walking off when no fight is left (the owner's case: running off from the last kill).
|
||||
//
|
||||
// No corpse here (2026-11-20): "in threads it shouldn't wait for the death animation since mobs don't have
|
||||
// corpses, it needs to move as fast as possible". DreamWeave's Thread monsters leave no corpse, so every kill there
|
||||
// stood the character still for the whole wait ("no corpse came in 3.5 s, carrying on"). Learned in the session,
|
||||
// per dungeon landblock and per monster: after NoCorpseSkipAfter kills in a row with no corpse, a kill there (or of
|
||||
// that monster anywhere) starts no wait. A corpse of a kill near the character puts its landblock and its monster
|
||||
// back to waiting.
|
||||
// Pump thread throughout.
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Loot;
|
||||
using RynthCore.Plugin.RynthAi.MonsterStats;
|
||||
|
|
@ -57,6 +65,48 @@ public sealed partial class RynthAiPlugin
|
|||
private int _deathCorpseId; // its corpse, once it came
|
||||
private long _deathCorpseAt;
|
||||
private bool _deathWaitHeld; // HasLootWork's answer this tick (the arbiter's DeathWait input)
|
||||
private uint _deathWaitLandblock; // the dungeon landblock of the kill being waited for (0 outdoors)
|
||||
|
||||
/// <summary>Kills in a row with no corpse after which a landblock or a monster gets no corpse wait.</summary>
|
||||
internal const int NoCorpseSkipAfter = 2;
|
||||
private readonly Dictionary<uint, int> _noCorpseByLandblock = new();
|
||||
private readonly Dictionary<string, int> _noCorpseByName = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>The kills here (a dungeon landblock), or of this monster, have left no corpse lately: no wait.</summary>
|
||||
private bool NoCorpseExpected(uint landblock, string name, out string because)
|
||||
{
|
||||
if (landblock != 0 && _noCorpseByLandblock.TryGetValue(landblock, out int n) && n >= NoCorpseSkipAfter)
|
||||
{
|
||||
because = $"the last {n} kills in landblock 0x{landblock:X4} left no corpse";
|
||||
return true;
|
||||
}
|
||||
if (name.Length > 0 && _noCorpseByName.TryGetValue(name, out int m) && m >= NoCorpseSkipAfter)
|
||||
{
|
||||
because = $"its last {m} kills left no corpse";
|
||||
return true;
|
||||
}
|
||||
because = "";
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>The waited-for kill left no corpse: counted for its landblock and its monster (one line when either stops waiting).</summary>
|
||||
private void NoteNoCorpse()
|
||||
{
|
||||
if (_deathWaitLandblock != 0)
|
||||
{
|
||||
int n = _noCorpseByLandblock.TryGetValue(_deathWaitLandblock, out int was) ? was + 1 : 1;
|
||||
_noCorpseByLandblock[_deathWaitLandblock] = n;
|
||||
if (n == NoCorpseSkipAfter)
|
||||
Host.Log($"[RynthAi] Kill: {n} kills in a row in landblock 0x{_deathWaitLandblock:X4} left no corpse: no corpse wait here until one does.");
|
||||
}
|
||||
if (_deathWaitName.Length > 0)
|
||||
{
|
||||
int m = _noCorpseByName.TryGetValue(_deathWaitName, out int was) ? was + 1 : 1;
|
||||
_noCorpseByName[_deathWaitName] = m;
|
||||
if (m == NoCorpseSkipAfter)
|
||||
Host.Log($"[RynthAi] Kill: '{_deathWaitName}' left no corpse {m} times in a row: no corpse wait for it until one comes.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The death wait can run: the macro and Looting on, and the looter able to loot now.</summary>
|
||||
private bool DeathWaitCanRun(LegacyUiSettings settings)
|
||||
|
|
@ -73,6 +123,14 @@ public sealed partial class RynthAiPlugin
|
|||
{
|
||||
var s = _dashboard?.Settings;
|
||||
if (s == null || !DeathWaitCanRun(s)) return;
|
||||
uint landblock = CurrentLandblockOrZero();
|
||||
string trimmed = name?.Trim() ?? "";
|
||||
if (NoCorpseExpected(landblock, trimmed, out string because))
|
||||
{
|
||||
Host.Log($"[RynthAi] Kill: no wait for the corpse of {(trimmed.Length > 0 ? $"'{trimmed}'" : "the kill")}: {because}.");
|
||||
return;
|
||||
}
|
||||
_deathWaitLandblock = landblock;
|
||||
double? learned = string.IsNullOrWhiteSpace(name) ? null : _xpTable.DeathMs(name);
|
||||
long death = learned is double d ? (long)Math.Round(Math.Clamp(d, 0, DeathWaitMaxDeathMs)) : DeathWaitDefaultMs;
|
||||
_deathWaitMs = death + DeathWaitExtraMs;
|
||||
|
|
@ -114,6 +172,7 @@ public sealed partial class RynthAiPlugin
|
|||
if (_deathCorpseId == 0)
|
||||
{
|
||||
if (since < _deathWaitMs) return true;
|
||||
NoteNoCorpse();
|
||||
EndDeathWait($"no corpse came in {_deathWaitMs / 1000.0:0.0} s, carrying on");
|
||||
return false;
|
||||
}
|
||||
|
|
@ -156,6 +215,10 @@ public sealed partial class RynthAiPlugin
|
|||
if (!Host.HasGetObjectName || !Host.TryGetObjectName(objectId, out string name)) return;
|
||||
string? killed = CorpseTimer.KilledName(name);
|
||||
if (killed == null || !CorpseNearMe(objectId)) return;
|
||||
// Corpses come here after all: this landblock and this monster wait for them again.
|
||||
uint landblock = CurrentLandblockOrZero();
|
||||
if (landblock != 0) _noCorpseByLandblock.Remove(landblock);
|
||||
_noCorpseByName.Remove(killed);
|
||||
if (_corpseTimer.OnCorpse(name, CorpseNowMs) is var (who, ms) && ms <= DeathWaitMaxDeathMs)
|
||||
{
|
||||
_monsterStats.OnCorpseTime(who, ms, DateTime.UtcNow);
|
||||
|
|
|
|||
|
|
@ -121,7 +121,8 @@ public sealed partial class RynthAiPlugin
|
|||
if (ImGui.Combo("Then attack##dfdefault", ref defIdx, DfDefaultLabels, DfDefaultLabels.Length))
|
||||
s.DfDefaultHeight = defIdx - 1;
|
||||
if (!s.DfHeightRotation) ImGui.EndDisabled();
|
||||
Wrapped("Once all three are on, attacks use the Then attack height (Attack Height setting: the Melee "
|
||||
Wrapped("An order with one or two heights puts on just those effects. "
|
||||
+ "Once the effects in the order are on, attacks use the Then attack height (Attack Height setting: the Melee "
|
||||
+ "or Missile Attack Height), and go back to an effect about 5 seconds before it runs out. "
|
||||
+ "Each effect lands on up to 1 hit in 4 and lasts 20 seconds; RynthAi sees it land from the "
|
||||
+ "\"Dirty Fighting! ...\" combat line.", Ui.Mute);
|
||||
|
|
|
|||
|
|
@ -363,7 +363,7 @@ public sealed partial class RynthAiPlugin
|
|||
if (!isRebuild)
|
||||
{
|
||||
if (!settings.IsMacroRunning && RefuseMacroStartForVTank()) return false; // one bot per client (Decal bridge)
|
||||
settings.IsMacroRunning = true;
|
||||
settings.SetMacroRunning(true, "the dungeon explore");
|
||||
// As the patrol: the explore picked its own start; the macro-start "nearest waypoint" pick
|
||||
// on the next tick must not move it (on a walk that ends it would skip rooms).
|
||||
_macroWasRunning = true;
|
||||
|
|
@ -700,7 +700,7 @@ public sealed partial class RynthAiPlugin
|
|||
if (!settings.IsMacroRunning)
|
||||
{
|
||||
if (RefuseMacroStartForVTank()) return;
|
||||
settings.IsMacroRunning = true;
|
||||
settings.SetMacroRunning(true, "the dungeon explore");
|
||||
_macroWasRunning = true;
|
||||
}
|
||||
settings.CurrentNavPath = string.Empty;
|
||||
|
|
@ -1002,7 +1002,7 @@ public sealed partial class RynthAiPlugin
|
|||
if (toward == 0)
|
||||
{
|
||||
if (geo != null && StuckSpot(route, at, from, wx, wy, z, label, lx, ly, "with the next points in its cell too", out spot, out note)) return true;
|
||||
Host.Log($"[RynthAi] {label}: stuck in cell {from:X8} with the next {StuckLookAheadPoints} points in it too: nothing to close");
|
||||
Host.Log($"[RynthAi] {label}: stuck in cell {from:X8} with the next {StuckLookAheadPoints} points in it too: nothing to close{_navigationEngine?.LastStuckNote()}");
|
||||
return false;
|
||||
}
|
||||
var open = closed.Count > 0 ? DungeonPathfinder.WithoutOpenings(graph, new HashSet<ulong>(closed), from) : graph;
|
||||
|
|
@ -1028,7 +1028,7 @@ public sealed partial class RynthAiPlugin
|
|||
string twins = keys.Count > 1 ? $" and {keys.Count - 1} more cell pair(s) through the same opening" : "";
|
||||
string seen = geo != null && geo.TryGetDoorway(a, b, out var dw) ? ThingsInDoorway(landblock, dw, inDoorway) : "";
|
||||
Host.Log($"[RynthAi] {label}: stuck for good at ({lx:F1},{ly:F1},{z:F1}) heading for waypoint {at} (cell {toward:X8}): "
|
||||
+ $"closing the opening between {note}{twins} ({stuckCount + 1} closed){seen}");
|
||||
+ $"closing the opening between {note}{twins} ({stuckCount + 1} closed){seen}{_navigationEngine?.LastStuckNote()}");
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
@ -1051,7 +1051,7 @@ public sealed partial class RynthAiPlugin
|
|||
};
|
||||
note = $"a spot in cell {cell:X8}";
|
||||
Host.Log($"[RynthAi] {label}: stuck for good at ({lx:F1},{ly:F1},{z:F1}) heading for waypoint {at}, {where}: "
|
||||
+ $"walking round the spot ({spot.X:F1},{spot.Y:F1}) {StuckSpotRadius:F1} m round it");
|
||||
+ $"walking round the spot ({spot.X:F1},{spot.Y:F1}) {StuckSpotRadius:F1} m round it{_navigationEngine?.LastStuckNote()}");
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
|
|||
153
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.HuntFence.cs
Normal file
153
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.HuntFence.cs
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
// The hunt fence (2026-11-17): a circle the outdoor hunt picks its monsters inside and combat fights inside.
|
||||
//
|
||||
// DreamWeave's open-world Threads are a circle: 15 m inside its edge the server warns ("The Thread thins
|
||||
// here. Turn back toward its heart."), outside it the Unraveling hurts more every second, and the Thread's
|
||||
// monsters are held to the circle (a hit from a player outside it is refused). The hunt picked monsters by
|
||||
// distance alone and walked out past the edge after them ("In outdoor threads he is going outside of
|
||||
// the thread boundary"). A script reads the circle off the ring of wisps the server sets on its edge and
|
||||
// fences the hunt a margin inside it: /ra hunt fence <x> <y> <radius> (global metres: landblock x * 192 +
|
||||
// local x, as the hunt's own positions), /ra hunt fence off. Not saved: a script sets it for the place it
|
||||
// is in, and clears it when it leaves.
|
||||
//
|
||||
// A walk is fenced too (same day: "here and there nav takes him outside of the thread boundary"): to a
|
||||
// monster inside the fence, the way round a building can swing out past the edge. An optional fourth number
|
||||
// is how far out a walk may go (default the fence and 15 m); a walk whose corners go out past it, farther
|
||||
// out than where the character stands, is no walk (the monster is left out a while, as one with no way to it).
|
||||
// From outside it a walk back in is still a walk.
|
||||
//
|
||||
// The hunt (OutdoorHunt.Fence) leaves a monster outside the fence out of its picks; combat
|
||||
// (CombatManager.SkipTarget) leaves one out of its targets, unless it is the one
|
||||
// being fought or the player's own target lock.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
public sealed partial class RynthAiPlugin
|
||||
{
|
||||
/// <summary>The fence (centre and radius, global metres), or null: none.</summary>
|
||||
internal (double X, double Y, double R)? HuntFence { get; private set; }
|
||||
/// <summary>How far from the fence's centre a walk may go (metres).</summary>
|
||||
internal double HuntFenceWalkR { get; private set; }
|
||||
|
||||
/// <summary>A walk may go this much past the fence when the fence is given without its walk radius.</summary>
|
||||
internal const double HuntFenceWalkDefaultM = 15.0;
|
||||
|
||||
internal const string HuntFenceUsage = "[RynthAi] Usage: /ra hunt fence <x> <y> <radius> [walk radius] (global metres: landblock x * 192 + local x) or /ra hunt fence off";
|
||||
|
||||
/// <summary>OutdoorHunt.WalkFence: no corner out past the walk radius farther out than where it starts (me).</summary>
|
||||
internal bool WalkInHuntFence(OutdoorHunt.Vec me, IReadOnlyList<OutdoorHunt.Vec> corners)
|
||||
{
|
||||
if (FenceHere() is not { } f || corners.Count == 0) return true;
|
||||
double Out(OutdoorHunt.Vec v) => Math.Sqrt((v.X - f.X) * (v.X - f.X) + (v.Y - f.Y) * (v.Y - f.Y));
|
||||
double start = Out(me);
|
||||
foreach (var c in corners)
|
||||
{
|
||||
double d = Out(c);
|
||||
if (d > HuntFenceWalkR && d > start + 2.0) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>True when (x, y) (global metres) is inside the fence, or there is none (or it was for another place).</summary>
|
||||
internal bool InHuntFence(double x, double y)
|
||||
=> FenceHere() is not { } f || (x - f.X) * (x - f.X) + (y - f.Y) * (y - f.Y) <= f.R * f.R;
|
||||
|
||||
/// <summary>A monster this near the character is fought, fence or not.</summary>
|
||||
internal const double FenceFightNearM = 10.0;
|
||||
/// <summary>Outside the fence, a monster no more than this farther from its middle than the character (up to the walk radius) is fought.</summary>
|
||||
internal const double FenceFightOutM = 5.0;
|
||||
/// <summary>The character this far past the walk radius: the fence was for another place, and is lifted.</summary>
|
||||
internal const double FenceForgetM = 300.0;
|
||||
|
||||
/// <summary>
|
||||
/// CombatManager.SkipTarget's fence half: a monster outside the fence is left alone, unless it is near
|
||||
/// the character or no farther out than the character stands (FenceFightOutM, up to the walk radius).
|
||||
/// 2026-11-17 16:40, DreamWeave Thread 32D9: the character stood 127 m from the middle of a 124 m fence,
|
||||
/// among the Thread's monsters, all outside it; combat took none of them ("possible=0"), and it stood
|
||||
/// there being hit until it died ("he's just standing there not attacking").
|
||||
/// </summary>
|
||||
internal bool FenceSkipsTarget(int id)
|
||||
{
|
||||
if (FenceHere() is not { } f) return false;
|
||||
if (!Host.TryGetObjectPosition(unchecked((uint)id), out uint c, out float x, out float y, out _)) return false;
|
||||
double gx = ((c >> 24) & 0xFF) * 192.0 + x, gy = ((c >> 16) & 0xFF) * 192.0 + y;
|
||||
bool hasMe = TryHuntPosition(out _, out var me);
|
||||
return FenceSkips(f, HuntFenceWalkR, gx, gy, hasMe, me.X, me.Y);
|
||||
}
|
||||
|
||||
/// <summary>The pure half of <see cref="FenceSkipsTarget"/>.</summary>
|
||||
internal static bool FenceSkips((double X, double Y, double R) f, double walkR, double gx, double gy, bool hasMe, double mx, double my)
|
||||
{
|
||||
double dMon = Math.Sqrt((gx - f.X) * (gx - f.X) + (gy - f.Y) * (gy - f.Y));
|
||||
if (dMon <= f.R) return false;
|
||||
if (!hasMe) return true;
|
||||
if (Math.Sqrt((gx - mx) * (gx - mx) + (gy - my) * (gy - my)) <= FenceFightNearM) return false;
|
||||
double dMe = Math.Sqrt((mx - f.X) * (mx - f.X) + (my - f.Y) * (my - f.Y));
|
||||
return dMon > Math.Min(dMe + FenceFightOutM, Math.Max(walkR, f.R));
|
||||
}
|
||||
|
||||
private long _fenceCheckedAt;
|
||||
|
||||
/// <summary>
|
||||
/// The fence, for where the character is: null when there is none, and lifted when the character is in a
|
||||
/// dungeon or far past it (FenceForgetM). 2026-11-17 16:42, the fence of Thread 32D9 outlived the Thread
|
||||
/// (the script lost it with the Thread at a death): in the next Thread, a dungeon, every monster was
|
||||
/// outside it, and combat fought none ("he died because he isn't fighting").
|
||||
/// </summary>
|
||||
internal (double X, double Y, double R)? FenceHere()
|
||||
{
|
||||
if (HuntFence is not { } f) return null;
|
||||
long now = Environment.TickCount64;
|
||||
if (now - _fenceCheckedAt < 500) return f;
|
||||
_fenceCheckedAt = now;
|
||||
if (!TryHuntPosition(out uint cell, out var me)) return f;
|
||||
double d = Math.Sqrt((me.X - f.X) * (me.X - f.X) + (me.Y - f.Y) * (me.Y - f.Y));
|
||||
bool dungeon = OutdoorHunt.IsIndoorCell(cell) && InDungeon(cell);
|
||||
if (!dungeon && d <= Math.Max(HuntFenceWalkR, f.R) + FenceForgetM) return f;
|
||||
HuntFence = null;
|
||||
HuntFenceWalkR = 0;
|
||||
Host.Log(string.Format(CultureInfo.InvariantCulture, "[RynthAi] Hunt fence: lifted ({0}): it was for another place.",
|
||||
dungeon ? "in a dungeon" : $"{d:0} m from its middle"));
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>/ra hunt fence <x> <y> <radius> | off (parts[3..]).</summary>
|
||||
private void SetHuntFence(string[] parts)
|
||||
{
|
||||
string a = parts.Length > 3 ? parts[3].Trim().ToLowerInvariant() : "";
|
||||
if (a is "off" or "none" or "clear")
|
||||
{
|
||||
bool had = HuntFence != null;
|
||||
HuntFence = null;
|
||||
HuntFenceWalkR = 0;
|
||||
ChatLine(had ? "[RynthAi] Hunt fence: off." : "[RynthAi] Hunt fence: there was none.");
|
||||
return;
|
||||
}
|
||||
var inv = CultureInfo.InvariantCulture;
|
||||
if (parts.Length < 6
|
||||
|| !double.TryParse(parts[3], NumberStyles.Float, inv, out double x)
|
||||
|| !double.TryParse(parts[4], NumberStyles.Float, inv, out double y)
|
||||
|| !double.TryParse(parts[5], NumberStyles.Float, inv, out double r)
|
||||
|| double.IsNaN(x) || double.IsNaN(y) || double.IsNaN(r) || r <= 0)
|
||||
{
|
||||
ChatLine(a == "" && HuntFence is { } f
|
||||
? string.Format(inv, "[RynthAi] Hunt fence: {0:0.0} m round {1:0.0}, {2:0.0}.", f.R, f.X, f.Y)
|
||||
: HuntFenceUsage);
|
||||
return;
|
||||
}
|
||||
double walk = r + HuntFenceWalkDefaultM;
|
||||
if (parts.Length > 6 && double.TryParse(parts[6], NumberStyles.Float, inv, out double w) && w >= r) walk = w;
|
||||
HuntFence = (x, y, r);
|
||||
HuntFenceWalkR = walk;
|
||||
string where = "";
|
||||
if (TryHuntPosition(out _, out var me))
|
||||
{
|
||||
double d = Math.Sqrt((me.X - x) * (me.X - x) + (me.Y - y) * (me.Y - y));
|
||||
where = string.Format(inv, "; you are {0:0} m from its middle{1}", d, d > r ? " (outside it)" : "");
|
||||
}
|
||||
ChatLine(string.Format(inv, "[RynthAi] Hunt fence: {0:0.0} m round {1:0.0}, {2:0.0}, walks to {3:0.0} m{4}.", r, x, y, walk, where));
|
||||
}
|
||||
}
|
||||
422
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Kits.cs
Normal file
422
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Kits.cs
Normal file
|
|
@ -0,0 +1,422 @@
|
|||
using System;
|
||||
using System.Globalization;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.MiniRemote;
|
||||
using RynthCore.Plugin.RynthAi.MiniRemote.Crafting;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
// Make kits (a players' request, 2026-11-22): /ra kits [status|make [N]|stop|floor <0-100>|show].
|
||||
// The work is MiniRemote/Crafting/KitRunner.cs (ticked by the Crafting tab); the main path is the
|
||||
// Mini Remote's Crafting tab, Kits sub-tab, "Make kits". Kits are made by hand only while the macro is off.
|
||||
//
|
||||
// Make kits when low (MakeKitsWhenLow, off by default; /ra kits auto ...): with the macro on, the
|
||||
// Crafting tab's KitAuto decides when a run may start (MiniRemote/Crafting/KitAuto.cs) from the
|
||||
// facts read here, and while one gets ready or goes the rest of the tick waits, as it does for buffs
|
||||
// (TickAutoKits, right after the Buffing hold). Right after the arbiter's decision, ahead of every
|
||||
// hold, CheckAutoKitsDanger stops a run at once on a monster within the safe radius, buffing or a
|
||||
// heal line, a fight, a portal; KitRunner itself stops on a hit, moving, leaving peace or the macro off.
|
||||
public sealed partial class RynthAiPlugin
|
||||
{
|
||||
internal const string KitsUsage = "Usage: /ra kits [status | make [count] | stop | floor <0-100> | show | auto [on|off|status|below N|upto M]]";
|
||||
internal const string KitsAutoUsage = "Usage: /ra kits auto [status | on | off | below <1-50> | upto <1-100>]";
|
||||
|
||||
/// <summary>/ra kits: status (the default), make [count], stop, floor <percent>, show (the Kits tab), auto ....</summary>
|
||||
private void HandleKitsCommand(string[] parts)
|
||||
{
|
||||
string verb = parts.Length > 2 ? parts[2].Trim().ToLowerInvariant() : "status";
|
||||
if (verb is not ("status" or "make" or "stop" or "floor" or "show" or "auto"))
|
||||
{
|
||||
ReplyFail($"[RynthAi] Make kits: unknown option '{parts[2]}'. {KitsUsage}");
|
||||
return;
|
||||
}
|
||||
if (verb == "auto") { HandleKitsAutoCommand(parts); return; }
|
||||
var remote = _miniRemote;
|
||||
if (remote == null) { ReplyFail("[RynthAi] Make kits: not ready yet (log in first)."); return; }
|
||||
var tab = remote.Crafting;
|
||||
var kits = tab.Kits;
|
||||
|
||||
switch (verb)
|
||||
{
|
||||
case "status":
|
||||
{
|
||||
var rows = kits.RefreshPlan();
|
||||
foreach (var row in rows) ChatLine("[RynthAi] Make kits: " + KitPlanner.Line(row));
|
||||
ChatLine($"[RynthAi] Make kits: {(kits.Running ? kits.Status : "not running")}; floor {kits.Floor}%. "
|
||||
+ "Mini Remote > Crafting > Kits, or /ra kits make.");
|
||||
ChatLine(KitsAutoStatusLine());
|
||||
break;
|
||||
}
|
||||
case "make":
|
||||
{
|
||||
int count = 0;
|
||||
if (parts.Length > 3 && !parts[3].Equals("all", StringComparison.OrdinalIgnoreCase)
|
||||
&& (!int.TryParse(parts[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out count) || count < 1))
|
||||
{
|
||||
ReplyFail($"[RynthAi] Make kits: the count must be a number of 1 or more, or 'all' (got '{parts[3]}'). {KitsUsage}");
|
||||
break;
|
||||
}
|
||||
var recipe = kits.Find(null);
|
||||
if (recipe == null) { ReplyFail("[RynthAi] Make kits: no kit recipe is known."); break; }
|
||||
int can = KitPlanner.CanMake(recipe, kits.Pack());
|
||||
string why = kits.Start(recipe, count);
|
||||
if (why.Length > 0) { ReplyFail($"[RynthAi] Make kits: can't start - {why}."); break; }
|
||||
int target = count > 0 ? Math.Min(count, can) : can;
|
||||
ReplyOk($"[RynthAi] Make kits: making up to {target} {recipe.Name}(s), floor {kits.Floor}%. /ra kits stop to stop.");
|
||||
break;
|
||||
}
|
||||
case "stop":
|
||||
if (!kits.Running) { ReplyOk("[RynthAi] Make kits: nothing is running."); break; }
|
||||
kits.Stop("stopped by you");
|
||||
Reply.Answered(); // Stop printed the summary line
|
||||
break;
|
||||
case "floor":
|
||||
{
|
||||
if (parts.Length < 4)
|
||||
{
|
||||
ReplyOk($"[RynthAi] Make kits: the floor is {kits.Floor}% (no combine under it is tried). {KitsUsage}");
|
||||
break;
|
||||
}
|
||||
string text = parts[3].Trim().TrimEnd('%');
|
||||
if (!int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out int pct) || pct < 0 || pct > 100)
|
||||
{
|
||||
ReplyFail($"[RynthAi] Make kits: the floor must be 0-100 (got '{parts[3]}'). {KitsUsage}");
|
||||
break;
|
||||
}
|
||||
remote.State.Crafting.KitMinChancePercent = pct;
|
||||
ReplyOk($"[RynthAi] Make kits: floor set to {pct}%" + (pct == 0 ? " (any chance)." : "."));
|
||||
break;
|
||||
}
|
||||
case "show":
|
||||
{
|
||||
tab.SelectKitsTab();
|
||||
string? reply = remote.MiniRemoteTabCommand?.Invoke(MiniRemoteTabs.Crafting, "show");
|
||||
if (reply == null) ReplyFail("[RynthAi] Make kits: the Mini Remote isn't available yet.");
|
||||
else ReplyOk("[RynthAi] Make kits: " + reply);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── /ra kits auto ───────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>/ra kits auto [status | on | off | below N | upto M]: Make kits when low (a profile setting).</summary>
|
||||
private void HandleKitsAutoCommand(string[] parts)
|
||||
{
|
||||
var settings = _dashboard?.Settings;
|
||||
if (settings == null) { ReplyFail("[RynthAi] Make kits when low: not ready yet (log in first)."); return; }
|
||||
string verb = parts.Length > 3 ? parts[3].Trim().ToLowerInvariant() : "status";
|
||||
var auto = _miniRemote?.Crafting.AutoKits;
|
||||
switch (verb)
|
||||
{
|
||||
case "status":
|
||||
ChatLine(KitsAutoStatusLine()); // the status asked for
|
||||
break;
|
||||
case "on":
|
||||
case "off":
|
||||
{
|
||||
bool on = verb == "on";
|
||||
settings.MakeKitsWhenLow = on;
|
||||
_dashboard?.SaveSettings();
|
||||
if (on) auto?.LookNow();
|
||||
else
|
||||
{
|
||||
var kits = _miniRemote?.Crafting.Kits;
|
||||
if (kits != null && kits.Auto) kits.Stop("Make kits when low turned off", KitStopKind.Other);
|
||||
auto?.Off();
|
||||
}
|
||||
ReplyOk($"[RynthAi] Make kits when low: {verb} (under {Below(settings)} kits, make up to {UpTo(settings)})"
|
||||
+ (on && !settings.IsMacroRunning ? "; it works while the macro runs." : "."));
|
||||
break;
|
||||
}
|
||||
case "below":
|
||||
case "upto":
|
||||
{
|
||||
int max = verb == "below" ? KitAuto.MaxBelow : KitAuto.MaxUpTo;
|
||||
if (parts.Length < 5)
|
||||
{
|
||||
ReplyOk($"[RynthAi] Make kits when low: {(verb == "below" ? $"starts under {Below(settings)} kits" : $"makes up to {UpTo(settings)} kits a run")}. {KitsAutoUsage}");
|
||||
break;
|
||||
}
|
||||
if (!int.TryParse(parts[4].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int n) || n < 1 || n > max)
|
||||
{
|
||||
ReplyFail($"[RynthAi] Make kits when low: {verb} must be a number from 1 to {max} (got '{parts[4]}'). {KitsAutoUsage}");
|
||||
break;
|
||||
}
|
||||
if (verb == "below") settings.MakeKitsBelow = n; else settings.MakeKitsUpTo = n;
|
||||
_dashboard?.SaveSettings();
|
||||
auto?.LookNow();
|
||||
ReplyOk(verb == "below"
|
||||
? $"[RynthAi] Make kits when low: starts when you carry fewer than {n} kits{(settings.MakeKitsWhenLow ? "." : " (it is off: /ra kits auto on).")}"
|
||||
: $"[RynthAi] Make kits when low: makes up to {n} kits a run{(settings.MakeKitsWhenLow ? "." : " (it is off: /ra kits auto on).")}");
|
||||
break;
|
||||
}
|
||||
default:
|
||||
ReplyFail($"[RynthAi] Make kits when low: unknown option '{parts[3]}'. {KitsAutoUsage}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static int Below(LegacyUiSettings s) => Math.Clamp(s.MakeKitsBelow, 1, KitAuto.MaxBelow);
|
||||
private static int UpTo(LegacyUiSettings s) => Math.Clamp(s.MakeKitsUpTo, 1, KitAuto.MaxUpTo);
|
||||
|
||||
/// <summary>One line: the setting, its numbers, the radius and what it is doing.</summary>
|
||||
private string KitsAutoStatusLine()
|
||||
{
|
||||
var s = _dashboard?.Settings;
|
||||
if (s == null) return "[RynthAi] Make kits when low: not ready yet (log in first).";
|
||||
string state = !s.MakeKitsWhenLow ? "off" : "on";
|
||||
string doing = "";
|
||||
var tab = _miniRemote?.Crafting;
|
||||
if (s.MakeKitsWhenLow && tab != null) doing = "; " + tab.AutoStatusText(s);
|
||||
return $"[RynthAi] Make kits when low: {state}, under {Below(s)} kits make up to {UpTo(s)}, "
|
||||
+ $"no monster within {KitSafeRadiusYd(s):0} yd{doing}. Mini Remote > Crafting > Kits, /ra kits auto on|off.";
|
||||
}
|
||||
|
||||
// ── Make kits when low: the macro side ──────────────────────────────────
|
||||
|
||||
/// <summary>No monster this close for a start, and one coming this close stops a run: 35 yd, or Monster Range when bigger.</summary>
|
||||
internal static double KitSafeRadiusYd(LegacyUiSettings s) => Math.Max(KitAuto.DefaultRadiusYd, s.MonsterRange);
|
||||
|
||||
/// <summary>The world walk for monsters is this far apart while nothing is going (the scan list is read every time).</summary>
|
||||
private const long KitMonsterWalkMs = 500;
|
||||
private long _kitMonsterWalkAt = long.MinValue / 2;
|
||||
private double _kitMonsterWalkYd = double.PositiveInfinity;
|
||||
private uint _kitLastHealth;
|
||||
private long _kitHurtAt = long.MinValue / 2;
|
||||
private bool _kitPoseKnown;
|
||||
private uint _kitPoseCell;
|
||||
private float _kitPoseX, _kitPoseY, _kitPoseZ;
|
||||
private bool _kitMoving;
|
||||
/// <summary>Moving more than this between two ticks counts as moving (KitRunner stops past 1.5 m from the start).</summary>
|
||||
private const float KitMoveEpsilon = 0.15f;
|
||||
|
||||
private long KitNow() => _miniRemote?.Crafting.AutoKits.NowMs() ?? Environment.TickCount64;
|
||||
|
||||
/// <summary>
|
||||
/// Every in-world tick, right after the arbiter's decision and ahead of every hold: notes a hit and
|
||||
/// a move, and stops a "when low" run at once when a monster comes within the radius, buffing or a
|
||||
/// heal is wanted, a fight starts or a portal is taken.
|
||||
/// </summary>
|
||||
private void CheckAutoKitsDanger(LegacyUiSettings s)
|
||||
{
|
||||
long now = KitNow();
|
||||
TrackKitHurtAndMove(now);
|
||||
var kits = _miniRemote?.Crafting.Kits;
|
||||
if (kits == null || !kits.Auto) return;
|
||||
var f = new KitAutoFacts
|
||||
{
|
||||
Enabled = true,
|
||||
MacroOn = s.IsMacroRunning,
|
||||
BusyWhy = KitBusyWhy(s, starting: false),
|
||||
VitalsWhy = KitVitalsWhy(s),
|
||||
RadiusYd = KitSafeRadiusYd(s),
|
||||
};
|
||||
// The combat scan (kept fresh by the hold) is read every tick; the world walk past it every half second.
|
||||
if (f.BusyWhy.Length == 0 && f.VitalsWhy.Length == 0) f.NearestMonsterYd = NearestMonsterYards(f.RadiusYd, now, force: false);
|
||||
string why = KitAuto.StopReason(f);
|
||||
if (why.Length > 0) kits.Stop(why, KitStopKind.Danger);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Make kits when low, after the Buffing hold: true while a run gets ready or goes, and the rest of
|
||||
/// the tick (combat, looting, navigation, item chores) waits, as it does for buffs.
|
||||
/// </summary>
|
||||
private bool TickAutoKits(LegacyUiSettings s)
|
||||
{
|
||||
var tab = _miniRemote?.Crafting;
|
||||
if (tab == null) return false;
|
||||
var kits = tab.Kits;
|
||||
var auto = tab.AutoKits;
|
||||
if (kits.Running)
|
||||
{
|
||||
if (!kits.Auto) return false; // a run by hand (the macro is off then)
|
||||
auto.Running(kits.MadeCount, kits.Limit);
|
||||
return s.IsMacroRunning;
|
||||
}
|
||||
if (!s.MakeKitsWhenLow) { if (auto.Status != "off") auto.Off(); return false; }
|
||||
|
||||
long now = auto.NowMs();
|
||||
KitAutoStep step = auto.Decide(() => KitStartFacts(s, kits, now, readying: auto.Readying));
|
||||
switch (step)
|
||||
{
|
||||
case KitAutoStep.GoPeace:
|
||||
Host.ChangeCombatModeFor(CombatMode.NonCombat, "Kits", "peace mode for Make kits when low");
|
||||
return true;
|
||||
case KitAutoStep.Hold:
|
||||
return true;
|
||||
case KitAutoStep.Start:
|
||||
{
|
||||
var recipe = kits.Find(null);
|
||||
if (recipe == null) { auto.StartRefused("no kit recipe is known"); return false; }
|
||||
string why = kits.StartAuto(recipe, UpTo(s), (kind, made) => auto.RunEnded(kind, made));
|
||||
if (why.Length > 0) { auto.StartRefused(why); return false; }
|
||||
auto.Running(0, UpTo(s));
|
||||
return true;
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One full look for a start (KitAuto reads it only when a look is due).</summary>
|
||||
private KitAutoFacts KitStartFacts(LegacyUiSettings s, KitRunner kits, long now, bool readying)
|
||||
{
|
||||
var f = new KitAutoFacts
|
||||
{
|
||||
Enabled = s.MakeKitsWhenLow,
|
||||
MacroOn = s.IsMacroRunning,
|
||||
Below = Below(s),
|
||||
RadiusYd = KitSafeRadiusYd(s),
|
||||
};
|
||||
if (!f.Enabled || !f.MacroOn) return f;
|
||||
var pack = kits.Pack();
|
||||
f.Kits = KitPlanner.Count(KitPlanner.PlentifulHealingKit, pack);
|
||||
if (f.Kits >= f.Below) return f;
|
||||
// Getting ready, the client is busy with our own peace-mode switch: not a reason to give up.
|
||||
f.BusyWhy = KitBusyWhy(s, starting: true, clientBusyCounts: !readying);
|
||||
f.VitalsWhy = KitVitalsWhy(s);
|
||||
f.NearestMonsterYd = NearestMonsterYards(f.RadiusYd, now, force: false);
|
||||
f.SinceHurtMs = _kitHurtAt <= long.MinValue / 4 ? long.MaxValue : Math.Max(0, now - _kitHurtAt);
|
||||
var recipe = kits.Find(null);
|
||||
if (recipe == null) f.PackWhy = "no kit recipe is known";
|
||||
else
|
||||
{
|
||||
var next = KitPlanner.Next(recipe, pack, kits.Skill, kits.Floor);
|
||||
f.PackWhy = next.Step == null ? next.Why : string.Empty;
|
||||
}
|
||||
try { f.InPeace = !Host.HasGetCurrentCombatMode || Host.GetCurrentCombatMode() == CombatMode.NonCombat; }
|
||||
catch { f.InPeace = false; }
|
||||
f.Moving = _kitMoving;
|
||||
return f;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What else has the character ("" = nothing): buffing or healing, a fight, a portal, a vendor or
|
||||
/// trade; for a start also looting, salvaging, other item work, following, travelling back to the
|
||||
/// corpse, or a busy client.
|
||||
/// </summary>
|
||||
private string KitBusyWhy(LegacyUiSettings s, bool starting, bool clientBusyCounts = true)
|
||||
{
|
||||
if (_activity == BotActivity.Buffing || (_buffManager != null && _buffManager.PendingSpellId != 0)) return "buffing or healing";
|
||||
var combat = _combatManager;
|
||||
if (_activity == BotActivity.Combat || FightIsOn(s) || (combat != null && (combat.IsActivelyEngaged || combat.IsUnderCloseAttack))) return "a fight";
|
||||
try { if (Host.HasIsPortaling && Host.IsPortaling()) return "in portal space"; } catch { }
|
||||
if (_navigationEngine?.IsInPortalAction == true) return "taking a portal";
|
||||
if (_autoVendor?.HoldsBot == true || _autoTrade?.HoldsBot == true) return "at a vendor or a trade";
|
||||
if (!starting) return string.Empty;
|
||||
if (_activity == BotActivity.Looting || _lastWantLoot || _openedContainerId != 0 || _targetCorpseId != 0) return "looting";
|
||||
if (_activity == BotActivity.Salvaging || _salvageManager?.IsBusy == true) return "salvaging";
|
||||
if (_missileCraftingManager?.IsCrafting == true) return "crafting ammunition";
|
||||
if (_aetheriaUnboxer?.IsUnboxing == true) return "unboxing aetheria";
|
||||
if (_scrollLearner?.IsReading == true) return "reading a scroll";
|
||||
if (IsFollowActive(s)) return "following";
|
||||
if (OwnCorpseTravelHoldsNav) return "travelling back to your corpse";
|
||||
if (clientBusyCounts && PacedBusy > 0) return "busy";
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>"" when health, stamina and mana are over their lines (and no heal or recharge is wanted); else which.</summary>
|
||||
private string KitVitalsWhy(LegacyUiSettings s)
|
||||
{
|
||||
if (_buffManager?.WantsVitalRecharge == true) return "healing or restoring vitals";
|
||||
uint h = 0, mh = 0, st = 0, mst = 0, m = 0, mm = 0;
|
||||
try { if (!Host.HasGetPlayerVitals || !Host.TryGetPlayerVitals(out h, out mh, out st, out mst, out m, out mm)) return string.Empty; }
|
||||
catch { return string.Empty; }
|
||||
if (mh > 0)
|
||||
{
|
||||
int hp = (int)(h * 100UL / mh);
|
||||
int line = Math.Max(s.HealAt, Math.Max(s.EmergencyHealAt, s.StaminaToHealthAt));
|
||||
if (hp <= line) return $"health {hp}% (Heal At {line}%)";
|
||||
}
|
||||
if (mst > 0)
|
||||
{
|
||||
int sp = (int)(st * 100UL / mst);
|
||||
if (sp <= s.RestamAt) return $"stamina {sp}% (Re-stam At {s.RestamAt}%)";
|
||||
}
|
||||
if (mm > 0)
|
||||
{
|
||||
int mp = (int)(m * 100UL / mm);
|
||||
if (mp <= s.GetManaAt) return $"mana {mp}% (Get Mana At {s.GetManaAt}%)";
|
||||
}
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The nearest live monster: the combat scan (within Monster Range, a clear line) and, at most every
|
||||
/// half second unless <paramref name="force"/>, the world cache (any line, past Monster Range).
|
||||
/// PositiveInfinity when none is known.
|
||||
/// </summary>
|
||||
private double NearestMonsterYards(double within, long now, bool force)
|
||||
{
|
||||
double best = double.PositiveInfinity;
|
||||
var combat = _combatManager;
|
||||
if (combat != null)
|
||||
{
|
||||
var scanned = combat.ScannedTargets;
|
||||
for (int i = 0; i < scanned.Count; i++)
|
||||
if (scanned[i].Distance < best) best = scanned[i].Distance;
|
||||
if (best > within && combat.HasCloseThreat(within)) best = within; // a predicted kill still alive
|
||||
}
|
||||
if (force || now - _kitMonsterWalkAt >= KitMonsterWalkMs)
|
||||
{
|
||||
_kitMonsterWalkAt = now;
|
||||
_kitMonsterWalkYd = WorldMonsterYards();
|
||||
}
|
||||
return Math.Min(best, _kitMonsterWalkYd);
|
||||
}
|
||||
|
||||
/// <summary>The nearest live, fightable monster in the world cache (PositiveInfinity = none).</summary>
|
||||
private double WorldMonsterYards()
|
||||
{
|
||||
var cache = _objectCache;
|
||||
uint me = _playerId;
|
||||
if (cache == null || me == 0) return double.PositiveInfinity;
|
||||
double best = double.PositiveInfinity;
|
||||
foreach (var wo in cache.GetLandscapeObjects())
|
||||
{
|
||||
if (wo.ObjectClass != AcObjectClass.Monster) continue;
|
||||
if (cache.GetHealthRatio(wo.Id) == 0f) continue; // dead
|
||||
double d = cache.Distance(unchecked((int)me), wo.Id);
|
||||
if (!(d < best)) continue;
|
||||
if (!IsFightableCreature(unchecked((uint)wo.Id))) continue;
|
||||
best = d;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>Health going down is a hit (for "no hit for 20 s"); the pose changing between ticks is moving.</summary>
|
||||
private void TrackKitHurtAndMove(long now)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Host.HasGetPlayerVitals && Host.TryGetPlayerVitals(out uint h, out _, out _, out _, out _, out _))
|
||||
{
|
||||
if (_kitLastHealth > 0 && h > 0 && h < _kitLastHealth) _kitHurtAt = now;
|
||||
_kitLastHealth = h;
|
||||
}
|
||||
if (Host.TryGetPlayerPose(out uint cell, out float x, out float y, out float z, out _, out _, out _, out _))
|
||||
{
|
||||
float dx = x - _kitPoseX, dy = y - _kitPoseY, dz = z - _kitPoseZ;
|
||||
_kitMoving = _kitPoseKnown && (cell != _kitPoseCell || dx * dx + dy * dy + dz * dz > KitMoveEpsilon * KitMoveEpsilon);
|
||||
_kitPoseKnown = true;
|
||||
_kitPoseCell = cell;
|
||||
_kitPoseX = x; _kitPoseY = y; _kitPoseZ = z;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
/// <summary>Logout: this character's hit and pose notes go.</summary>
|
||||
private void ResetKitTracking()
|
||||
{
|
||||
_kitLastHealth = 0;
|
||||
_kitHurtAt = long.MinValue / 2;
|
||||
_kitPoseKnown = false;
|
||||
_kitMoving = false;
|
||||
_kitMonsterWalkAt = long.MinValue / 2;
|
||||
_kitMonsterWalkYd = double.PositiveInfinity;
|
||||
}
|
||||
}
|
||||
251
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LootPerDay.cs
Normal file
251
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LootPerDay.cs
Normal file
|
|
@ -0,0 +1,251 @@
|
|||
// ============================================================================
|
||||
// RynthAi - RynthAiPlugin.LootPerDay.cs
|
||||
// "Keep # per day" (2026-11-22, RynthCore.Loot.LootPerDay): a Keep # rule with
|
||||
// a window (24 h by default) takes at most its count of matching items picked
|
||||
// up in any such window, counted by what this character picked up, not by
|
||||
// what the pack holds (treasure maps get used or sold). An item over the count
|
||||
// is left like any item no rule wants.
|
||||
//
|
||||
// Flow: the classifier approves an item while the window's pickups plus the
|
||||
// items approved and not landed yet are under the count (_pendingPerDay);
|
||||
// the send moves it to _perDayInFlight; the landing (the pickup confirmed, a
|
||||
// late landing, a ground pickup) records it in the character's
|
||||
// LootPerDayStore (Loot/LootPerDayStore.cs), saved at once, so the count
|
||||
// survives reloads and relogs.
|
||||
//
|
||||
// Shown: the Loot Editor's rule view (option, help line, today's count, a
|
||||
// reset button) and /ra loot today [clear <rule>|clear all].
|
||||
// ============================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Loot.VTank;
|
||||
using RynthCore.Plugin.RynthAi.Loot;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
public sealed partial class RynthAiPlugin
|
||||
{
|
||||
/// <summary>The time pickups are stamped with (UTC). Host tests move it.</summary>
|
||||
internal static Func<DateTime> PerDayClock = static () => DateTime.UtcNow;
|
||||
|
||||
// Approved this corpse (or ground scan), not sent yet: counted while fresh.
|
||||
private readonly Dictionary<int, (string Key, int Units, long At)> _pendingPerDay = new();
|
||||
// Sent: counted until it lands (recorded) or the late-landing watch gives up on it.
|
||||
private readonly Dictionary<int, (string Key, int Units, long Until)> _perDayInFlight = new();
|
||||
private const long PerDayPendingMs = 120_000;
|
||||
private const long PerDayInFlightMs = 120_000;
|
||||
|
||||
private LootPerDayStore? _lootPerDay;
|
||||
private string _lootPerDayFolder = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// The store of the character logged in (SettingsProfiles\<server>\<character>\loot_per_day.json),
|
||||
/// loaded on first use and again when the character changes. Before login: an in-memory one.
|
||||
/// </summary>
|
||||
internal LootPerDayStore PerDayStore()
|
||||
{
|
||||
string folder = _dashboard?.CharFolder ?? string.Empty;
|
||||
if (_lootPerDay != null && string.Equals(folder, _lootPerDayFolder, StringComparison.OrdinalIgnoreCase))
|
||||
return _lootPerDay;
|
||||
_lootPerDay ??= new LootPerDayStore();
|
||||
_lootPerDayFolder = folder;
|
||||
_lootPerDay.Load(folder.Length == 0 ? string.Empty : Path.Combine(folder, LootPerDayStore.FileName), PerDayClock());
|
||||
if (_lootPerDay.Problem.Length > 0)
|
||||
Host.Log($"[RynthAi] Keep # per day: could not read the pickup counts ({_lootPerDay.Problem}); starting from none.");
|
||||
return _lootPerDay;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Keep # per day: true while fewer than <paramref name="cap"/> units were picked up for
|
||||
/// <paramref name="key"/> in the last <paramref name="hours"/>, counting items approved or on
|
||||
/// their way that haven't landed yet. At the count the item is left (and said, once per item).
|
||||
/// </summary>
|
||||
private bool UnderDailyCap(string key, string ruleLabel, WorldObject item, int cap, int hours, bool preview = false)
|
||||
{
|
||||
long nowMs = CorpseNowMs;
|
||||
if (_pendingPerDay.TryGetValue(item.Id, out var mine) && nowMs - mine.At < PerDayPendingMs) return true;
|
||||
if (_perDayInFlight.ContainsKey(item.Id)) return true;
|
||||
|
||||
DateTime now = PerDayClock();
|
||||
LootPerDayStore store = PerDayStore();
|
||||
int have = store.Count(key, hours, now) + NotLandedYet(key, item.Id, nowMs);
|
||||
if (preview) return LootKeepCap.UnderCap(have, cap);
|
||||
string window = LootPerDay.WindowText(hours);
|
||||
if (!LootKeepCap.UnderCap(have, cap))
|
||||
{
|
||||
_corpseCappedIds.Add(item.Id);
|
||||
TimeSpan? next = store.NextFree(key, hours, cap, now);
|
||||
ChatLine($"[RynthAi] Keep # per day '{ruleLabel}': {have}/{cap} picked up in the last {window}"
|
||||
+ (next is TimeSpan t && t > TimeSpan.Zero ? $" (the next in {LootPerDayStore.Duration(t)})" : string.Empty)
|
||||
+ $" — leaving {item.Name}.");
|
||||
return false;
|
||||
}
|
||||
int stack = LootKeepCap.StackOf(item);
|
||||
_pendingPerDay[item.Id] = (key, stack, nowMs);
|
||||
ChatLine($"[RynthAi] Keep # per day '{ruleLabel}': {have}/{cap} picked up in the last {window} — looting {item.Name}{(stack > 1 ? " x" + stack : "")}.");
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Units for <paramref name="key"/> approved (still fresh) or on their way, other than <paramref name="exceptId"/>.</summary>
|
||||
private int NotLandedYet(string key, int exceptId, long nowMs)
|
||||
{
|
||||
int n = 0;
|
||||
foreach (var kv in _perDayInFlight)
|
||||
if (kv.Key != exceptId && string.Equals(kv.Value.Key, key, StringComparison.OrdinalIgnoreCase) && nowMs < kv.Value.Until)
|
||||
n += kv.Value.Units;
|
||||
foreach (var kv in _pendingPerDay)
|
||||
if (kv.Key != exceptId && !_perDayInFlight.ContainsKey(kv.Key)
|
||||
&& string.Equals(kv.Value.Key, key, StringComparison.OrdinalIgnoreCase) && nowMs - kv.Value.At < PerDayPendingMs)
|
||||
n += kv.Value.Units;
|
||||
return n;
|
||||
}
|
||||
|
||||
/// <summary>The pickup of <paramref name="itemId"/> was sent: an approved Keep # per day item is now on its way.</summary>
|
||||
private void NotePerDaySent(int itemId)
|
||||
{
|
||||
if (!_pendingPerDay.TryGetValue(itemId, out var p)) return;
|
||||
_perDayInFlight[itemId] = (p.Key, p.Units, CorpseNowMs + PerDayInFlightMs);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="itemId"/> left the corpse or the ground into the pack: if a Keep # per day
|
||||
/// rule took it, it counts now (once).
|
||||
/// </summary>
|
||||
private void NotePerDayPickedUp(int itemId)
|
||||
{
|
||||
string key;
|
||||
int units;
|
||||
if (_perDayInFlight.Remove(itemId, out var f)) { key = f.Key; units = f.Units; }
|
||||
else if (_pendingPerDay.TryGetValue(itemId, out var p)) { key = p.Key; units = p.Units; }
|
||||
else return;
|
||||
_pendingPerDay.Remove(itemId);
|
||||
LootPerDayStore store = PerDayStore();
|
||||
store.Record(key, units, PerDayClock());
|
||||
if (store.Problem.Length > 0)
|
||||
Host.Log($"[RynthAi] Keep # per day: the pickup of '{key}' is counted but could not be saved ({store.Problem}).");
|
||||
}
|
||||
|
||||
/// <summary>Drops sends whose landing never came (the late-landing watch is over). Each corpse tick.</summary>
|
||||
private void PrunePerDay()
|
||||
{
|
||||
if (_perDayInFlight.Count == 0 && _pendingPerDay.Count == 0) return;
|
||||
long nowMs = CorpseNowMs;
|
||||
List<int>? gone = null;
|
||||
foreach (var kv in _perDayInFlight)
|
||||
if (nowMs >= kv.Value.Until) (gone ??= new()).Add(kv.Key);
|
||||
if (gone != null) foreach (int id in gone) _perDayInFlight.Remove(id);
|
||||
gone = null;
|
||||
foreach (var kv in _pendingPerDay)
|
||||
if (nowMs - kv.Value.At >= PerDayPendingMs && !_perDayInFlight.ContainsKey(kv.Key)) (gone ??= new()).Add(kv.Key);
|
||||
if (gone != null) foreach (int id in gone) _pendingPerDay.Remove(id);
|
||||
}
|
||||
|
||||
/// <summary>The Loot Editor's line for a Keep # per day rule (LootEditorBridge).</summary>
|
||||
internal string PerDayStatusFor(string key, int hours, int cap) =>
|
||||
PerDayStore().Status(key, hours, cap, PerDayClock());
|
||||
|
||||
/// <summary>
|
||||
/// The Loot Editor's revision part: the store's changes plus the minute, while any pickup is on
|
||||
/// record, so "next frees in" stays current.
|
||||
/// </summary>
|
||||
internal long PerDayRevision()
|
||||
{
|
||||
LootPerDayStore s = PerDayStore();
|
||||
long minute = 0;
|
||||
foreach (var _ in s.Rules()) { minute = (long)(PerDayClock() - DateTime.UnixEpoch).TotalMinutes; break; }
|
||||
return s.Revision * 1_000_000_000L + minute;
|
||||
}
|
||||
|
||||
/// <summary>The Loot Editor's "Reset count": forgets the rule's pickups. The reply for the editor's message line.</summary>
|
||||
internal string PerDayReset(string key)
|
||||
{
|
||||
bool had = PerDayStore().Clear(key);
|
||||
return had ? $"Keep # per day '{key}': pickups forgotten; it counts from 0 again." : $"Keep # per day '{key}': no pickups on record.";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// /ra loot today [clear <rule>|clear all]: each Keep # per day rule of the loot profile in use,
|
||||
/// with what was picked up in its window, and any other rule with pickups on record.
|
||||
/// </summary>
|
||||
private void HandleLootTodayCommand(string[] parts)
|
||||
{
|
||||
LootPerDayStore store = PerDayStore();
|
||||
DateTime now = PerDayClock();
|
||||
if (parts.Length >= 4)
|
||||
{
|
||||
if (!string.Equals(parts[3], "clear", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
ReplyFail($"[RynthAi] loot today: '{parts[3]}'? Usage: /ra loot today [clear <rule name>|clear all]");
|
||||
return;
|
||||
}
|
||||
string what = parts.Length > 4 ? string.Join(" ", parts, 4, parts.Length - 4).Trim() : string.Empty;
|
||||
if (what.Length == 0)
|
||||
{
|
||||
ReplyFail("[RynthAi] loot today clear: which rule? Usage: /ra loot today clear <rule name>|all");
|
||||
return;
|
||||
}
|
||||
bool all = string.Equals(what, "all", StringComparison.OrdinalIgnoreCase);
|
||||
bool had = store.Clear(all ? null : what);
|
||||
if (had) ReplyOk(all ? "[RynthAi] Keep # per day: every rule's pickups forgotten." : $"[RynthAi] Keep # per day '{what}': pickups forgotten; it counts from 0 again.");
|
||||
else ReplyFail(all ? "[RynthAi] Keep # per day: no pickups on record." : $"[RynthAi] Keep # per day: no pickups on record for '{what}'. /ra loot today lists them.");
|
||||
return;
|
||||
}
|
||||
|
||||
var lines = new List<string>();
|
||||
var shown = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach ((string key, int cap, int hours) in PerDayRulesInUse())
|
||||
{
|
||||
if (!shown.Add(key)) continue;
|
||||
lines.Add($"[RynthAi] '{key}': {store.Status(key, hours, cap, now)}");
|
||||
}
|
||||
foreach ((string key, IReadOnlyList<LootPerDayStore.Pick> picks) in store.Rules())
|
||||
{
|
||||
if (shown.Contains(key)) continue;
|
||||
int units = 0;
|
||||
foreach (var p in picks) if (p.AtUtc > now.AddHours(-LootPerDay.DefaultHours)) units += p.Units;
|
||||
lines.Add($"[RynthAi] '{key}' (not a Keep # per day rule of this profile): {units} picked up in the last 24 h");
|
||||
}
|
||||
if (lines.Count == 0)
|
||||
{
|
||||
ReplyOk("[RynthAi] Keep # per day: the loot profile in use has no such rule and no pickups are on record. "
|
||||
+ "Turn it on for a Keep # rule in the Loot Editor (rule view: Per day).");
|
||||
return;
|
||||
}
|
||||
ReplyOk($"[RynthAi] Keep # per day ({lines.Count} rule{(lines.Count == 1 ? "" : "s")}), counted for this character:");
|
||||
foreach (string l in lines) ChatLine(l);
|
||||
if (store.Problem.Length > 0) ChatLine("[RynthAi] (" + store.Problem + ")");
|
||||
}
|
||||
|
||||
/// <summary>The loot profile in use's Keep # per day rules: key, count, window.</summary>
|
||||
private List<(string Key, int Cap, int Hours)> PerDayRulesInUse()
|
||||
{
|
||||
var list = new List<(string, int, int)>();
|
||||
try
|
||||
{
|
||||
string path = (_dashboard?.Settings?.CurrentLootPath ?? string.Empty).Trim().Trim('"');
|
||||
if (path.Length == 0 || !File.Exists(path)) return list;
|
||||
if (TryLoadNativeLootProfile(out LootProfile native, out _))
|
||||
{
|
||||
for (int i = 0; i < native.Rules.Count; i++)
|
||||
{
|
||||
LootRule r = native.Rules[i];
|
||||
int h = LootPerDay.Clamp(r.PerDayHours);
|
||||
if (r.Action == LootAction.KeepUpTo && h > 0) list.Add((LootPerDay.Key(r.Name, i), r.KeepCount, h));
|
||||
}
|
||||
}
|
||||
else if (TryLoadLootProfile(string.Empty, out VTankLootProfile utl, out _))
|
||||
{
|
||||
for (int i = 0; i < utl.Rules.Count; i++)
|
||||
{
|
||||
VTankLootRule r = utl.Rules[i];
|
||||
int h = LootPerDay.Clamp(r.PerDayHours);
|
||||
if (r.Action == VTankLootAction.KeepUpTo && h > 0) list.Add((LootPerDay.Key(r.Name, i), r.KeepCount ?? 0, h));
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
|
@ -50,7 +50,7 @@ public sealed partial class RynthAiPlugin
|
|||
if (low == null) return;
|
||||
|
||||
_lowCompsFired = true;
|
||||
HandleMacroRunCommand("stop", Array.Empty<string>());
|
||||
HandleMacroRunCommand("stop", Array.Empty<string>(), "Low Components Recall");
|
||||
bool recalled = Host.HasInvokeChatParser;
|
||||
if (recalled) Host.InvokeChatParser("/lifestone");
|
||||
string line = $"Low on components ({low}): macro stopped" + (recalled ? ", recalling to the lifestone" : "") +
|
||||
|
|
|
|||
|
|
@ -0,0 +1,46 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - RynthAiPlugin.MacroStopWho.cs
|
||||
// The "Macro stopped" line says who stopped it, and the health at that moment.
|
||||
//
|
||||
// The stop is seen at the next tick (the macro switch went false), so the line used to say only what
|
||||
// the stop did. Who did it (the panel's button, a typed /ra stop, a meta, a Lua script, the HP failsafe,
|
||||
// Stop Macro On Death...) is recorded where the switch is written (LegacyUiSettings.SetMacroRunning,
|
||||
// MacroSource) and said here. With health under a heal line nothing heals while the macro is off: said
|
||||
// too, and flagged when the stop came from a script, a meta, a route or a remote rather than the player.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
public sealed partial class RynthAiPlugin
|
||||
{
|
||||
private string MacroStopWho(LegacyUiSettings settings)
|
||||
{
|
||||
string line = "";
|
||||
int hp = 0, lineValue = 0;
|
||||
try { line = _buffManager?.HealLineNow(out hp, out lineValue) ?? ""; }
|
||||
catch { line = ""; }
|
||||
return DescribeMacroStop(settings.MacroStopSource, hp, line, lineValue);
|
||||
}
|
||||
|
||||
/// <summary>The tail of the "Macro stopped" line (internal for the host tests).</summary>
|
||||
internal static string DescribeMacroStop(string source, int healthPct, string healLine, int lineValue)
|
||||
{
|
||||
string who = string.IsNullOrEmpty(source) ? "a plain write (no source named)" : source;
|
||||
string text = $"Stopped by {who}";
|
||||
if (healLine.Length == 0) return text + ".";
|
||||
text += $"; health {healthPct}% is under {healLine} {lineValue}%: no heal goes while the macro is off";
|
||||
if (!StopIsThePlayers(who)) text += ". FLAG: stopped by a script, meta, route or remote with a heal due";
|
||||
return text + ".";
|
||||
}
|
||||
|
||||
/// <summary>The player's own hands: the panel, the Mini Remote, a typed command, Stop Macro On Death.</summary>
|
||||
internal static bool StopIsThePlayers(string who) =>
|
||||
who.StartsWith("the panel", StringComparison.Ordinal)
|
||||
|| who.StartsWith("the Mini Remote", StringComparison.Ordinal)
|
||||
|| who.Contains("(typed", StringComparison.Ordinal)
|
||||
|| who.StartsWith("Stop Macro On Death", StringComparison.Ordinal)
|
||||
|| who.StartsWith("the character session ending", StringComparison.Ordinal);
|
||||
}
|
||||
|
|
@ -21,16 +21,20 @@ namespace RynthCore.Plugin.RynthAi;
|
|||
public sealed partial class RynthAiPlugin
|
||||
{
|
||||
private readonly OutdoorHunt _hunt = new();
|
||||
private bool _huntFenceHooked;
|
||||
private readonly List<OutdoorHunt.Candidate> _huntCandidates = new();
|
||||
private NavRouteParser? _huntRoute; // the route the hunt installed; another one loaded ends the hunt
|
||||
private NavRecoveryPlanner? _huntDungeonCheck;
|
||||
private int _huntStuckSeq; // NavigationEngine.StuckSpotSeq last looked at
|
||||
private BuildingMap? _huntBuildings;
|
||||
private long _huntPortalsAt;
|
||||
private string _huntNoteLogged = "";
|
||||
private bool _huntOnLoginPending; // Hunt On Login: read at login, run once by TickLoginAutoStart
|
||||
private const int HuntMaxCorners = 128;
|
||||
private const int HuntPathFlags = RynthNavPathApiV1.PathAvoidPortals | RynthNavPathApiV1.PathWallClearance
|
||||
| RynthNavPathApiV1.PathAllowPartial | RynthNavPathApiV1.PathQuiet;
|
||||
// Also the stuck recovery's outdoor detours (NavRecovery.PlanOutdoor) and a script's GoTo: one set of rules for every
|
||||
// walk RynthAi lays on RynthNav's map.
|
||||
internal const int HuntPathFlags = RynthNavPathApiV1.PathAvoidPortals | RynthNavPathApiV1.PathWallClearance
|
||||
| RynthNavPathApiV1.PathAllowPartial | RynthNavPathApiV1.PathQuiet;
|
||||
private const uint HuntItemTypePortal = 0x00010000;
|
||||
private const long HuntPortalRefreshMs = 1000;
|
||||
|
||||
|
|
@ -56,6 +60,9 @@ public sealed partial class RynthAiPlugin
|
|||
case "radius":
|
||||
SetHuntSetting(arg, parts.Length > 3 ? parts[3] : "");
|
||||
break;
|
||||
case "fence":
|
||||
SetHuntFence(parts);
|
||||
break;
|
||||
case "pick":
|
||||
SetHuntPick(parts.Length > 3 ? string.Join(" ", parts, 3, parts.Length - 3) : "");
|
||||
break;
|
||||
|
|
@ -74,7 +81,7 @@ public sealed partial class RynthAiPlugin
|
|||
if (_hunt.Active) StopHunt("stopped", say: true); else StartHunt();
|
||||
break;
|
||||
default:
|
||||
ChatLine("[RynthAi] /ra hunt [start|stop|status|panel] | /ra hunt range <yd> | /ra hunt radius <yd, 0 = anywhere> | " + HuntPickUsage + " | " + HuntLoginUsage + " | " + KeepHuntingUsage);
|
||||
ChatLine("[RynthAi] /ra hunt [start|stop|status|panel] | /ra hunt range <yd> | /ra hunt radius <yd, 0 = anywhere> | /ra hunt fence <x> <y> <radius> | off | " + HuntPickUsage + " | " + HuntLoginUsage + " | " + KeepHuntingUsage);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
|
@ -302,7 +309,7 @@ public sealed partial class RynthAiPlugin
|
|||
s.EnableNavigation = true;
|
||||
if (!s.IsMacroRunning)
|
||||
{
|
||||
s.IsMacroRunning = true;
|
||||
s.SetMacroRunning(true, "the outdoor hunt");
|
||||
_macroWasRunning = true; // no macro-start "nearest waypoint" pick: the hunt plans its own walks
|
||||
}
|
||||
ChatLine((onLogin ? "[RynthAi] Hunt On Login: outdoor hunt on: "
|
||||
|
|
@ -417,6 +424,21 @@ public sealed partial class RynthAiPlugin
|
|||
}
|
||||
if (!TryHuntPosition(out uint cell, out var me)) return;
|
||||
if (InDungeon(cell)) { StopHunt("went into a dungeon", say: true); return; }
|
||||
// Navigation stuck at one spot again and again on the hunt's walk (a snag RynthNav's map doesn't hold):
|
||||
// the hunt leaves that monster and keeps its walks off the spot (OutdoorHunt.Snagged). 2026-11-17 11:14,
|
||||
// the fort Thread 3073: the same walk was planned through a piece of wall every 8 s for 90 s.
|
||||
var navE = _navigationEngine;
|
||||
if (navE != null && navE.StuckSpotSeq != _huntStuckSeq)
|
||||
{
|
||||
_huntStuckSeq = navE.StuckSpotSeq;
|
||||
if (navE.StuckSpotHits >= NavigationEngine.StuckSpotRepeatHits && s.CurrentRoute.Points.Count > 0)
|
||||
{
|
||||
// Where the snag is, on one line with the stuck line's words (cell, local x/y/z, headings, the walk's
|
||||
// target, metres moved): the snags in the logs had x,y only, and the A9B4 replays failed for want of z.
|
||||
Host.Log($"[RynthAi] Hunt: snag x{navE.StuckSpotHits} on the walk to 0x{(uint)_hunt.TargetId:X8} | {navE.LastStuckWhere}");
|
||||
_hunt.Snagged(RynthClock.Now, me);
|
||||
}
|
||||
}
|
||||
// A building's rooms (InDungeon said it isn't a dungeon): off RynthNav's landscape map. The way in
|
||||
// is kept on every tick, a fight's chase included, for the walk back out of a building whose
|
||||
// doors aren't known.
|
||||
|
|
@ -486,6 +508,7 @@ public sealed partial class RynthAiPlugin
|
|||
_hunt.RangeYd = Math.Clamp(s.OutdoorHuntRange, OutdoorHuntRangeMin, OutdoorHuntRangeMax);
|
||||
_hunt.RadiusYd = Math.Clamp(s.OutdoorHuntRadius, 0, OutdoorHuntRadiusMax);
|
||||
_hunt.Pick = (OutdoorHunt.PickMode)Math.Clamp(s.OutdoorHuntPick, 0, 2);
|
||||
if (!_huntFenceHooked) { _hunt.Fence = p => InHuntFence(p.X, p.Y); _hunt.WalkFence = WalkInHuntFence; _huntFenceHooked = true; }
|
||||
_hunt.XpLookup ??= XpPerKill; // the learned XP per kill (MonsterXpTable), for Most XP
|
||||
}
|
||||
|
||||
|
|
@ -522,7 +545,11 @@ public sealed partial class RynthAiPlugin
|
|||
{
|
||||
_huntDungeonCheck ??= new NavRecoveryPlanner(Host, () => _raycast, () => _objectCache?.GetHazardCells());
|
||||
var check = _huntDungeonCheck;
|
||||
_huntBuildings = new BuildingMap(cellDat, () => _raycast?.GeometryLoader?.DungeonLOS, lb => check.IsDungeonLandblock(lb, cellDat));
|
||||
// The cells' furniture too (the stairs left out): walks round tables and chairs, not through them.
|
||||
// The ground's height too: an opening whose foot is a step over it and over the room's floor is a window.
|
||||
_huntBuildings = new BuildingMap(cellDat, () => _raycast?.GeometryLoader?.DungeonLOS, lb => check.IsDungeonLandblock(lb, cellDat),
|
||||
lb => _raycast?.GeometryLoader?.GetDungeonStaticMeshes(lb),
|
||||
(x, y) => _raycast?.GeometryLoader is { } gl ? gl.GetTerrainZWorld((float)x, (float)y) : double.NaN);
|
||||
}
|
||||
return _huntBuildings;
|
||||
}
|
||||
|
|
@ -610,4 +637,27 @@ public sealed partial class RynthAiPlugin
|
|||
corners.Add(new OutdoorHunt.Vec(buf[i * 3], buf[i * 3 + 1], buf[i * 3 + 2]));
|
||||
return new OutdoorHunt.PathResult(status, corners, info[0], info[5]);
|
||||
}
|
||||
|
||||
/// <summary>HuntRaycast's answer when RynthNav (v2 or later) isn't loaded.</summary>
|
||||
internal const int HuntRayUnavailable = -2;
|
||||
|
||||
/// <summary>
|
||||
/// RynthNav's raycast (RynthNav.Path v2): RayClear when walking straight from (ax, ay, az) to (bx, by, bz), world
|
||||
/// units, stays on the navmesh (the agent radius from every wall it knows), RayBlocked when a wall, building, drop
|
||||
/// or the mesh's edge is in the way, ResultNoMesh off the landscape mesh (a building's cells, a dungeon), or
|
||||
/// <see cref="HuntRayUnavailable"/>. The navigation engine's corner gate asks it on hunt walks, planned GoTo
|
||||
/// walks and navmesh detours (NavigationEngine.NavmeshRaycast), as RynthNav's own walker does (PathFollow.Advance).
|
||||
/// </summary>
|
||||
internal int HuntRaycast(double ax, double ay, double az, double bx, double by, double bz)
|
||||
{
|
||||
if (!Host.HasGetPluginInterface) return HuntRayUnavailable;
|
||||
unsafe
|
||||
{
|
||||
// Resolved on every call, as HuntPath.
|
||||
var t = (RynthNavPathApiV1*)Host.GetPluginInterface(RynthNavPathApiV1.PluginName, RynthNavPathApiV1.InterfaceName, 2);
|
||||
if (t == null || t->Version < 2 || t->StructSize < (uint)sizeof(RynthNavPathApiV1) || t->Raycast == null)
|
||||
return HuntRayUnavailable;
|
||||
return t->Raycast(ax, ay, az, bx, by, bz);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
70
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.PetElement.cs
Normal file
70
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.PetElement.cs
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
// Pet element (a players' request, 2026-11-22): /ra petelement [status|any|fire|cold|...].
|
||||
// The main path is the Mini Remote's Pets tab, Combat type, "Pet element". The pick itself is
|
||||
// PetChoice.Order; what each summoning item deals (two elements for a server's holder of two
|
||||
// summons) is PetElements.
|
||||
public sealed partial class RynthAiPlugin
|
||||
{
|
||||
internal const string PetElementUsage =
|
||||
"Usage: /ra petelement [status | any | fire | cold | acid | lightning | nether | slash | pierce | bludgeon]";
|
||||
|
||||
/// <summary>/ra petelement: status (the default) or the element combat pets are summoned for.</summary>
|
||||
private void HandlePetElementCommand(string[] parts)
|
||||
{
|
||||
var settings = _dashboard?.Settings;
|
||||
if (settings == null) { ReplyFail("[RynthAi] Pet element: not ready yet (log in first)."); return; }
|
||||
|
||||
string arg = parts.Length > 2 ? parts[2].Trim() : "status";
|
||||
if (arg.Equals("status", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
ChatLine(PetElementStatusLine(settings));
|
||||
foreach (string line in ListedPetElementLines(settings)) ChatLine(line);
|
||||
return;
|
||||
}
|
||||
|
||||
string elem = arg.Equals("any", StringComparison.OrdinalIgnoreCase) || arg.Equals("auto", StringComparison.OrdinalIgnoreCase)
|
||||
? "" : PetChoice.NormalizeElement(arg.Equals("frost", StringComparison.OrdinalIgnoreCase) ? "Cold" : arg);
|
||||
if (elem.Length == 0 && !arg.Equals("any", StringComparison.OrdinalIgnoreCase) && !arg.Equals("auto", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
ReplyFail($"[RynthAi] Pet element: unknown element '{arg}'. {PetElementUsage}");
|
||||
return;
|
||||
}
|
||||
settings.PetElement = elem;
|
||||
_dashboard?.SaveSettings();
|
||||
ReplyOk(elem.Length == 0
|
||||
? "[RynthAi] Pet element: Any (each monster's own choice: Damage-panel pick, Monsters rule, then its weakness)."
|
||||
: $"[RynthAi] Pet element: {elem}. A {elem} essence is summoned first unless the monster has a pick or a rule of its own.");
|
||||
}
|
||||
|
||||
private static string PetElementStatusLine(LegacyUiSettings settings)
|
||||
{
|
||||
string e = PetChoice.NormalizeElement(settings.PetElement);
|
||||
return e.Length == 0
|
||||
? "[RynthAi] Pet element: Any (each monster's own choice). /ra petelement <element>, or Mini Remote > Pets > Combat."
|
||||
: $"[RynthAi] Pet element: {e}. /ra petelement any to go back, or Mini Remote > Pets > Combat.";
|
||||
}
|
||||
|
||||
/// <summary>One line per listed combat pet item: what it deals ("Fire+Cold" for a holder of two summons).</summary>
|
||||
private List<string> ListedPetElementLines(LegacyUiSettings settings)
|
||||
{
|
||||
var lines = new List<string>();
|
||||
foreach (var rule in settings.ConsumableRules)
|
||||
{
|
||||
if (!rule.Type.Equals("Pet", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
string name = _objectCache?[rule.Id]?.Name ?? rule.Name;
|
||||
var info = PetElements.Describe(Host, unchecked((uint)rule.Id), name);
|
||||
string elems = info.ElementText.Length > 0 ? info.ElementText : "element unknown";
|
||||
string extra = !info.IsHolder ? ""
|
||||
: info.Ready ? $", holds {Math.Max(info.Held.Count, info.Slots)} summons" + (info.Held.Count > 0 ? ": " + string.Join(", ", info.Held) : "")
|
||||
: $", holds {info.Held.Count} of {info.Slots} (can't summon yet)";
|
||||
lines.Add($"[RynthAi] {name}: {elems}{extra}");
|
||||
}
|
||||
if (lines.Count == 0) lines.Add("[RynthAi] No pet essences listed (Mini Remote > Pets: tick them, or /ra items fill).");
|
||||
return lines;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - RynthAiPlugin.RareCorpses.cs
|
||||
// Loot Only Rare Corpses (2026-11-22: "we should know whether it's a rare corpse... vtank does
|
||||
// somehow"). Asked for on Discord for rare farming on Conquest: Rares loot mode opened every corpse,
|
||||
// and kills per hour went down. The setting was kept only so profiles round-trip, read by nothing.
|
||||
//
|
||||
// How a corpse says it holds a rare: ACE (Corpse.TryGenerateRare, the same in DreamWeave's fork)
|
||||
// appends " This corpse generated a rare item!" to the corpse's long description, the text whose
|
||||
// "Killed by <name>." the ownership rules already read once the corpse is identified (the looter
|
||||
// asks for that ID for every corpse in range). It also broadcasts "<killer> has discovered the
|
||||
// <rare>!", but the description is on the corpse, so it holds for a corpse seen after a relog too.
|
||||
//
|
||||
// With the setting on, a corpse is opened only when its description has that sentence. One whose
|
||||
// description hasn't arrived yet waits for it, as Mine Only does. Your own death corpse
|
||||
// (Recover My Corpse) is decided before this, so it is always recovered.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
public sealed partial class RynthAiPlugin
|
||||
{
|
||||
/// <summary>The sentence ACE adds to a corpse that generated a rare (Corpse.TryGenerateRare).</summary>
|
||||
internal const string RareCorpseText = "This corpse generated a rare item";
|
||||
|
||||
/// <summary>The corpse's long description says it generated a rare.</summary>
|
||||
internal static bool IsRareCorpse(string? longDesc)
|
||||
=> !string.IsNullOrEmpty(longDesc) && longDesc.IndexOf(RareCorpseText, StringComparison.OrdinalIgnoreCase) >= 0;
|
||||
|
||||
/// <summary>Why Loot Only Rare Corpses leaves a corpse closed, or null when it is a rare corpse.</summary>
|
||||
internal static string? RareCorpseRefusal(string? longDesc)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(longDesc))
|
||||
return "Loot Only Rare Corpses: waiting for its description (the ID) to see whether it generated a rare.";
|
||||
return IsRareCorpse(longDesc) ? null : "Loot Only Rare Corpses: it didn't generate a rare.";
|
||||
}
|
||||
}
|
||||
|
|
@ -34,7 +34,7 @@ public sealed partial class RynthAiPlugin
|
|||
ArmDeathRecall(s); // before Stop Macro On Death: it reads whether the macro ran
|
||||
if (s.StopMacroOnDeath && s.IsMacroRunning)
|
||||
{
|
||||
HandleMacroRunCommand("stop", Array.Empty<string>());
|
||||
HandleMacroRunCommand("stop", Array.Empty<string>(), "Stop Macro On Death");
|
||||
ChatLine("[RynthAi] You died — macro stopped (Stop Macro On Death is on).");
|
||||
}
|
||||
}
|
||||
|
|
@ -153,7 +153,7 @@ public sealed partial class RynthAiPlugin
|
|||
if (_noComponentFails.Count < NoComponentFailsToStop) return;
|
||||
|
||||
_noComponentFails.Clear();
|
||||
HandleMacroRunCommand("stop", Array.Empty<string>());
|
||||
HandleMacroRunCommand("stop", Array.Empty<string>(), "Stop Macro On No Components");
|
||||
ChatLine("[RynthAi] Out of spell components — macro stopped (Stop Macro On No Components is on).");
|
||||
}
|
||||
|
||||
|
|
@ -179,7 +179,7 @@ public sealed partial class RynthAiPlugin
|
|||
var s = _dashboard?.Settings;
|
||||
if (s != null && s.StopMacroWhenPackFull && s.IsMacroRunning)
|
||||
{
|
||||
HandleMacroRunCommand("stop", Array.Empty<string>());
|
||||
HandleMacroRunCommand("stop", Array.Empty<string>(), "Stop Macro When Pack Full");
|
||||
ChatLine("[RynthAi] Your packs are full — macro stopped (Stop Macro When Pack Full is on).");
|
||||
}
|
||||
else
|
||||
|
|
|
|||
|
|
@ -59,7 +59,8 @@ public sealed partial class RynthAiPlugin
|
|||
{
|
||||
Host.Log($"[RynthAi] Timed command ({TimedCommandSet.ScopeName(scope)}, {why}): {command}");
|
||||
// As a script's line (a nav route's chat waypoint does the same): quiet when it works.
|
||||
Reply.AsScript(() => { HandleRynthChatSubmit(command); return true; });
|
||||
using (_dashboard?.Settings.MacroSource($"the timed command '{command}'"))
|
||||
Reply.AsScript(() => { HandleRynthChatSubmit(command); return true; });
|
||||
}
|
||||
|
||||
private void SaveTimedCommands()
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ namespace RynthCore.Plugin.RynthAi;
|
|||
// /ra targetlock [off] Target lock attack the selected monster (again / off: release)
|
||||
// /ra fightselected [on|off] Fight the monster I select (no argument: toggle)
|
||||
// /ra meleewalls [on|off] Melee through walls (no argument: toggle)
|
||||
// /ra debuffall [on|off] Debuff every monster in range before attacking (no argument: toggle)
|
||||
// /ra meleelow|meleemid|meleehigh melee attack height
|
||||
// /ra navaddpt NavAddPt waypoint at your position (same as /ra addnavpt)
|
||||
// /ra testitem TestItem the selected item against the loot profile
|
||||
|
|
@ -58,6 +59,8 @@ public sealed partial class RynthAiPlugin
|
|||
case "fightselect": HandleFightSelectedCommand(parts); return true;
|
||||
case "meleewalls":
|
||||
case "meleethroughwalls": HandleMeleeWallsCommand(parts); return true;
|
||||
case "debuffall":
|
||||
case "debuffallfirst": HandleDebuffAllCommand(parts); return true;
|
||||
case "meleelow": SetMeleeAttackHeight(0); return true;
|
||||
case "meleemid":
|
||||
case "meleemedium": SetMeleeAttackHeight(1); return true;
|
||||
|
|
@ -234,6 +237,32 @@ public sealed partial class RynthAiPlugin
|
|||
: "[RynthAi] Melee through walls: off (a monster behind a wall is never a melee target for being close).");
|
||||
}
|
||||
|
||||
// ── Debuff every monster in range before attacking ───────────────────────
|
||||
|
||||
private void HandleDebuffAllCommand(string[] parts)
|
||||
{
|
||||
var dash = _dashboard;
|
||||
var s = dash?.Settings;
|
||||
if (s == null) { ReplyFail("[RynthAi] Settings not ready."); return; }
|
||||
string arg = parts.Length >= 3 ? parts[2].ToLowerInvariant() : "";
|
||||
bool? set = arg switch
|
||||
{
|
||||
"" or "toggle" => !s.DebuffAllBeforeAttacking,
|
||||
"on" or "1" or "true" => true,
|
||||
"off" or "0" or "false" => false,
|
||||
_ => null,
|
||||
};
|
||||
if (set is not bool on)
|
||||
{
|
||||
ReplyFail($"[RynthAi] Debuff every monster before attacking: unknown '{arg}'. Usage: /ra debuffall [on|off] (now {(s.DebuffAllBeforeAttacking ? "on" : "off")}).");
|
||||
return;
|
||||
}
|
||||
s.DebuffAllBeforeAttacking = on;
|
||||
dash!.SaveSettings();
|
||||
ReplyOk(on ? "[RynthAi] Debuff every monster before attacking: on (each monster in range gets its Monsters-rule debuffs, nearest first, before any attack)."
|
||||
: "[RynthAi] Debuff every monster before attacking: off (only the target is debuffed before it is attacked).");
|
||||
}
|
||||
|
||||
// ── Melee attack height ──────────────────────────────────────────────────
|
||||
|
||||
private void SetMeleeAttackHeight(int height)
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ public sealed partial class RynthAiPlugin
|
|||
_vtankRefusalPending = true;
|
||||
return;
|
||||
}
|
||||
dash.TogglePanelMacro();
|
||||
dash.TogglePanelMacro("the panel's Run/Stop button");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
|
|||
|
|
@ -521,6 +521,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
_scrollLearner = null;
|
||||
_aetheriaUnboxer?.Reset();
|
||||
_aetheriaUnboxer = null;
|
||||
ResetKitTracking(); // Make kits when low (RynthAiPlugin.Kits.cs)
|
||||
_manaStoneManager = null;
|
||||
_petManager = null;
|
||||
_buffManager?.Dispose();
|
||||
|
|
@ -611,7 +612,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
_navigationEngine = new NavigationEngine(Host, _dashboard.Settings)
|
||||
{
|
||||
// A route's chat waypoint answers as a script's line: quiet when it works (CommandReply.cs).
|
||||
ChatSubmit = line => Reply.AsScript(() => { HandleRynthChatSubmit(line); return true; }),
|
||||
ChatSubmit = line => { using (_dashboard?.Settings.MacroSource($"a route's chat waypoint '{line}'")) Reply.AsScript(() => { HandleRynthChatSubmit(line); return true; }); },
|
||||
// Jump waypoints go through the UB-style jumper (turn, charge, jump, then
|
||||
// it hands navigation back). Forward jump; shift = walking jump.
|
||||
Jump = (heading, shift, ms) => _jumper?.Start(shift ? "ws" : "w", heading, ms),
|
||||
|
|
@ -630,12 +631,16 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
KeepWaypointAfterPause = () => _dunPatrolActive,
|
||||
// Stuck escapes keep out of portals (RynthAiPlugin.PatrolPortals.cs).
|
||||
EscapePortals = EscapePortalsNear,
|
||||
// Hunt walks, GoTo walks and navmesh detours turn a corner early only where RynthNav's mesh
|
||||
// shows a straight walk to the next one (RynthAiPlugin.OutdoorHunt.cs).
|
||||
NavmeshRaycast = HuntRaycast,
|
||||
};
|
||||
// Plans the detours: the dungeon cell graph indoors, RynthNav's navmesh outdoors.
|
||||
// Reads the raycast geometry and hazards through the fields, so it follows their
|
||||
// (re)creation; dropped with the engine at teardown.
|
||||
_navPlanner = new NavRecoveryPlanner(Host, () => _raycast, () => _objectCache?.GetHazardCells());
|
||||
_navigationEngine.SetRecoveryPlanner(_navPlanner);
|
||||
_navigationEngine.EscapeRoom = _navPlanner.EscapeRoom; // in a dungeon, a burst turns to where the map has room
|
||||
if (_objectCache != null) _navigationEngine.SetWorldObjectCache(_objectCache);
|
||||
_navMarkerRenderer = new NavMarkerRenderer(Host, _dashboard.Settings)
|
||||
{
|
||||
|
|
@ -801,6 +806,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
|| (_dashboard?.Settings?.EnableBuffing == true && _buffManager.NeedsAnyBuff()));
|
||||
_combatManager.HoldNewTarget = LootHoldsNewTarget; // Boost Loot Priority: one kill, one loot (the death wait holds no target since 2026-11-15)
|
||||
_combatManager.HoldNewTargetWhy = LootHoldWhy;
|
||||
_combatManager.HoldNewTargetThroughThreat = BoostLootHoldsThroughThreat; // corpses first (RynthAiPlugin.BoostLootFirst.cs)
|
||||
_combatManager.SkipTarget = FenceSkipsTarget; // the hunt fence: monsters outside it are left alone
|
||||
_combatManager.ManaReserveHold = spellId => _buffManager?.OffensiveCastHold(spellId); // the mana reserve
|
||||
_combatManager.ManaCanEverAfford = spellId => _buffManager?.CanEverAfford(spellId) ?? true; // script hook: never-payable spells
|
||||
_combatManager.SetStaleBusyCallback(OnCombatBusyStale);
|
||||
|
|
@ -1083,7 +1090,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
{
|
||||
case "macro":
|
||||
if (on && !dash.Settings.IsMacroRunning && RefuseMacroStartForVTank()) break; // one bot per client
|
||||
if (dash.Settings.IsMacroRunning != on) dash.TogglePanelMacro();
|
||||
if (dash.Settings.IsMacroRunning != on) dash.TogglePanelMacro("a remote command (phone/web remote)");
|
||||
break;
|
||||
case "combat": dash.SetSubsystemEnabled(0, on); break;
|
||||
case "buffing": dash.SetSubsystemEnabled(1, on); break;
|
||||
|
|
@ -1101,7 +1108,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
case "cancelrebuff": dash.RequestCancelForceRebuff(); break;
|
||||
case "clearbusy": HandleClearBusyCommand(); break;
|
||||
case "hideui": _hideUi = on; dash.SetUiHidden(on); break; // applied each tick in OnTick
|
||||
case "sendchat": if (!string.IsNullOrEmpty(value)) RunItemToolUntrusted(() => HandleRynthChatSubmit(value)); break; // a remote line is never the player at the keyboard
|
||||
case "sendchat": if (!string.IsNullOrEmpty(value)) using (dash.Settings.MacroSource($"a remote chat line '{value}'")) RunItemToolUntrusted(() => HandleRynthChatSubmit(value)); break; // a remote line is never the player at the keyboard
|
||||
case "setsetting": ApplyRemoteSetting(value); break; // one advanced setting from the phone (clamped + persisted)
|
||||
case "hub":
|
||||
case "quests":
|
||||
|
|
@ -1575,7 +1582,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
var pauseDash = _dashboard;
|
||||
if (pauseDash != null && !pauseDash.Settings.IsMacroRunning && !RefuseMacroStartForVTank())
|
||||
{
|
||||
pauseDash.TogglePanelMacro();
|
||||
pauseDash.TogglePanelMacro("the /ra pause timer running out");
|
||||
ChatLine("[RynthAi] Pause elapsed — macro RESUMED.");
|
||||
}
|
||||
}
|
||||
|
|
@ -1844,7 +1851,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
if (_buffManager != null) _buffManager.BusyCount = 0;
|
||||
Host.Log($"[RynthAi] Macro stopped: attack cancelled, " +
|
||||
(halt ? "movement stopped" : $"movement left alone (nothing of RynthAi's was moving, action {settings.BotAction})") +
|
||||
$", busy {busyBefore} cleared.");
|
||||
$", busy {busyBefore} cleared. {MacroStopWho(settings)}");
|
||||
}
|
||||
catch (Exception ex) { Host.Log($"[RynthAi] Macro-stop cleanup failed: {ex.Message}"); }
|
||||
}
|
||||
|
|
@ -1852,7 +1859,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
// was heading to when stopped (after a recall that can be far away).
|
||||
// NavResumeNearest off keeps the last waypoint.
|
||||
if (!_macroWasRunning && settings.IsMacroRunning)
|
||||
{
|
||||
Host.Log($"[RynthAi] Macro started by {settings.MacroStartSource}.");
|
||||
_navigationEngine?.ResumeFromNearestWaypoint();
|
||||
}
|
||||
_macroWasRunning = settings.IsMacroRunning;
|
||||
_killClock.ObserveMacro(settings.IsMacroRunning); // a start counts even if nothing reads the clock meanwhile
|
||||
|
||||
|
|
@ -1894,7 +1904,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
&& (_buffManager.PendingSpellId != 0
|
||||
|| _buffManager.WantsVitalRecharge
|
||||
|| (settings.EnableBuffing && _buffManager.NeedsAnyBuff()
|
||||
&& !_buffManager.BuffsWaitForHealth())); // hurt in a fight: combat, not buffs
|
||||
&& !_buffManager.BuffsWaitForFight())); // in a fight: combat first, buffs after (2026-11-20)
|
||||
bool wantBuff = wantBuffRaw;
|
||||
|
||||
// ── Buffing-coma watchdog (STEP 5: decides, no longer falls through) ──
|
||||
|
|
@ -1967,6 +1977,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
|
||||
bool wantLoot = HasLootWork(settings, nowMs);
|
||||
_lastWantLoot = wantLoot;
|
||||
// Boost Loot Priority, corpses first (RynthAiPlugin.BoostLootFirst.cs): a close or fought
|
||||
// monster doesn't take the tick from loot work while health is at or above Heal At.
|
||||
if (engaged && wantLoot && BoostLootFirst(settings)) engaged = false;
|
||||
bool wantSalvage = _salvageManager != null && _salvageManager.IsBusy;
|
||||
bool followActive = IsFollowActive(settings);
|
||||
bool wantNav = NavWantsTick(settings);
|
||||
|
|
@ -2012,6 +2025,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
}
|
||||
}
|
||||
|
||||
// ── Make kits when low: a run stops at once on danger ─────────────
|
||||
// After the decision, ahead of every hold below (buffing above all), so a monster, a
|
||||
// heal or a fight ends a kit run on this tick (RynthAiPlugin.Kits.cs).
|
||||
Guard(TickStep.AutoKits, () => CheckAutoKitsDanger(settings));
|
||||
|
||||
// ── Travel back to your corpse (TravelToOwnCorpse) ─────────────────
|
||||
// After the decision, ahead of every early return below: RynthNav walks only
|
||||
// while the arbiter says Idle, and is stopped the moment RynthAi wants the tick.
|
||||
|
|
@ -2096,6 +2114,20 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
// hundreds of pending CreateObjects (RL hot-reload, fresh login),
|
||||
// the concurrent native walk has been causing intermittent crashes.
|
||||
bool inventorySettled = (RynthClock.Now - _loginCompletedAt).TotalMilliseconds > 3000;
|
||||
|
||||
// Make kits when low (RynthAiPlugin.Kits.cs): while a kit run gets ready (peace mode,
|
||||
// standing still) or goes, everything below waits, as it does for buffs: the item
|
||||
// chores, crafting, combat, looting and navigation. A fault holds nothing.
|
||||
if (inventorySettled && settings.IsMacroRunning
|
||||
&& GuardHold(TickStep.AutoKits, () => TickAutoKits(settings)))
|
||||
{
|
||||
StopNavFor(BotActivity.Idle);
|
||||
KeepThreatScanFresh(settings);
|
||||
FreezeCorpseTimeout(CorpseNowMs); // a claimed corpse must not time out while held
|
||||
ThinkMeta();
|
||||
return;
|
||||
}
|
||||
|
||||
if (inventorySettled)
|
||||
TickCramStack(settings);
|
||||
|
||||
|
|
@ -4176,6 +4208,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
case "find": HandleFindCommand(parts); break; // RynthAiPlugin.FeatureSearch.cs
|
||||
case "aetheria": HandleAetheriaCommand(parts); break; // RynthAiPlugin.Aetheria.cs
|
||||
case "autoconfirm": HandleAutoConfirmCommand(parts); break; // RynthAiPlugin.AutoConfirm.cs
|
||||
case "kits": HandleKitsCommand(parts); break; // RynthAiPlugin.Kits.cs
|
||||
case "petelement": HandlePetElementCommand(parts); break; // RynthAiPlugin.PetElement.cs
|
||||
case "why": HandleWhyCommand(); break;
|
||||
case "ghost":
|
||||
case "ghosts": HandleGhostsCommand(cmd, parts); break;
|
||||
|
|
|
|||
|
|
@ -217,31 +217,127 @@ public sealed partial class RynthAiPlugin
|
|||
{
|
||||
if (_dashboard == null || _dashboard.Settings.IsMacroRunning == on) return;
|
||||
if (on && RefuseMacroStartForVTank()) return; // one bot per client (Decal bridge)
|
||||
if (on) _dashboard.TogglePanelMacro();
|
||||
else HandleMacroRunCommand("stop", Array.Empty<string>());
|
||||
if (on) _dashboard.TogglePanelMacro("a Lua script (ai.MacroRunning = true)");
|
||||
else HandleMacroRunCommand("stop", Array.Empty<string>(), "a Lua script (ai.MacroRunning = false)");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A script's ai.GoTo(ns, ew): a Once route to the point, the macro on. A script roaming a Thread in 80 m legs
|
||||
/// and edges back 40 m with it, and a one-point straight route walked into every tree, rock and wall on the way
|
||||
/// (2026-11-18). So the walk is planned as /ra navheading and /ra dunnav-to plan theirs: outdoors along RynthNav's
|
||||
/// path with the Outdoor Hunt's flags, in a dungeon by the dungeon map; when neither answers, the straight route
|
||||
/// as before. What the script sees is the same: true, a Once route ending on the point asked for (ranav[] name ""
|
||||
/// and finished at its end), and the character walking there.
|
||||
/// </summary>
|
||||
internal bool ScriptGoTo(double ns, double ew)
|
||||
{
|
||||
var dash = _dashboard;
|
||||
if (dash == null) return false;
|
||||
var st = dash.Settings;
|
||||
if (!st.IsMacroRunning && RefuseMacroStartForVTank()) return false; // one bot per client (Decal bridge)
|
||||
float z = 0;
|
||||
if (Host.HasGetPlayerPose) Host.TryGetPlayerPose(out _, out _, out _, out z, out _, out _, out _, out _);
|
||||
var route = new NavRouteParser { RouteType = NavRouteType.Once };
|
||||
route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = ns, EW = ew, Z = z / 240.0 });
|
||||
uint cell = 0;
|
||||
float lx = 0, ly = 0, z = 0;
|
||||
bool pose = Host.HasGetPlayerPose && Host.TryGetPlayerPose(out cell, out lx, out ly, out z, out _, out _, out _, out _);
|
||||
NavRouteParser? route = null;
|
||||
string how = "straight (no position)";
|
||||
if (pose)
|
||||
{
|
||||
// Never worse than before: anything going wrong in planning leaves the straight route.
|
||||
try { route = PlanGoTo(cell, lx, ly, z, ns, ew, out how); }
|
||||
catch (Exception ex) { route = null; how = "straight (planning failed: " + ex.Message + ")"; }
|
||||
}
|
||||
if (route == null || route.Points.Count == 0)
|
||||
{
|
||||
route = new NavRouteParser { RouteType = NavRouteType.Once };
|
||||
route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = ns, EW = ew, Z = z / 240.0 });
|
||||
}
|
||||
Host.Log(string.Create(CultureInfo.InvariantCulture, $"[RynthAi] GoTo: NS {ns:0.0000} EW {ew:0.0000}, {how}"));
|
||||
st.CurrentRoute = route;
|
||||
st.CurrentNavPath = string.Empty;
|
||||
st.ActiveNavIndex = 0;
|
||||
st.EnableNavigation = true;
|
||||
if (!st.IsMacroRunning) dash.TogglePanelMacro();
|
||||
if (!st.IsMacroRunning) dash.TogglePanelMacro("a Lua script (GoTo)");
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The planned walk for <see cref="ScriptGoTo"/>, or null (with <paramref name="how"/> saying why) for the
|
||||
/// straight route. The route always ends on (ns, ew).</summary>
|
||||
private NavRouteParser? PlanGoTo(uint cell, float lx, float ly, float z, double ns, double ew, out string how)
|
||||
{
|
||||
if ((cell & 0xFFFF) >= 0x0100)
|
||||
{
|
||||
if (!InDungeon(cell)) { how = "straight (in a building's rooms: no map plans from here)"; return null; }
|
||||
return PlanGoToDungeon(cell, lx, ly, z, ns, ew, out how);
|
||||
}
|
||||
|
||||
var at = new OutdoorHunt.Vec(((cell >> 24) & 0xFF) * 192.0 + lx, ((cell >> 16) & 0xFF) * 192.0 + ly, z);
|
||||
var goal = new OutdoorHunt.Vec(DungeonGeometry.NavToWorld(ew), DungeonGeometry.NavToWorld(ns), z);
|
||||
var path = HuntPath(at, goal);
|
||||
if ((path.Status != OutdoorHunt.PathStatus.Ok && path.Status != OutdoorHunt.PathStatus.Partial) || path.Corners.Count == 0)
|
||||
{
|
||||
how = path.Status switch
|
||||
{
|
||||
OutdoorHunt.PathStatus.NoMesh => "straight (no RynthNav map here)",
|
||||
OutdoorHunt.PathStatus.Unavailable => "straight (RynthNav isn't loaded)",
|
||||
_ => "straight (RynthNav found no way)",
|
||||
};
|
||||
return null;
|
||||
}
|
||||
var route = HeadingRoute(path.Corners);
|
||||
route.NavmeshCorners = true; // RynthNav's corners: turned early only where its mesh shows the next one (the corner gate)
|
||||
// The walk ends on the point asked for, as the straight route did: the last corner is moved onto it (RynthNav
|
||||
// put it on the mesh, its height kept), or, a way that ends short (partial, the point off the mesh), the
|
||||
// point follows it.
|
||||
var last = route.Points[^1];
|
||||
double shortYd = Math.Sqrt(Sq(DungeonGeometry.NavToWorld(last.EW) - goal.X) + Sq(DungeonGeometry.NavToWorld(last.NS) - goal.Y));
|
||||
if (shortYd <= GoToEndSnapYd) { last.NS = ns; last.EW = ew; }
|
||||
else route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = ns, EW = ew, Z = last.Z != 0 ? last.Z : z / 240.0 });
|
||||
var inv = CultureInfo.InvariantCulture;
|
||||
how = path.Status == OutdoorHunt.PathStatus.Ok
|
||||
? string.Create(inv, $"round obstacles on RynthNav's map, {route.Points.Count} point(s), {path.Length:0} yd")
|
||||
: string.Create(inv, $"round obstacles on RynthNav's map as far as it goes ({shortYd:0} yd short), then straight, {route.Points.Count} point(s)");
|
||||
return route;
|
||||
}
|
||||
|
||||
// RynthNav's last corner this close to the point asked for is the point (it snapped it onto the mesh).
|
||||
private const double GoToEndSnapYd = 1.0;
|
||||
// A dungeon point this far from every room's centre isn't in this dungeon (NavRecovery's DungeonCellReachYd).
|
||||
private const double GoToDungeonReachYd = 30.0;
|
||||
|
||||
private static double Sq(double v) => v * v;
|
||||
|
||||
/// <summary>A GoTo in a dungeon: the dungeon map's walk from the character's cell to the point's, as /ra dunnav-to.</summary>
|
||||
private NavRouteParser? PlanGoToDungeon(uint cell, float lx, float ly, float z, double ns, double ew, out string how)
|
||||
{
|
||||
uint lb = cell >> 16;
|
||||
var map = DungeonMapOverride?.Invoke(lb);
|
||||
var cellDat = _raycast?.GeometryLoader.CellDat;
|
||||
if (map == null && (cellDat == null || !cellDat.IsLoaded)) { how = "straight (the dungeon map isn't loaded yet)"; return null; }
|
||||
var graph = map?.Graph ?? DungeonPathfinder.GetGraph(lb, cellDat!);
|
||||
if (graph.Count == 0) { how = "straight (no dungeon map here)"; return null; }
|
||||
var geo = map != null ? map.Value.Geo : DungeonPathfinder.GetGeometry(lb, cellDat!, _raycast?.GeometryLoader?.DungeonLOS);
|
||||
double lbX = ((cell >> 24) & 0xFF) * 192.0, lbY = ((cell >> 16) & 0xFF) * 192.0;
|
||||
double pNs = DungeonGeometry.WorldToNav(lbY + ly), pEw = DungeonGeometry.WorldToNav(lbX + lx);
|
||||
uint start = graph.ContainsKey(cell) ? cell : DungeonPathfinder.NearestCell(graph, pNs, pEw, z);
|
||||
// The point's room: the cell whose floor holds it at the character's height (a script gives no z), else the nearest.
|
||||
uint goal = DungeonPathfinder.CellAt(graph, geo, new NavPoint { Type = NavPointType.Point, NS = ns, EW = ew, Z = z / 240.0 });
|
||||
if (start == 0 || goal == 0 || !graph.TryGetValue(goal, out var goalNode)) { how = "straight (not on the dungeon map)"; return null; }
|
||||
if (Math.Sqrt(Sq(goalNode.NS - ns) + Sq(goalNode.EW - ew)) * 240.0 > GoToDungeonReachYd)
|
||||
{
|
||||
how = "straight (the point isn't near any room of this dungeon)";
|
||||
return null;
|
||||
}
|
||||
var hazards = _objectCache?.GetHazardCells();
|
||||
var path = DungeonPathfinder.FindPath(start, goal, graph, hazards);
|
||||
if (path.Count == 0) { how = $"straight (no walk from {start:X8} to {goal:X8} on the dungeon map)"; return null; }
|
||||
var route = DungeonPathfinder.BuildNavRoute(path, graph, ns, ew, geo, hazards, pNs, pEw, z, z);
|
||||
how = $"by the dungeon map, {path.Count} cell(s), {route.Points.Count} point(s)";
|
||||
return route;
|
||||
}
|
||||
|
||||
internal void ScriptStop()
|
||||
{
|
||||
if (_dashboard?.Settings.IsMacroRunning == true) HandleMacroRunCommand("stop", Array.Empty<string>());
|
||||
if (_dashboard?.Settings.IsMacroRunning == true) HandleMacroRunCommand("stop", Array.Empty<string>(), "a Lua script (Stop)");
|
||||
else _navigationEngine?.Stop();
|
||||
}
|
||||
|
||||
|
|
@ -275,5 +371,8 @@ public sealed partial class RynthAiPlugin
|
|||
/// (quiet when it works, errors in chat; CommandReply.cs), and the Item Tool refuses it (a script's
|
||||
/// line is never the player at the keyboard).</summary>
|
||||
internal void ScriptSubmitCommand(string text)
|
||||
=> Reply.AsScript(() => { RunItemToolUntrusted(() => HandleRynthChatSubmit(text)); return true; });
|
||||
{
|
||||
using (_dashboard?.Settings.MacroSource($"a Lua script's command '{text}'"))
|
||||
Reply.AsScript(() => { RunItemToolUntrusted(() => HandleRynthChatSubmit(text)); return true; });
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -65,7 +65,7 @@ internal sealed class VTankYield
|
|||
Verdict v = Tick(settings.IsMacroRunning, macroWasRunning, settings.YieldToVTank);
|
||||
if (v == Verdict.None)
|
||||
return v;
|
||||
settings.IsMacroRunning = false;
|
||||
settings.SetMacroRunning(false, "VTank yield (VTank's macro runs: one bot per client)");
|
||||
onStop?.Invoke();
|
||||
if (v == Verdict.StopForVTankStart) chat(StoppedForStartLine);
|
||||
else if (v == Verdict.StopWhileVTankRuns) chat(StoppedWhileRunningLine);
|
||||
|
|
|
|||
|
|
@ -13,6 +13,9 @@ namespace RynthCore.Plugin.RynthChat;
|
|||
/// a fixed 500 before. Changing it keeps the newest lines and never touches the
|
||||
/// numbering: the engine (and its Discord relay) tell new lines from old by seq.
|
||||
///
|
||||
/// Player chat (0.4.0) is kept longer, in a second ring (see DefaultPlayerCapacity): a read
|
||||
/// that starts before the main ring's oldest line gets those player lines first, in seq order.
|
||||
///
|
||||
/// JSON per line: {"seq":N,"ts":"HH:mm:ss","chan":"Chat","type":3,"sender":"Bob"|null,"text":"..."}.
|
||||
/// "type" (AC's ChatMessageType) was added in 0.2.0; engines before it ignore it.
|
||||
/// Every non-ASCII character is written as a \uXXXX escape, so the export is
|
||||
|
|
@ -26,15 +29,62 @@ internal sealed class ChatBuffer
|
|||
internal const int MinCapacity = 100;
|
||||
internal const int MaxCapacity = 10000;
|
||||
|
||||
// Player chat (0.4.0, ChatClassifier.IsPlayerChat) is also kept in a ring of its own, so it
|
||||
// outlasts the main ring: the engine's "Player chat history" (RynthChatSetPlayerCapacity). A
|
||||
// busy hunt fills the main ring with combat lines in minutes; after an engine reload, or with
|
||||
// the chat window closed for a while, the engine reads the scrollback from here, and the tells
|
||||
// and fellowship lines are still in it. 0 turns the second ring off.
|
||||
internal const int DefaultPlayerCapacity = 5000;
|
||||
internal const int MaxPlayerCapacity = 20000;
|
||||
|
||||
private ChatLine?[] _ring;
|
||||
private readonly object _lock = new();
|
||||
private int _head; // next write index (mod _ring.Length)
|
||||
private int _count; // lines stored (<= _ring.Length)
|
||||
private ulong _nextSeq = 1;
|
||||
private ChatLine?[] _players;
|
||||
private int _pHead, _pCount;
|
||||
|
||||
internal ChatBuffer(int capacity = DefaultCapacity)
|
||||
internal ChatBuffer(int capacity = DefaultCapacity, int playerCapacity = DefaultPlayerCapacity)
|
||||
{
|
||||
_ring = new ChatLine?[Math.Clamp(capacity, MinCapacity, MaxCapacity)];
|
||||
_players = new ChatLine?[Math.Clamp(playerCapacity, 0, MaxPlayerCapacity)];
|
||||
}
|
||||
|
||||
internal int PlayerCapacity
|
||||
{
|
||||
get { lock (_lock) return _players.Length; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Keeps up to <paramref name="capacity"/> player lines (0..MaxPlayerCapacity) in their own
|
||||
/// ring from now on; when it shrinks, the oldest go. Returns the capacity applied, or -1 for 0
|
||||
/// (off), so the engine can tell "applied" from "not up yet". Any thread.
|
||||
/// </summary>
|
||||
internal int SetPlayerCapacity(int capacity)
|
||||
{
|
||||
capacity = Math.Clamp(capacity, 0, MaxPlayerCapacity);
|
||||
lock (_lock)
|
||||
{
|
||||
if (capacity != _players.Length)
|
||||
{
|
||||
(_players, _pHead, _pCount) = Resize(_players, _pHead, _pCount, capacity);
|
||||
}
|
||||
return capacity == 0 ? -1 : capacity;
|
||||
}
|
||||
}
|
||||
|
||||
private static (ChatLine?[] Ring, int Head, int Count) Resize(ChatLine?[] old, int head, int count, int capacity)
|
||||
{
|
||||
int keep = Math.Min(count, capacity);
|
||||
var ring = new ChatLine?[capacity];
|
||||
int oldCap = old.Length;
|
||||
if (oldCap > 0)
|
||||
{
|
||||
int start = (head - keep + oldCap) % oldCap; // the oldest line kept
|
||||
for (int i = 0; i < keep; i++) ring[i] = old[(start + i) % oldCap];
|
||||
}
|
||||
return (ring, capacity == 0 ? 0 : keep % capacity, keep);
|
||||
}
|
||||
|
||||
internal int Capacity
|
||||
|
|
@ -58,14 +108,7 @@ internal sealed class ChatBuffer
|
|||
lock (_lock)
|
||||
{
|
||||
if (capacity == _ring.Length) return capacity;
|
||||
int keep = Math.Min(_count, capacity);
|
||||
var ring = new ChatLine?[capacity];
|
||||
int oldCap = _ring.Length;
|
||||
int start = (_head - keep + oldCap) % oldCap; // the oldest line kept
|
||||
for (int i = 0; i < keep; i++) ring[i] = _ring[(start + i) % oldCap];
|
||||
_ring = ring;
|
||||
_count = keep;
|
||||
_head = keep % capacity;
|
||||
(_ring, _head, _count) = Resize(_ring, _head, _count, capacity);
|
||||
return capacity;
|
||||
}
|
||||
}
|
||||
|
|
@ -78,12 +121,13 @@ internal sealed class ChatBuffer
|
|||
: ChatClassifier.ChannelFor(text, chatType);
|
||||
string? sender = ChatClassifier.SenderFor(text, chatType);
|
||||
string ts = DateTime.Now.ToString("HH:mm:ss");
|
||||
bool player = ChatClassifier.IsPlayerChat(channel, chatType, text);
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
// Numbered under the lock, so the ring is always in seq order (the
|
||||
// engine skips anything at or below the last seq it has seen).
|
||||
_ring[_head] = new ChatLine
|
||||
var line = new ChatLine
|
||||
{
|
||||
Seq = _nextSeq++,
|
||||
Timestamp = ts,
|
||||
|
|
@ -92,8 +136,15 @@ internal sealed class ChatBuffer
|
|||
Sender = sender,
|
||||
Text = text,
|
||||
};
|
||||
_ring[_head] = line;
|
||||
_head = (_head + 1) % _ring.Length;
|
||||
if (_count < _ring.Length) _count++;
|
||||
if (player && _players.Length > 0)
|
||||
{
|
||||
_players[_pHead] = line; // the same object: no extra copy of the text
|
||||
_pHead = (_pHead + 1) % _players.Length;
|
||||
if (_pCount < _players.Length) _pCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -111,10 +162,31 @@ internal sealed class ChatBuffer
|
|||
ulong newest = _nextSeq - 1;
|
||||
int n = sinceSeq >= newest ? 0 : (int)Math.Min((ulong)_count, newest - sinceSeq);
|
||||
if (n == 0) return "[]";
|
||||
lines = new ChatLine?[n];
|
||||
// Player lines older than the main ring (0.4.0), first: only when the reader is behind
|
||||
// the main ring's oldest line (its first read after a bind or reload, or a long gap).
|
||||
// An ordinary poll (a few new lines) skips this, so it still copies only those.
|
||||
ulong oldestMain = newest - (ulong)_count + 1;
|
||||
int older = 0;
|
||||
int pCap = _players.Length;
|
||||
int pStart = pCap == 0 ? 0 : (_pHead - _pCount + pCap) % pCap;
|
||||
if (_pCount > 0 && sinceSeq + 1 < oldestMain)
|
||||
for (int i = 0; i < _pCount; i++)
|
||||
{
|
||||
ChatLine? p = _players[(pStart + i) % pCap];
|
||||
if (p == null || p.Seq >= oldestMain) break;
|
||||
if (p.Seq > sinceSeq) older++;
|
||||
}
|
||||
lines = new ChatLine?[older + n];
|
||||
int w = 0;
|
||||
if (older > 0)
|
||||
for (int i = 0; i < _pCount && w < older; i++)
|
||||
{
|
||||
ChatLine? p = _players[(pStart + i) % pCap];
|
||||
if (p != null && p.Seq > sinceSeq && p.Seq < oldestMain) lines[w++] = p;
|
||||
}
|
||||
int cap = _ring.Length;
|
||||
int start = (_head - n + cap) % cap;
|
||||
for (int i = 0; i < n; i++) lines[i] = _ring[(start + i) % cap];
|
||||
for (int i = 0; i < n; i++) lines[w + i] = _ring[(start + i) % cap];
|
||||
}
|
||||
|
||||
var sb = new StringBuilder(64 + lines.Length * 192);
|
||||
|
|
|
|||
|
|
@ -74,6 +74,47 @@ internal static class ChatClassifier
|
|||
|| text.StartsWith("[Admin]", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
// ── Player chat (0.4.0) ────────────────────────────────────────────────
|
||||
// The engine's ChatPlayerText (RynthCore, UI/Data/ChatPlayerText.cs) has the same rule; keep
|
||||
// the two the same. ChatBuffer keeps these lines in a ring of their own, so a reload or a
|
||||
// closed chat window doesn't lose tells and fellowship lines to combat spam.
|
||||
|
||||
/// <summary>
|
||||
/// True for a line a player typed: say, tells both ways, emotes, allegiance, fellowship, every
|
||||
/// channel line, an admin's tell, and a room line of any other type ("[Room] Name says, \"").
|
||||
/// Never plugin output, item info, combat or spell words.
|
||||
/// </summary>
|
||||
internal static bool IsPlayerChat(string channel, int chatType, string? text)
|
||||
{
|
||||
if (channel is Rynth or Items) return false;
|
||||
if (channel is Chat or Channels) return true;
|
||||
if (chatType == 0x1F) return true; // AdminTell
|
||||
if (channel == Combat) return false;
|
||||
return LooksLikeSpeech(text);
|
||||
}
|
||||
|
||||
/// <summary>"[Tag] Name says, \"" / "[Tag] Name tells you, \"" (AC's name links allowed), or "You say ..., \"".</summary>
|
||||
internal static bool LooksLikeSpeech(string? text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text) || text.Length < 8) return false;
|
||||
int start = 0;
|
||||
bool tagged = false;
|
||||
if (text[0] == '[')
|
||||
{
|
||||
int close = text.IndexOf(']', 1);
|
||||
if (close < 2 || close > 41 || close + 1 >= text.Length || text[close + 1] != ' ') return false;
|
||||
if (text.IndexOf('[', 1, close - 1) >= 0) return false;
|
||||
start = close + 2;
|
||||
tagged = true;
|
||||
}
|
||||
int quote = text.IndexOf(", \"", start, StringComparison.Ordinal);
|
||||
if (quote < 0 || quote - start > 220) return false;
|
||||
string who = text.Substring(start, quote - start);
|
||||
if (who.IndexOf('"') >= 0) return false;
|
||||
if (who.StartsWith("You say", StringComparison.Ordinal) || who.StartsWith("You tell ", StringComparison.Ordinal)) return true;
|
||||
return tagged && (who.Contains(" says", StringComparison.Ordinal) || who.Contains(" tells you", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
internal static uint ColorFor(string channel) => channel switch
|
||||
{
|
||||
Chat => 0xFFE0E0E0,
|
||||
|
|
|
|||
|
|
@ -88,6 +88,19 @@ public static unsafe class PluginExports
|
|||
catch { return 0; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// How many player lines (tells, say, fellowship, allegiance, channels) the scrollback keeps in
|
||||
/// a ring of their own, past the main one (the engine's "Player chat history"; 0.4.0). Returns
|
||||
/// the number applied (clamped to 0..20000; -1 for 0, off), or 0 before the plugin is up.
|
||||
/// Engines before it never call this, and the plugin keeps ChatBuffer.DefaultPlayerCapacity.
|
||||
/// </summary>
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthChatSetPlayerCapacity", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static int SetPlayerCapacity(int lines)
|
||||
{
|
||||
try { return Runtime.Plugin?.SetPlayerScrollbackCapacity(lines) ?? 0; }
|
||||
catch { return 0; }
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthChatSendLine", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void SendLine(IntPtr ansiText)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ namespace RynthCore.Plugin.RynthChat;
|
|||
public sealed class RynthChatPlugin : RynthPluginBase
|
||||
{
|
||||
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthChat");
|
||||
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.3.0");
|
||||
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.4.0");
|
||||
|
||||
private readonly ChatBuffer _buffer = new();
|
||||
|
||||
|
|
@ -44,6 +44,8 @@ public sealed class RynthChatPlugin : RynthPluginBase
|
|||
|
||||
internal int SetScrollbackCapacity(int lines) => _buffer.SetCapacity(lines);
|
||||
|
||||
internal int SetPlayerScrollbackCapacity(int lines) => _buffer.SetPlayerCapacity(lines);
|
||||
|
||||
// Called on the game thread from the engine's deferred chat dispatch
|
||||
// (Win32Backend posts WM_RYNTHCORE_CHAT so this runs on a fresh, non-reentrant
|
||||
// message dispatch rather than inline inside the Enter keystroke handler).
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue