Repository navigation
Expand file tree
/
Copy pathNavGraph.cs
More file actions
849 lines (754 loc) · 29.5 KB
/
Copy pathNavGraph.cs
File metadata and controls
849 lines (754 loc) · 29.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using UnityEngine;
namespace Killer_Frequency_Access;
/// <summary>
/// The scene's NavMesh polygons and their neighbour links, generated from the rip's NavMesh assets by
/// tools\rip\gen_navmesh.py (the game strips NavMeshPath and NavMesh.CalculateTriangulation, so the
/// mod cannot read them at runtime). Routes are an A* over polygons, straightened with the funnel
/// (string pulling) through the shared edges.
///
/// Why: the 0.5 m lattice search over NavMesh.SamplePosition failed between floors. The stairs are
/// ~40 degree runs of 0.3 m sloped strips, so each lattice step rises ~0.42 m, at the edge of the 0.5 m
/// sample radius (2026-11-22 run: "no NavMesh route" after the whole floor was searched, 3,800 nodes).
/// The rip's NavMesh_0 connects basement, ground, the 1.0 m level and the first floor in one region.
/// Auto-walk uses only this graph: routes, snapping points onto the walkable area, the floors under a
/// standing spot. The graph for a scene is picked by scene name (the game will not be updated).
/// </summary>
internal sealed class NavGraph
{
private const float GridCell = 2f;
public readonly string Name;
private readonly Vector3[][] _polys;
private readonly (int Other, Vector3 A, Vector3 B)[][] _links;
private readonly Dictionary<(int, int), List<int>> _grid = new();
/// <summary>Connected region of each polygon (polygons reachable from each other share one).</summary>
private readonly int[] _region;
private readonly List<int> _regionSize = new();
private NavGraph(string name, Vector3[][] polys, (int, Vector3, Vector3)[][] links)
{
Name = name;
_polys = polys;
_links = links;
_region = new int[polys.Length];
Array.Fill(_region, -1);
var stack = new Stack<int>();
for (var seed = 0; seed < polys.Length; seed++)
{
if (_region[seed] >= 0)
{
continue;
}
var id = _regionSize.Count;
var size = 0;
_region[seed] = id;
stack.Push(seed);
while (stack.Count > 0)
{
var poly = stack.Pop();
size++;
foreach (var (other, _, _) in links[poly])
{
if (_region[other] < 0)
{
_region[other] = id;
stack.Push(other);
}
}
}
_regionSize.Add(size);
}
for (var i = 0; i < polys.Length; i++)
{
float minX = float.MaxValue, maxX = float.MinValue, minZ = float.MaxValue, maxZ = float.MinValue;
foreach (var v in polys[i])
{
minX = Math.Min(minX, v.x); maxX = Math.Max(maxX, v.x);
minZ = Math.Min(minZ, v.z); maxZ = Math.Max(maxZ, v.z);
}
for (var gx = Cell(minX); gx <= Cell(maxX); gx++)
{
for (var gz = Cell(minZ); gz <= Cell(maxZ); gz++)
{
if (!_grid.TryGetValue((gx, gz), out var list))
{
_grid[(gx, gz)] = list = new List<int>();
}
list.Add(i);
}
}
}
}
public int PolygonCount => _polys.Length;
private static int Cell(float v) => Mathf.FloorToInt(v / GridCell);
public static List<NavGraph> LoadAll()
{
var result = new List<NavGraph>();
var assembly = typeof(NavGraph).Assembly;
foreach (var resource in assembly.GetManifestResourceNames())
{
if (!resource.StartsWith("Nav.", StringComparison.Ordinal) || !resource.EndsWith(".navbin.gz", StringComparison.Ordinal))
{
continue;
}
using var stream = assembly.GetManifestResourceStream(resource)!;
using var gzip = new GZipStream(stream, CompressionMode.Decompress);
using var reader = new BinaryReader(gzip);
if (new string(reader.ReadChars(4)) != "KFNV" || reader.ReadInt32() != 1)
{
MelonLoader.MelonLogger.Warning($"[nav] {resource}: unknown format");
continue;
}
var count = reader.ReadInt32();
var polys = new Vector3[count][];
var links = new (int, Vector3, Vector3)[count][];
for (var i = 0; i < count; i++)
{
var vc = reader.ReadByte();
polys[i] = new Vector3[vc];
for (var k = 0; k < vc; k++)
{
polys[i][k] = ReadVector(reader);
}
var lc = reader.ReadUInt16();
links[i] = new (int, Vector3, Vector3)[lc];
for (var k = 0; k < lc; k++)
{
links[i][k] = (reader.ReadInt32(), ReadVector(reader), ReadVector(reader));
}
}
var name = resource["Nav.".Length..^".navbin.gz".Length];
result.Add(new NavGraph(name, polys, links));
}
return result;
}
private static Vector3 ReadVector(BinaryReader reader) => new(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle());
/// <summary>
/// The closest point of the walking graph to <paramref name="point"/>, within <paramref name="maxDistance"/>:
/// straight above or below it when a polygon covers its x/z, otherwise the nearest polygon edge.
/// </summary>
public bool TryClosestPoint(Vector3 point, float maxDistance, out Vector3 closest)
{
return TryClosestPoint(point, maxDistance, -1, out closest);
}
/// <summary>
/// Region of the polygon under a point on the graph, and that region's polygon count; -1 if none.
/// </summary>
public int RegionAt(Vector3 point, out int polygons)
{
var poly = Locate(point);
polygons = poly < 0 ? 0 : _regionSize[_region[poly]];
return poly < 0 ? -1 : _region[poly];
}
/// <summary>
/// Snaps both ends of a route onto one connected region. Each end goes to its closest graph point; if
/// those lie in different regions (the player can stand where the graph has no floor: its radius is
/// 0.15 m against the bake's 0.22 m, and SCN_Main has 23 small pockets near the main floor), either end
/// is moved, within <paramref name="maxDistance"/>, into the other's region, whichever moves less.
/// </summary>
/// <remarks>
/// <paramref name="isClear"/> checks a move between regions: a 2 m move went through the Basement
/// Janitor's west wall into the stairwell (2026-11-23 run), and the walk pressed into the wall.
/// </remarks>
public bool TrySnapConnected(Vector3 start, Vector3 goal, float maxDistance, Func<Vector3, Vector3, bool> isClear, out Vector3 snappedStart, out Vector3 snappedGoal, out string failure)
{
snappedStart = start;
snappedGoal = goal;
failure = string.Empty;
if (!TryClosestPoint(start, maxDistance, out var s))
{
failure = $"start {start} is not within {maxDistance} m of the graph";
return false;
}
if (!TryClosestPoint(goal, maxDistance, out var g))
{
failure = $"goal {goal} is not within {maxDistance} m of the graph";
return false;
}
var startRegion = RegionAt(s, out var startSize);
var goalRegion = RegionAt(g, out var goalSize);
if (startRegion == goalRegion)
{
snappedStart = s;
snappedGoal = g;
return true;
}
var moveStart = TryClosestPoint(start, maxDistance, goalRegion, out var s2) && isClear(start, s2) ? Vector3.Distance(s2, start) : float.MaxValue;
var moveGoal = TryClosestPoint(goal, maxDistance, startRegion, out var g2) && isClear(goal, g2) ? Vector3.Distance(g2, goal) : float.MaxValue;
if (moveStart == float.MaxValue && moveGoal == float.MaxValue)
{
failure = $"start and goal are on separate parts of the floor ({startSize} and {goalSize} polygons) with none shared within {maxDistance} m without passing a wall";
return false;
}
if (moveStart <= moveGoal)
{
snappedStart = s2;
snappedGoal = g;
}
else
{
snappedStart = s;
snappedGoal = g2;
}
return true;
}
/// <summary>
/// Joins two parts of the floor through a doorway the bake left closed. The bake's agentClimb is 0.05 m,
/// so a door threshold splits the floor (SCN_Main: the Basement Janitor and Cupboard, 68 polygons, 1.3 m
/// from the main floor), while the player steps up to CharacterController.stepOffset, 0.3 m.
/// <paramref name="sideA"/> and <paramref name="sideB"/> are points either side of the doorway; each is
/// snapped onto the graph within <paramref name="maxDistance"/>. The snapped points must be on opposite
/// sides of <paramref name="doorway"/>, in different regions, and within <paramref name="maxStep"/> in
/// height. The link is a zero-width portal at the doorway's centre on the floor, so routes pass
/// through the middle of the doorway.
/// </summary>
public bool TryConnectAcross(Vector3 sideA, Vector3 sideB, Plane doorway, float maxDistance, float maxStep, out string result)
{
if (!TryClosestPoint(sideA, maxDistance, out var a) || !TryClosestPoint(sideB, maxDistance, out var b))
{
result = "no floor on one side";
return false;
}
var polyA = Locate(a);
var polyB = Locate(b);
if (polyA < 0 || polyB < 0)
{
result = "no polygon on one side";
return false;
}
if (_region[polyA] == _region[polyB])
{
result = "already connected";
return false;
}
if (doorway.GetSide(a) == doorway.GetSide(b))
{
result = "both sides snapped to the same side";
return false;
}
if (Math.Abs(a.y - b.y) > maxStep)
{
result = $"height step {Math.Abs(a.y - b.y):0.00} m";
return false;
}
var middle = (a + b) * 0.5f;
var onPlane = middle - doorway.normal * doorway.GetDistanceToPoint(middle);
result = Join(polyA, polyB, onPlane, crouch: false) + $", gap {Vector3.Distance(a, b):0.00} m";
return true;
}
/// <summary>Points where a route must be walked crouched (joins through low openings).</summary>
public readonly List<Vector3> CrouchPassages = new();
/// <summary>Set once the floor gaps of this graph have been checked against the scene's colliders.</summary>
public bool GapsChecked;
public readonly struct GapCandidate
{
public readonly Vector3 A;
public readonly Vector3 B;
public readonly int PolyA;
public readonly int PolyB;
public readonly float Gap;
public GapCandidate(Vector3 a, Vector3 b, int polyA, int polyB, float gap)
{
A = a;
B = b;
PolyA = polyA;
PolyB = polyB;
Gap = gap;
}
}
public bool SameRegion(int polyA, int polyB) => _region[polyA] == _region[polyB];
public int RegionSize(int poly) => _regionSize[_region[poly]];
/// <summary>
/// Places where two parts of the floor come within <paramref name="maxGap"/> of each other (in x/z) and
/// <paramref name="maxStep"/> in height: points along every outer polygon edge (one with no neighbour
/// link), every <paramref name="sampleStep"/>, paired with the closest edge of a polygon in another
/// region. Smallest gap first. Whether the gap can be walked is for the caller to check against the
/// scene (a wall between two rooms is a gap too).
/// </summary>
public List<GapCandidate> FindGapCandidates(float maxGap, float maxStep, float sampleStep)
{
var result = new List<GapCandidate>();
// Every gap has at least one side off the largest region, so only those polygons are sampled.
var largest = 0;
for (var r = 1; r < _regionSize.Count; r++)
{
if (_regionSize[r] > _regionSize[largest])
{
largest = r;
}
}
for (var i = 0; i < _polys.Length; i++)
{
if (_region[i] == largest)
{
continue;
}
var poly = _polys[i];
for (var k = 0; k < poly.Length; k++)
{
var p = poly[k];
var q = poly[(k + 1) % poly.Length];
if (IsLinkedEdge(i, p, q))
{
continue;
}
var length = new Vector2(q.x - p.x, q.z - p.z).magnitude;
var steps = Math.Max(1, Mathf.CeilToInt(length / sampleStep));
for (var s = 0; s <= steps; s++)
{
var point = Vector3.Lerp(p, q, s / (float)steps);
var bestGap = maxGap;
var bestPoly = -1;
var bestPoint = point;
for (var gx = Cell(point.x - maxGap); gx <= Cell(point.x + maxGap); gx++)
{
for (var gz = Cell(point.z - maxGap); gz <= Cell(point.z + maxGap); gz++)
{
if (!_grid.TryGetValue((gx, gz), out var candidates))
{
continue;
}
foreach (var j in candidates)
{
if (_region[j] == _region[i])
{
continue;
}
var other = ClosestOnEdges(_polys[j], point);
var gap = new Vector2(other.x - point.x, other.z - point.z).magnitude;
if (gap <= bestGap && Math.Abs(other.y - point.y) <= maxStep)
{
bestGap = gap;
bestPoly = j;
bestPoint = other;
}
}
}
}
if (bestPoly >= 0)
{
result.Add(new GapCandidate(point, bestPoint, i, bestPoly, bestGap));
}
}
}
}
result.Sort((x, y) => x.Gap.CompareTo(y.Gap));
return result;
}
/// <summary>Whether a neighbour link's shared edge lies on the edge p-q (it is not an outer edge).</summary>
private bool IsLinkedEdge(int poly, Vector3 p, Vector3 q)
{
foreach (var (_, a, b) in _links[poly])
{
if (DistanceToSegment(a, p, q) < 0.02f && DistanceToSegment(b, p, q) < 0.02f)
{
return true;
}
}
return false;
}
private static float DistanceToSegment(Vector3 x, Vector3 p, Vector3 q)
{
var pq = q - p;
var t = pq.sqrMagnitude < 1e-9f ? 0f : Mathf.Clamp01(Vector3.Dot(x - p, pq) / pq.sqrMagnitude);
return Vector3.Distance(x, p + pq * t);
}
/// <summary>
/// Links two polygons in different regions through a zero-width portal at <paramref name="at"/> (routes
/// pass through that point) and merges the regions. Crouch joins are remembered in CrouchPassages.
/// </summary>
public string Join(int polyA, int polyB, Vector3 at, bool crouch)
{
_links[polyA] = Append(_links[polyA], (polyB, at, at));
_links[polyB] = Append(_links[polyB], (polyA, at, at));
if (crouch)
{
CrouchPassages.Add(at);
}
var keep = _region[polyA];
var merge = _region[polyB];
if (keep == merge)
{
return $"linked at {at}";
}
var moved = 0;
for (var i = 0; i < _region.Length; i++)
{
if (_region[i] == merge)
{
_region[i] = keep;
moved++;
}
}
_regionSize[keep] += moved;
_regionSize[merge] = 0;
return $"joined {moved} polygons to {_regionSize[keep] - moved} at {at}";
}
private static (int, Vector3, Vector3)[] Append((int, Vector3, Vector3)[] links, (int, Vector3, Vector3) link)
{
var result = new (int, Vector3, Vector3)[links.Length + 1];
Array.Copy(links, result, links.Length);
result[^1] = link;
return result;
}
private bool TryClosestPoint(Vector3 point, float maxDistance, int region, out Vector3 closest)
{
closest = point;
var best = maxDistance;
var found = false;
for (var gx = Cell(point.x - maxDistance); gx <= Cell(point.x + maxDistance); gx++)
{
for (var gz = Cell(point.z - maxDistance); gz <= Cell(point.z + maxDistance); gz++)
{
if (!_grid.TryGetValue((gx, gz), out var candidates))
{
continue;
}
foreach (var i in candidates)
{
if (region >= 0 && _region[i] != region)
{
continue;
}
var poly = _polys[i];
Vector3 onPoly;
if (TryHeightInside(poly, point.x, point.z, out var y))
{
onPoly = new Vector3(point.x, y, point.z);
}
else
{
onPoly = ClosestOnEdges(poly, point);
}
var distance = Vector3.Distance(onPoly, point);
if (distance <= best)
{
best = distance;
closest = onPoly;
found = true;
}
}
}
}
return found;
}
private static Vector3 ClosestOnEdges(Vector3[] poly, Vector3 p)
{
var best = float.MaxValue;
var result = poly[0];
for (var k = 0; k < poly.Length; k++)
{
var a = poly[k];
var b = poly[(k + 1) % poly.Length];
var ab = b - a;
var t = ab.sqrMagnitude < 1e-9f ? 0f : Mathf.Clamp01(Vector3.Dot(p - a, ab) / ab.sqrMagnitude);
var q = a + ab * t;
var d = (q - p).sqrMagnitude;
if (d < best)
{
best = d;
result = q;
}
}
return result;
}
/// <summary>For every polygon within <paramref name="radius"/> of the point, its closest point to it.</summary>
public void PointsNear(Vector3 point, float radius, List<Vector3> result)
{
var seen = new HashSet<int>();
for (var gx = Cell(point.x - radius); gx <= Cell(point.x + radius); gx++)
{
for (var gz = Cell(point.z - radius); gz <= Cell(point.z + radius); gz++)
{
if (!_grid.TryGetValue((gx, gz), out var candidates))
{
continue;
}
foreach (var i in candidates)
{
if (!seen.Add(i))
{
continue;
}
var poly = _polys[i];
var onPoly = TryHeightInside(poly, point.x, point.z, out var y) ? new Vector3(point.x, y, point.z) : ClosestOnEdges(poly, point);
if (Vector3.Distance(onPoly, point) <= radius)
{
result.Add(onPoly);
}
}
}
}
}
/// <summary>The height of every polygon (every floor) whose x/z covers the point.</summary>
public void FloorHeightsAt(float x, float z, List<float> heights)
{
if (!_grid.TryGetValue((Cell(x), Cell(z)), out var candidates))
{
return;
}
foreach (var i in candidates)
{
if (TryHeightInside(_polys[i], x, z, out var y) && !heights.Exists(h => Math.Abs(h - y) < 0.1f))
{
heights.Add(y);
}
}
}
/// <summary>The polygon under a NavMesh point: inside it in x/z, with the closest height (within 0.5 m).</summary>
public int Locate(Vector3 point)
{
if (!_grid.TryGetValue((Cell(point.x), Cell(point.z)), out var candidates))
{
return -1;
}
var best = -1;
var bestDy = 0.5f;
var nearest = -1;
var nearestScore = float.MaxValue;
foreach (var i in candidates)
{
var poly = _polys[i];
if (TryHeightInside(poly, point.x, point.z, out var y))
{
var dy = Math.Abs(y - point.y);
if (dy < bestDy)
{
best = i;
bestDy = dy;
}
continue;
}
// SamplePosition can return a point on a polygon's edge; accept the closest edge within 10 cm.
var planar = PlanarDistanceToPolygon(poly, point, out var edgeY);
var height = Math.Abs(edgeY - point.y);
if (planar < 0.1f && height < 0.5f && planar + height < nearestScore)
{
nearest = i;
nearestScore = planar + height;
}
}
return best >= 0 ? best : nearest;
}
private static bool TryHeightInside(Vector3[] poly, float x, float z, out float y)
{
var a = poly[0];
for (var k = 1; k < poly.Length - 1; k++)
{
var b = poly[k];
var c = poly[k + 1];
var d = (b.z - c.z) * (a.x - c.x) + (c.x - b.x) * (a.z - c.z);
if (Math.Abs(d) < 1e-9f)
{
continue;
}
var w1 = ((b.z - c.z) * (x - c.x) + (c.x - b.x) * (z - c.z)) / d;
var w2 = ((c.z - a.z) * (x - c.x) + (a.x - c.x) * (z - c.z)) / d;
var w3 = 1f - w1 - w2;
if (w1 >= -1e-4f && w2 >= -1e-4f && w3 >= -1e-4f)
{
y = w1 * a.y + w2 * b.y + w3 * c.y;
return true;
}
}
y = 0f;
return false;
}
private static float PlanarDistanceToPolygon(Vector3[] poly, Vector3 p, out float y)
{
var best = float.MaxValue;
y = 0f;
for (var k = 0; k < poly.Length; k++)
{
var a = poly[k];
var b = poly[(k + 1) % poly.Length];
var ab = new Vector2(b.x - a.x, b.z - a.z);
var ap = new Vector2(p.x - a.x, p.z - a.z);
var t = ab.sqrMagnitude < 1e-9f ? 0f : Mathf.Clamp01(Vector2.Dot(ap, ab) / ab.sqrMagnitude);
var d = (ap - ab * t).magnitude;
if (d < best)
{
best = d;
y = Mathf.Lerp(a.y, b.y, t);
}
}
return best;
}
/// <summary>
/// Route between two NavMesh points. Corners go into <paramref name="corners"/>, start excluded,
/// goal included. False when either point is on no polygon or the polygons are not connected.
/// </summary>
public bool TryRoute(Vector3 start, Vector3 goal, List<Vector3> corners, out int searched, out string failure)
{
corners.Clear();
searched = 0;
failure = string.Empty;
var from = Locate(start);
var to = Locate(goal);
if (from < 0 || to < 0)
{
failure = from < 0 ? $"start {start} is on no polygon" : $"goal {goal} is on no polygon";
return false;
}
var path = FindPolygonPath(from, to, start, goal, out searched);
if (path == null)
{
failure = "polygons not connected";
return false;
}
StringPull(path, start, goal, corners);
return true;
}
private List<int>? FindPolygonPath(int from, int to, Vector3 start, Vector3 goal, out int searched)
{
searched = 0;
if (from == to)
{
return new List<int> { from };
}
var cost = new Dictionary<int, float> { [from] = 0f };
var at = new Dictionary<int, Vector3> { [from] = start };
var parent = new Dictionary<int, int>();
var open = new SortedSet<(float F, int Order, int Poly)>();
var order = 0;
open.Add((Vector3.Distance(start, goal), order++, from));
while (open.Count > 0)
{
var current = open.Min;
open.Remove(current);
var poly = current.Poly;
var g = cost[poly];
if (current.F > g + Vector3.Distance(at[poly], goal) + 1e-4f)
{
continue; // stale entry
}
searched++;
if (poly == to)
{
var path = new List<int> { to };
while (path[^1] != from)
{
path.Add(parent[path[^1]]);
}
path.Reverse();
return path;
}
var here = at[poly];
foreach (var (other, a, b) in _links[poly])
{
var mid = (a + b) * 0.5f;
var next = g + Vector3.Distance(here, mid);
if (cost.TryGetValue(other, out var known) && known <= next)
{
continue;
}
cost[other] = next;
at[other] = mid;
parent[other] = poly;
open.Add((next + Vector3.Distance(mid, goal), order++, other));
}
}
return null;
}
private static float TriArea2(Vector3 a, Vector3 b, Vector3 c)
{
var ax = b.x - a.x;
var az = b.z - a.z;
var bx = c.x - a.x;
var bz = c.z - a.z;
return bx * az - ax * bz;
}
/// <summary>Height band of one funnel run (see StringPull).</summary>
private const float LevelBandMeters = 0.3f;
/// <summary>
/// Straightens the polygon path into corners. The funnel works in x/z, so over a path that passes over
/// or under itself (up the stairs and back above the start) it cut straight through the floor: 99 of
/// 1,000 random SCN_Main routes left their corridor, one climbing 3.4 m in 1.6 m. So the funnel runs
/// only over stretches whose shared edges stay within LevelBandMeters of the stretch's start height
/// (one floor, or a short piece of stairs, which cannot overlap itself); the edge that leaves the band
/// becomes a corner at its midpoint. With that, 0 of the same 1,000 routes leave their corridor.
/// </summary>
private void StringPull(List<int> path, Vector3 start, Vector3 goal, List<Vector3> corners)
{
var run = new List<(Vector3 Left, Vector3 Right)>();
var runStart = start;
for (var i = 0; i + 1 < path.Count; i++)
{
foreach (var (other, a, b) in _links[path[i]])
{
if (other != path[i + 1])
{
continue;
}
var mid = (a + b) * 0.5f;
if (Math.Abs(mid.y - runStart.y) > LevelBandMeters)
{
Funnel(run, runStart, mid, corners);
run.Clear();
runStart = mid;
}
else
{
run.Add((a, b));
}
break;
}
}
Funnel(run, runStart, goal, corners);
}
/// <summary>Recast's string pulling over one run of shared edges (edge order gives left and right).</summary>
private static void Funnel(List<(Vector3 Left, Vector3 Right)> edges, Vector3 start, Vector3 goal, List<Vector3> corners)
{
var portals = new List<(Vector3 Left, Vector3 Right)>(edges.Count + 2) { (start, start) };
portals.AddRange(edges);
portals.Add((goal, goal));
var apex = start;
var left = start;
var right = start;
int leftIndex = 0, rightIndex = 0;
for (var i = 1; i < portals.Count; i++)
{
var (l, r) = portals[i];
if (TriArea2(apex, right, r) <= 0f)
{
if (apex == right || TriArea2(apex, left, r) > 0f)
{
right = r;
rightIndex = i;
}
else
{
corners.Add(left);
apex = left;
right = left;
rightIndex = leftIndex;
i = leftIndex;
continue;
}
}
if (TriArea2(apex, left, l) >= 0f)
{
if (apex == left || TriArea2(apex, right, l) < 0f)
{
left = l;
leftIndex = i;
}
else
{
corners.Add(right);
apex = right;
left = right;
leftIndex = rightIndex;
i = rightIndex;
continue;
}
}
}
if (corners.Count == 0 || corners[^1] != goal)
{
corners.Add(goal);
}
}
}