Repository navigation
Expand file tree
/
Copy pathSimpleNavPlanner.cs
More file actions
4621 lines (4330 loc) · 253 KB
/
Copy pathSimpleNavPlanner.cs
File metadata and controls
4621 lines (4330 loc) · 253 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
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using BepInEx;
using UnityEngine;
namespace DateEverythingAccess
{
/// <summary>
/// O6.5 runtime planner: A* over per-floor navigable bitmaps (from
/// <c>navigable_region.bake.json</c>) plus inter-floor edges, producing a
/// <see cref="SimpleNavRoute"/> directly.
/// </summary>
// Originally a port of scripts/plan_object_route.py. That offline planner was retired on
// 2026-10-21 (it had drifted from this one); comments below that say "mirrors
// plan_object_route" refer to it as it stands in git history.
internal static class SimpleNavPlanner
{
private const string BakeFileName = "navigable_region.bake.json";
private const char NavigableChar = 'N';
private const float CornerWaypointDeg = 30f;
// (No planner-side interaction-radius constant: the planner uses the object's own
// InteractionRadius verbatim — interaction is gated on radius + line of sight, not on any
// bound we impose. See the radius handling in Plan() and BetterPlayerControl.Update.)
// Radius to snap a start/goal world position to the nearest navigable
// cell. 4.0m was too tight for real runtime starts: the player, driven
// by the executor, often ends up standing beside furniture (fireplace
// hearth, closet) more than 4m from any navigable cell, so Plan()
// returned no_path and the user had to reposition and replan
// repeatedly. 6.0m gives margin for those off-mesh standing spots while
// staying under the game's 7.5m default interaction radius and small enough that it
// won't routinely snap across a wall into the wrong room.
private const float NearestNavigableSearchM = 6.0f;
private const float FloorMatchToleranceM = 2.0f;
// Bounded clearance-cost A* + smoother guard. A cell nearer than
// ClearanceTargetCells (=4 cells = 0.8m) to a wall costs extra metres per missing
// clearance-cell, so A* prefers the wide lane through a doorway/between furniture
// WITHOUT detouring where there's no wider option. The smoother then refuses to
// straighten those margin-keeping curves back against the obstacle. Mirrors
// plan_object_route.py CLEARANCE_TARGET_CELLS / CLEARANCE_PENALTY_PER_CELL_M. See
// [[project-navigation-csharp-clearance-port-TODO]],
// [[project-navigation-clearance-cost-rejected-2026-05-29]] (reconciled: bounded, not flat).
private const int ClearanceTargetCells = 4;
private const float ClearancePenaltyPerCellM = 0.15f;
// Player-capsule + safety margin from the target's collider face. Goal cells whose
// player-capsule center is closer than this become invalid (overlap), and cells further
// than ColliderBandOuterM become invalid (too far to interact reliably). The result is
// a narrow band around the target so A* terminates near the collider rather than
// anywhere in the InteractionRadius disc.
private const float TargetColliderClearanceM = 0.5f;
// (The former TargetColliderBandOuterM 1.5m outer cap was removed: with a real per-cell
// line-of-sight test, distance within the InteractionRadius is no longer a quality signal,
// and the cap excluded the stand-back cells that give the cleanest line to an above-floor
// object. Goal cells are now bounded only by the InteractionRadius disc + LOS preference.)
// NOTE: the DoorHingeBandInner/OuterM geometric door-approach band was retired. A
// door target's goal cells now come exclusively from the bake's
// operable_from_cells (authoritative, swing-arc-aware). If a door lacks those
// cells the planner fails fast (DoorMissingOperableCells) rather than guessing
// with the band, so a missing/broken operability data source surfaces instead of
// being silently papered over. See [[project-navigation-door-operability-cells]].
private static BakeDoc _bake;
private static List<Floor> _floors;
private static float _cellSize;
private static Dictionary<NodeKey, List<EdgeRef>> _interFloorEdges;
// Min cost across all inter-floor edges, cached for the heuristic.
private static float _minInterFloorCost;
// Ramp interior points (world XYZ) keyed by the directed landing-cell pair, so a
// route crossing the stair seam can be expanded into a walkable polyline up the
// run. Direction matters: ascending and descending share geometry but reversed.
private static Dictionary<(NodeKey, NodeKey), Vector3[]> _stairRampInteriors;
private static bool _loadAttempted;
private static bool _loadOk;
// Names of doors and state-walls treated as open during the last
// ApplyLiveDoorState call. Captured here so the route-capture path can
// record overlay state without re-querying the live scene (which may
// have changed by the time we serialize).
private static List<string> _lastOpenDoorNames = new List<string>();
private static List<string> _lastOpenStateWallNames = new List<string>();
// Door names that are locked at scene load (exporter Door.Locked, carried
// through the bake). A locked door is a hard block; every other door is
// treated as openable when planning so A* can route through it and the
// executor opens it en route. Populated by IndexDoorFreedCells.
private static readonly HashSet<string> _lockedDoorNames = new HashSet<string>();
// Names of every door the BAKE modelled — the real PASSAGE/closet doors the player walks
// through or operates from a standpoint. A live GameObject can carry a Door component yet
// NOT be in here: fridge/cupboard "doors" are CONTAINERS the player opens in place and
// never walks through, so the exporter's door-detection rule deliberately skips them.
// The planner uses this to tell the two apart: a target Door IN this set takes the
// door-operability branch (and a missing operability set is a real bake bug → fail fast);
// a target Door NOT in this set is a container, routed like any other prop via the
// collider-band branch (front-approach; its swing is still a footprint blocker for
// pathing). See [[project-navigation-sweep-three-buckets-2026-06-12]].
private static readonly HashSet<string> _bakedDoorNames = new HashSet<string>();
// Container doors baked with operability ONLY (cupboard/fridge/breaker): opened in
// place to reveal an item inside, never traversed. These ARE in the bake (so they
// carry operable_from_cells) but are NOT passage doors — the item LOS rescue sees
// through them and tags them to be opened, routing to their baked operable cells.
// Kept separate from _bakedDoorNames so the passage-vs-container distinction holds.
private static readonly HashSet<string> _containerDoorNames = new HashSet<string>();
// Failure reasons surfaced by the most recent Plan() call. Read by the watcher to
// announce *why* a route couldn't be built instead of silently dropping. Cleared at
// the top of every Plan() invocation.
public enum PlanFailure
{
None,
NotReady,
StartOffBake,
TargetOffBake,
StartUnreachable,
TargetUnreachable,
NoPath,
// A door target has no operable_from_cells in the bake. We FAIL FAST here
// rather than fall back to a geometric hinge-band guess: a door with no
// operability data is a broken/missing data source (bake didn't compute it,
// e.g. a new scene's door geometry the operability pass didn't handle), and
// silently routing with a worse approximation would mask that. The log names
// the door so the producer can be fixed. See
// [[project-navigation-door-operability-cells]], [[feedback-fix-the-data-source-first]].
DoorMissingOperableCells,
// No navigable cell within the target's InteractionRadius has a clear interaction
// line-of-sight to it. LOS is MANDATORY — the game's interaction needs the camera ray
// to hit the object (BetterPlayerControl.Update) — so a cell without it is not a
// valid standpoint. Rather than route the player to a spot they provably can't interact
// from, we fail here: the object is reachable but not interactable from anywhere on the
// mesh (occluded by furniture/geometry, or only reachable from cells the ray can't
// clear). Names the target so the cause (placement/occluder) can be investigated.
TargetNoLineOfSight,
}
public static PlanFailure LastFailure { get; private set; } = PlanFailure.None;
/// <summary>
/// Plan a route from the player's current world position to the target object's world
/// position. Returns null if the bake isn't loaded, no path is found, or inputs are
/// invalid. The caller installs the returned route via <see cref="SimpleNavBridge.BeginRoute"/>.
/// </summary>
public static SimpleNavRoute Plan(
Vector3 startPos,
Vector3 targetPos,
float interactionRadius,
string targetName,
int targetGameObjectId,
bool targetIsDatable = false,
string targetInkFileName = null)
{
LastFailure = PlanFailure.None;
if (!EnsureLoaded())
{
LastFailure = PlanFailure.NotReady;
return null;
}
PruneRuntimeBlockers();
ReadLiveEyeData();
var planWatch = System.Diagnostics.Stopwatch.StartNew();
// Reflect live Door.open states into per-floor freed-cell overlays so A* can route
// through doors that are already open. Closed doors fall back to the bake's
// closed-pose blockers (which the door-tagging pass still flags so the executor
// opens them en route).
ApplyLiveDoorState();
// Correct a DEGENERATE target position. Some interactables (animated cushions,
// curtains, the broken-glass front door, ~30 objects) report a transform.position at
// their RIG ORIGIN — often near (0,0,0) — tens of metres from where the object's
// geometry actually is. Planning to that bogus point centres the goal disc on empty
// space and the object is unreachable. The object's COLLIDER carries the true world
// location, so when the given targetPos lies OUTSIDE the resolved collider's bounds
// (with a small pad), substitute the collider's bounds centre. Inside-bounds positions
// (large objects whose pivot is off-centre but still on the object) are left untouched.
// See [[project_navigation_target_position_degenerate]].
// ANCHOR FIRST. Collider selection scores candidates by distance to the interactable's
// transform, and for a degenerate object that transform is the rig origin (~world
// zero) — so selection picks whatever ANCESTOR collider is nearest world zero rather
// than one on the actual object. Kopi (the coffee machine) has no collider of its own,
// so the parent walk answered with an enclosing counter/cabinet block at
// (-31.06,3.57,26.34); the position "correction" then centred on THAT, the LOS filter
// found almost no standpoint, and front-approach cut the goals to 28 cells stranded
// behind the counter → no_path from anywhere in the house.
// The RENDERER bounds locate the real object without needing a collider at all, so when
// the transform is degenerate we use the renderer centre as the anchor and re-select the
// collider against it. Non-degenerate objects are unaffected (anchor stays the
// transform, so the same collider is chosen as before).
Bounds? renderBoundsForAnchor = ResolveTargetRenderBounds(targetGameObjectId);
if (renderBoundsForAnchor.HasValue)
{
Bounds rb0 = renderBoundsForAnchor.Value;
const float anchorPad = 0.5f;
bool transformOffObject =
targetPos.x < rb0.min.x - anchorPad || targetPos.x > rb0.max.x + anchorPad ||
targetPos.z < rb0.min.z - anchorPad || targetPos.z > rb0.max.z + anchorPad;
if (transformOffObject)
{
if (Main.Log != null)
Main.Log.LogInfo("SimpleNavPlanner.Plan: degenerate transform for " +
(targetName ?? "<null>") + "#" + targetGameObjectId + " at " +
targetPos.ToString("F2") + "; anchoring collider selection at RENDERER centre " +
rb0.center.ToString("F2"));
targetPos = rb0.center;
}
}
Collider posCheckCollider = ResolveTargetCollider(targetGameObjectId, targetPos);
if (posCheckCollider != null)
{
Bounds b = posCheckCollider.bounds;
const float pad = 0.5f;
bool outsideXZ =
targetPos.x < b.min.x - pad || targetPos.x > b.max.x + pad ||
targetPos.z < b.min.z - pad || targetPos.z > b.max.z + pad;
// Don't re-correct a position the renderer bounds already placed ON the object: for
// a collider-less interactable the resolved collider is an ANCESTOR (counter,
// cabinet, table) that merely encloses the object, and its centre can sit metres
// away — dragging the goal disc back off the target we just located. The renderer
// centre is the more specific point, so it wins.
bool anchoredByRenderer =
renderBoundsForAnchor.HasValue &&
targetPos == renderBoundsForAnchor.Value.center;
if (outsideXZ && !anchoredByRenderer)
{
Vector3 corrected = b.center;
if (Main.Log != null)
Main.Log.LogInfo("SimpleNavPlanner.Plan: corrected degenerate targetPos for " +
(targetName ?? "<null>") + "#" + targetGameObjectId +
" from " + targetPos.ToString("F2") + " to collider centre " + corrected.ToString("F2"));
targetPos = corrected;
}
}
// (No collider-less branch needed: the renderer-anchor block above has already moved a
// degenerate targetPos onto the real object, whether or not a collider resolves.)
Floor startFloor = FloorForY(startPos.y, StartFloorMatchToleranceM);
Floor goalFloor = FloorForTargetY(targetPos.y);
if (startFloor == null)
{
if (Main.Log != null) Main.Log.LogWarning("SimpleNavPlanner.Plan: start Y=" + startPos.y + " not on a baked floor");
LastFailure = PlanFailure.StartOffBake;
return null;
}
if (goalFloor == null)
{
if (Main.Log != null) Main.Log.LogWarning("SimpleNavPlanner.Plan: target Y=" + targetPos.y + " not on a baked floor");
LastFailure = PlanFailure.TargetOffBake;
return null;
}
int sIx, sIz;
if (!startFloor.NearestNavigable(startPos.x, startPos.z, NearestNavigableSearchM, out sIx, out sIz))
{
if (Main.Log != null) Main.Log.LogWarning("SimpleNavPlanner.Plan: no navigable cell near start (" + startPos.x + "," + startPos.z + ") on " + startFloor.Label);
LastFailure = PlanFailure.StartUnreachable;
return null;
}
NodeKey startNode = new NodeKey(startFloor.Label, sIx, sIz);
// Use the game's OWN interaction radius exactly as given — no planner clamp, no default.
// Interaction is gated purely on `Distance(camera, ClosestPointOnBounds) < InteractionRadius`
// + line of sight (BetterPlayerControl.Update). Every real interactable carries a
// radius (verified: 0/2612 missing; values include 10m and 25m the old 7.5 cap wrongly
// shrank). A degenerate radius (0 — only the junk "Main Camera" entry, never a real nav
// target) simply yields no goal cells and is handled by the goals.Count==0 path below.
float radius = interactionRadius;
List<NodeKey> goals = GoalCellsAround(goalFloor, targetPos.x, targetPos.z, radius);
if (goals.Count == 0)
{
int gIx, gIz;
if (!goalFloor.NearestNavigable(targetPos.x, targetPos.z, NearestNavigableSearchM, out gIx, out gIz))
{
if (Main.Log != null) Main.Log.LogWarning("SimpleNavPlanner.Plan: no navigable cell near target (" + targetPos.x + "," + targetPos.z + ") on " + goalFloor.Label);
LastFailure = PlanFailure.TargetUnreachable;
return null;
}
goals.Add(new NodeKey(goalFloor.Label, gIx, gIz));
}
// Refine goal cells by target kind:
// - Door targets: goals come from the bake's operable_from_cells (handled
// just below) — authoritative swing-arc-aware standpoints; the disc above
// is discarded for doors.
// - Non-door targets: keep the whole interaction-radius disc, drop cells that
// overlap the collider (< TargetColliderClearanceM via ClosestPointOnBounds),
// then PREFER cells with clear interaction line-of-sight. The game's gate is
// radius + LOS, so any in-radius LOS-clear cell is valid — we no longer cap to
// a tight near-the-collider band (that excluded the stand-back cells that are
// the only clean line to an above-floor object).
// See [[project_navigation_planner_los_goal_cells_2026_06_13]], [[project-navigation-door-operability-cells]].
// A live Door component alone doesn't make this a passage door: fridge/cupboard
// containers carry one too. Only treat it as a door target if the bake actually
// modelled it (it's in the passage-door set). Container doors — present live, absent
// from the bake — are dropped to null here so they route through the prop collider
// branch below: front-approach, swing arc as a footprint blocker, no operable-cell
// requirement (which would fail-fast on them). See the three-buckets memo.
Door targetDoor = ResolveTargetDoor(targetGameObjectId, targetName);
if (targetDoor != null && targetDoor.gameObject != null &&
!_bakedDoorNames.Contains(targetDoor.gameObject.name))
{
if (Main.Log != null)
Main.Log.LogInfo("SimpleNavPlanner.Plan: target=" + (targetName ?? "<null>") +
" (" + targetDoor.gameObject.name + ") has a Door component but isn't a baked " +
"passage door — treating as a container/prop (collider-band approach).");
targetDoor = null;
}
// Reuse the collider already resolved for the degenerate-position check above
// (avoids a second FindObjectsOfType). Null for door targets — they use
// operable_from_cells, not the collider-LOS goal filter.
Collider targetCollider = targetDoor == null ? posCheckCollider : null;
// Container door(s) the LOS rescue found occluding this item; the executor opens these
// at the destination so the player can interact with what's inside. Null = no rescue.
List<string> containerDoorsToOpen = null;
// Per-goal view quality for the AStar tiebreak (set by the collider-LOS branch below;
// null for door targets, which use operability cells with no LOS quality signal).
Dictionary<NodeKey, float> goalQuality = null;
// Door target: the goal set is the bake's operable_from_cells — the
// authoritative navigable cells the player can stand in to operate this door
// (excludes the swing arc and the panel, computed from the real Door.cs rule).
// This is REQUIRED, not best-effort: if a door has no operable cells we FAIL
// FAST (loud log + DoorMissingOperableCells) instead of guessing with a
// geometric hinge band. A door without operability data is a broken/missing
// data source to fix at the producer, not to paper over at runtime. See
// [[project-navigation-door-operability-cells]], [[feedback-fix-the-data-source-first]].
if (targetDoor != null && targetDoor.gameObject != null)
{
HashSet<long> operable;
List<NodeKey> opGoals = null;
if (goalFloor.OperableFromByName.TryGetValue(targetDoor.gameObject.name, out operable)
&& operable.Count > 0)
{
opGoals = new List<NodeKey>(operable.Count);
foreach (long packed in operable)
{
int ix = (int)(packed >> 32);
int iz = (int)(uint)packed;
if (goalFloor.Navigable(ix, iz))
opGoals.Add(new NodeKey(goalFloor.Label, ix, iz));
}
}
if (opGoals == null || opGoals.Count == 0)
{
if (Main.Log != null)
Main.Log.LogWarning("SimpleNavPlanner.Plan: door target=" +
(targetName ?? "<null>") + " (" + targetDoor.gameObject.name +
") on " + goalFloor.Label + " has no operable_from_cells in the bake" +
(operable != null && operable.Count > 0 ? " (all off the navigable set)" : "") +
" — failing fast; fix the bake's door operability data for this door.");
LastFailure = PlanFailure.DoorMissingOperableCells;
return null;
}
goals = opGoals;
// A walk to a door stops on the player's side of it: never plan through the door to
// a spot in the room beyond (after a stall blocked the spots in front of the laundry
// closet, the re-plan picked ones inside the closet and walked her into the door).
List<NodeKey> nearSide = GoalsOnPlayerSide(goalFloor, targetDoor.gameObject.name, startPos, goals);
if (nearSide != null && nearSide.Count > 0 && nearSide.Count < goals.Count)
{
if (Main.Log != null)
Main.Log.LogInfo("SimpleNavPlanner.Plan: door target kept " + nearSide.Count + "/" + goals.Count +
" goals on the player's side of " + targetDoor.gameObject.name);
goals = nearSide;
}
}
// Non-door collider target: the game's interaction gate is radius + LINE OF SIGHT, and
// nothing else — interaction needs the camera ray to HIT the object within
// InteractionRadius (BetterPlayerControl.Update). LOS is therefore MANDATORY, not a
// preference: a cell from which the ray can't reach the object is not a valid standpoint,
// and routing the player there would put them somewhere they provably can't interact.
// Distance within the radius is NOT a quality signal, so we do NOT narrow to a tight
// near-the-collider band (that crude pre-LOS proxy threw away the stand-BACK cells that
// are the only clean line to an above-floor object). Instead: from the whole radius disc,
// keep ONLY cells that (a) don't overlap the collider and (b) have clear interaction LOS.
// If none qualify, the object is reachable but not interactable from anywhere on the
// mesh → fail fast with TargetNoLineOfSight rather than route to a useless cell.
// LOS is live physics (C#-only); it doesn't change the route graph, only goal selection.
// See [[project_navigation_planner_los_goal_cells_2026_06_13]].
else if (targetCollider != null)
{
// A door is a door: the interaction sightline SEES PAST any operable container
// door (closed, unlocked cupboard/cabinet/fridge) the same way A* routes THROUGH a
// closed passage door — the executor opens it on arrival. Each cell's LOS records
// which container doors its line passed through; the selected cells' doors are
// tagged on the route so they're opened before the interaction. See
// [[project_navigation_container_open_on_interact]].
List<NodeKey> losClear = new List<NodeKey>(goals.Count);
List<HashSet<string>> passedOf = new List<HashSet<string>>(goals.Count);
float innerSq = TargetColliderClearanceM * TargetColliderClearanceM;
float bestClearance = 0f;
List<float> clearanceOf = new List<float>(goals.Count);
// Per-goal VIEW QUALITY (higher = more likely the game's interaction ray targets the
// object from here). Used as the tiebreak among equally-simple routes in AStar,
// replacing raw proximity. Combines side-clearance margin with a height-aware
// diagonal-angle bonus: for an above-eye target, standing directly under it gives a
// near-vertical sightline that grazes the ceiling/wall and self-occludes, while a
// stand-back cell gives a clean diagonal up-look. See
// [[project_navigation_los_camera_origin_mismatch_2026_06_14]].
goalQuality = new Dictionary<NodeKey, float>(goals.Count);
// Use the game-exact selection test for this target (see GameWouldSelectTarget).
_strictLosCollider = targetCollider;
_strictLosTarget = ResolveTargetInteractable(targetGameObjectId);
bool usedStrictLos = _strictLosTarget != null;
for (int pass = 0; pass < 2; pass++)
{
for (int i = 0; i < goals.Count; i++)
{
NodeKey g = goals[i];
Vector2 xz = goalFloor.CellToWorld(g.Ix, g.Iz);
Vector3 cellWorld = new Vector3(xz.x, goalFloor.FloorY + 1.0f, xz.y);
Vector3 nearest = targetCollider.ClosestPointOnBounds(cellWorld);
float dx = nearest.x - cellWorld.x;
float dz = nearest.z - cellWorld.z;
float d2 = dx * dx + dz * dz;
if (d2 < innerSq)
continue; // cell overlaps the collider — can't stand here
HashSet<string> passed = new HashSet<string>(StringComparer.Ordinal);
float margin = CellLineOfSightClearanceM(goalFloor, g, targetCollider, radius, passed);
if (margin >= 0f)
{
losClear.Add(g);
passedOf.Add(passed);
clearanceOf.Add(margin);
if (margin > bestClearance) bestClearance = margin;
goalQuality[g] = GoalViewQuality(goalFloor, g, targetCollider, margin);
}
}
if (losClear.Count > 0 || _strictLosTarget == null)
break;
// SAFETY NET: the strict test found no standpoint anywhere. Rather than turn this
// into a hard "no path", fall back to the older lenient test for this one target and
// say so loudly in the log, so objects where the strict model is wrong can be found
// and fixed instead of silently disappearing from auto-walk.
if (Main.Log != null)
Main.Log.LogWarning("SimpleNavPlanner.Plan: strict game-ray LOS found no standpoint for target=" +
(targetName ?? "<null>") + "#" + targetGameObjectId +
" — falling back to lenient LOS (the game may not select it on arrival).");
LogStrictLosDiagnostics(goalFloor, goals, targetCollider, _strictLosTarget, targetName);
_strictLosTarget = null;
usedStrictLos = false;
losClear.Clear(); passedOf.Clear(); clearanceOf.Clear(); goalQuality.Clear();
bestClearance = 0f;
}
_strictLosCollider = null;
_strictLosTarget = null;
if (usedStrictLos && Main.Log != null)
Main.Log.LogInfo("SimpleNavPlanner.Plan: strict game-ray LOS kept " + losClear.Count +
" standpoint(s) for target=" + (targetName ?? "<null>") + "#" + targetGameObjectId);
// NO SIGHTLINE FROM ANYWHERE: walk to the nearest spots beside it anyway, and the aim
// help takes over on arrival, rather than refusing to go at all.
if (losClear.Count == 0)
{
for (int pass = 0; pass < 2 && losClear.Count == 0; pass++)
{
for (int i = 0; i < goals.Count; i++)
{
NodeKey g = goals[i];
Vector2 axz = goalFloor.CellToWorld(g.Ix, g.Iz);
Vector3 aCell = new Vector3(axz.x, goalFloor.FloorY + 1.0f, axz.y);
Vector3 aNear = targetCollider.ClosestPointOnBounds(aCell);
float adx = aNear.x - aCell.x, adz = aNear.z - aCell.z;
float ad2 = adx * adx + adz * adz;
if (ad2 < innerSq) continue;
if (pass == 0 && ad2 > ApproachOnlyWithinM * ApproachOnlyWithinM) continue;
losClear.Add(g);
passedOf.Add(new HashSet<string>(StringComparer.Ordinal));
clearanceOf.Add(0f);
goalQuality[g] = 0f;
}
}
if (losClear.Count > 0 && Main.Log != null)
Main.Log.LogWarning("SimpleNavPlanner.Plan: no sightline to target=" + (targetName ?? "<null>") +
" from anywhere; walking to the nearest of " + losClear.Count +
" spots beside it instead (the aim help takes over there)");
}
// FRONT-APPROACH: if this object faces one way and has LOS-clear cells on BOTH its
// front and back, keep only the front cells — a standpoint behind a monitor/TV/painting
// passes the offline ray (it hits the box's back face) but the game won't let the player
// interact from back there. Filters losClear + its parallel bookkeeping in lockstep;
// returns null (no change) for omnidirectional or one-sided objects. See the constant.
// Only needed for the lenient test: the strict game-ray test already rejects standpoints
// behind a monitor/TV/painting, and it does so from real geometry rather than trusting
// the model's forward axis (the office Monitor's forward points out of its BACK, which
// made this heuristic keep exactly the wrong side).
List<NodeKey> frontGoals = usedStrictLos ? null : FrontApproachGoals(
goalFloor, losClear, targetPos, TargetForwardXZ(targetGameObjectId), passedOf, clearanceOf);
if (frontGoals != null)
{
losClear = frontGoals;
// bestClearance may have been set by a now-discarded back cell; recompute over the
// surviving front cells so the closest-clear-cell prune threshold stays correct.
bestClearance = 0f;
for (int i = 0; i < clearanceOf.Count; i++)
if (clearanceOf[i] > bestClearance) bestClearance = clearanceOf[i];
if (Main.Log != null)
Main.Log.LogInfo("SimpleNavPlanner.Plan: front-approach preference kept " +
losClear.Count + " front-of-object goal cell(s) for target=" +
(targetName ?? "<null>") + "#" + targetGameObjectId +
" (discarded back-of-object standpoints).");
}
// LOOK-ANGLE LIMIT: the game won't tilt the camera more than about 70 degrees up or
// down. From a spot right next to something on the floor (the dust bunny, the Key)
// the look needed is steeper than that, so the player can never aim at it however
// long she holds the down arrow. Drop standpoints that need too steep a look when
// others remain.
if (losClear.Count > 0)
{
float eyeY = EyeYOnFloor(goalFloor);
float maxPitch = LiveMaxCameraPitchDeg() - LookPitchMarginDeg;
var okGoals = new List<NodeKey>(losClear.Count);
var okPassed = new List<HashSet<string>>(losClear.Count);
var okClear = new List<float>(losClear.Count);
for (int i = 0; i < losClear.Count; i++)
{
Vector2 cw = goalFloor.CellToWorld(losClear[i].Ix, losClear[i].Iz);
Vector3 eyePos = new Vector3(cw.x, eyeY, cw.y);
Vector3 aimAt = targetCollider.ClosestPointOnBounds(eyePos);
float horiz = new Vector2(aimAt.x - eyePos.x, aimAt.z - eyePos.z).magnitude;
float pitch = Mathf.Atan2(Mathf.Abs(aimAt.y - eyePos.y), Mathf.Max(0.01f, horiz)) * Mathf.Rad2Deg;
if (pitch > maxPitch) continue;
okGoals.Add(losClear[i]);
okPassed.Add(passedOf[i]);
okClear.Add(clearanceOf[i]);
}
if (okGoals.Count > 0 && okGoals.Count < losClear.Count)
{
if (Main.Log != null)
Main.Log.LogInfo("SimpleNavPlanner.Plan: look-angle limit kept " + okGoals.Count + "/" +
losClear.Count + " standpoints for target=" + (targetName ?? "<null>") +
" (eyeY " + eyeY.ToString("F2") + ", max " + maxPitch.ToString("F0") + " deg)");
losClear = okGoals;
passedOf = okPassed;
clearanceOf = okClear;
bestClearance = 0f;
for (int i = 0; i < clearanceOf.Count; i++)
if (clearanceOf[i] > bestClearance) bestClearance = clearanceOf[i];
}
}
if (losClear.Count > 0)
{
// CLOSEST-CLEAR-CELL: prefer SOLIDLY-clear standpoints over edge-grazing ones.
// When any cell clears with real side margin, drop the cells that only barely
// clear (margin a full probe-step below the best). This removes the far doorframe-
// grazed / furniture-skimming standpoints that pass the boolean test but fail the
// game's real ray, while keeping the leg-optimal pick among the robust cells.
// See [[project_navigation_noloss_full_classification_2026_06_14]].
//
// SKIP this prune for HIGH-MOUNTED targets. The side margin is measured on a
// HORIZONTAL perpendicular, and for a near-vertical sightline the clearance probe
// short-circuits to max — so the cell directly UNDER a ceiling fixture reports the
// highest margin and the prune would discard the stand-back diagonal cells that
// are actually the better view. For high mounts we keep the whole LOS-clear set
// and let GoalViewQuality's diagonal-angle term rank them. See
// [[project_navigation_los_camera_origin_mismatch_2026_06_14]].
bool targetHighMounted =
(targetCollider.bounds.center.y - EyeYOnFloor(goalFloor)) > HighMountEyeRiseM;
HashSet<string> containerDoorsSeen = new HashSet<string>(StringComparer.Ordinal);
if (bestClearance > 0f && !targetHighMounted)
{
float keepAbove = bestClearance - LosProbeSideOffsetsM[0] - 1e-4f;
List<NodeKey> solid = new List<NodeKey>(losClear.Count);
for (int i = 0; i < losClear.Count; i++)
if (clearanceOf[i] >= keepAbove)
{
solid.Add(losClear[i]);
foreach (string dn in passedOf[i]) containerDoorsSeen.Add(dn);
}
goals = solid.Count > 0 ? solid : losClear;
if (solid.Count == 0)
for (int i = 0; i < passedOf.Count; i++)
foreach (string dn in passedOf[i]) containerDoorsSeen.Add(dn);
}
else
{
goals = losClear;
for (int i = 0; i < passedOf.Count; i++)
foreach (string dn in passedOf[i]) containerDoorsSeen.Add(dn);
}
if (containerDoorsSeen.Count > 0)
containerDoorsToOpen = new List<string>(containerDoorsSeen);
}
else
{
if (Main.Log != null)
Main.Log.LogWarning("SimpleNavPlanner.Plan: no goal cell with interaction line-of-sight for target=" +
(targetName ?? "<null>") + "#" + targetGameObjectId +
" — object reachable but not interactable from any navigable cell (occluded / placement)");
LastFailure = PlanFailure.TargetNoLineOfSight;
return null;
}
}
List<NodeKey> path = null;
float totalCost = 0f;
// The bake is dilated by the body's real 0.8 m radius, so every navigable goal cell
// already has room for the body; there is no clearance tier to prefer here.
bool planned = false;
// DOOR TARGET: finish squarely in front of the doorway, on the player's side, so walking
// straight forward afterwards goes through it. Falls back to the normal goals below.
string frontDoorName = targetDoor != null && targetDoor.gameObject != null
? targetDoor.gameObject.name : targetName;
// With the door already OPEN, any walkable cell squarely in front will do (the leaf has
// swung aside and its cells are blocked). While it is CLOSED the player must also be able
// to open it from there, so only the operable cells count; for a door that swings
// toward the player those all sit in the swing, and the normal goals are used instead
// (the executor then waits for the swing and re-plans once it is open).
bool frontDoorOpen = targetDoor != null && targetDoor.open;
List<NodeKey> doorFrontGoals = FrontOfDoorwayGoals(goalFloor, frontDoorName, startPos,
frontDoorOpen ? null : goals);
if (doorFrontGoals != null &&
AStar(startNode, doorFrontGoals, goalFloor.Label, targetPos.x, targetPos.z, out path, out totalCost, goalQuality))
{
planned = true;
if (Main.Log != null)
Main.Log.LogInfo("SimpleNavPlanner.Plan: door-front goals kept " + doorFrontGoals.Count + "/" + goals.Count +
" for door=" + frontDoorName);
goals = doorFrontGoals;
}
if (!planned &&
!AStar(startNode, goals, goalFloor.Label, targetPos.x, targetPos.z, out path, out totalCost, goalQuality))
{
// The closed-state plan to the LOS goal cells failed. Retry only with DOORS
// RELAXED (every door assumed openable, state-walls released) on the SAME goal
// set — autowalk opens gating doors en route via the segment door-tags. We do NOT
// widen the goal set back to the full radius disc: LOS is mandatory, so a non-LOS
// cell is never an acceptable destination even when the LOS cells are unreachable.
// Bedroom-from-bedroom is the canonical relax case (all doors closed at scene load).
{
if (TryRelaxedPlan(startNode, goals, goalFloor.Label, targetPos,
out path, out totalCost, goalQuality))
{
if (Main.Log != null)
Main.Log.LogInfo("SimpleNavPlanner.Plan: retried with all-doors-open for target=" +
(targetName ?? "<null>") + "#" + targetGameObjectId +
" (autowalk will open gating doors en route)");
}
else
{
// DIAGNOSTIC (2026-06-15, batched sweep): no_path here means BOTH the
// closed-state and doors-relaxed A* failed to reach any of the (LOS-valid)
// goal cells. The same objects plan fine OFFLINE from the manifest start, so
// the suspect is the in-game START cell. Distinguish a real planner gap from
// a harness artifact (start dropped in a disconnected pocket): flood the
// doors-relaxed navigable graph from startNode and report how many goal cells
// fall in the start's reachable component vs the component's total size.
// goalsInComponent>0 → goals ARE reachable but A* failed → real bug.
// goalsInComponent==0 + small component → start pocketed (likely artifact).
// goalsInComponent==0 + large component → goals genuinely isolated.
// See [[project-navigation-sweep-2026-06-16]].
if (Main.Log != null)
{
int goalsInComp, compSize;
DiagnoseNoPathReach(startNode, goals, out goalsInComp, out compSize);
Main.Log.LogWarning("SimpleNavPlanner.Plan: no_path target=" +
(targetName ?? "<null>") + "#" + targetGameObjectId +
" start=" + startNode.Floor + "(" + startNode.Ix + "," + startNode.Iz + ")" +
" goals=" + goals.Count +
" goalsInStartComponent=" + goalsInComp +
" startComponentCells=" + compSize);
}
LastFailure = PlanFailure.NoPath;
return null;
}
}
}
List<NodeKey> waypoints = SmoothPath(path);
List<List<string>> segmentDoorNames = TagDoors(waypoints, targetName, targetPos, radius);
// A container door the interaction sightline saw past is the LAST barrier before the
// item — tag it on the final approach segment so the executor opens it on arrival (the
// same open-on-reach the on-route passage doors get from TagDoors). De-dupes against
// TagDoors' own destination rule, which may tag the same door from its opening center.
if (containerDoorsToOpen != null && containerDoorsToOpen.Count > 0 && segmentDoorNames.Count > 0)
{
List<string> lastSeg = segmentDoorNames[segmentDoorNames.Count - 1];
if (lastSeg == null)
{
lastSeg = new List<string>(containerDoorsToOpen.Count);
segmentDoorNames[segmentDoorNames.Count - 1] = lastSeg;
}
for (int i = 0; i < containerDoorsToOpen.Count; i++)
if (!lastSeg.Contains(containerDoorsToOpen[i]))
lastSeg.Add(containerDoorsToOpen[i]);
}
// segmentDoorNames is per cell-waypoint segment (length waypoints.Count-1). The
// ramp-interior insertion below adds waypoints at the stair seam, splitting that
// one seam segment into several; expandedSegmentDoors mirrors the insertion with
// empty (no-door) entries so door tags stay aligned to their segments.
List<List<string>> expandedSegmentDoors = new List<List<string>>(segmentDoorNames.Count);
SimpleNavRoute route = new SimpleNavRoute();
route.TargetName = targetName;
route.TargetGameObjectId = targetGameObjectId;
route.TargetPosition = targetPos;
route.TargetInteractionRadius = radius;
route.TargetIsDatable = targetIsDatable;
route.TargetInkFileName = targetInkFileName;
// expandedSegmentDoors[j] is the door list for the segment STARTING at
// rawRouteWaypoints[j] (the same convention AddRouteWaypoints reads). For each
// source cell-waypoint i (i < last) we append exactly one door entry —
// segmentDoorNames[i] — for the segment leaving waypoint i. When we insert K
// ramp-interior points BEFORE landing waypoint i, the K extra segments they add
// all belong to the seam (no door), so we append K empty entries at that point.
List<Vector3> rawRouteWaypoints = new List<Vector3>(waypoints.Count);
// Parallel to rawRouteWaypoints: a per-raw-waypoint kind override (null = let
// AddRouteWaypoints decide Navigation/Target). Used to tag staircase LANDINGS — the
// cells where a cross-floor route changes floor — as Stairs landmarks. Threaded through
// like expandedSegmentDoors rather than position-matched after the fact.
List<SimpleNavWaypointKind?> rawWaypointKinds = new List<SimpleNavWaypointKind?>(waypoints.Count);
for (int i = 0; i < waypoints.Count; i++)
{
NodeKey w = waypoints[i];
Floor f = FloorByLabel(w.Floor);
if (f == null) continue;
// Stair seam: the previous waypoint is on a different floor and this directed
// landing pair has a baked ramp polyline — insert its interior points so the
// follower walks the diagonal run (real XZ progression + true Y) instead of a
// single stacked landing-to-landing jump it can't steer along.
bool isStairLanding = false;
if (i > 0 && _stairRampInteriors != null)
{
NodeKey prev = waypoints[i - 1];
if (prev.Floor != w.Floor &&
_stairRampInteriors.TryGetValue((prev, w), out Vector3[] interior))
{
// The DEPARTURE landing is the waypoint we just emitted (prev, last in the
// list); the ARRIVAL landing is this one (w). Tag both ends of the crossing.
if (rawWaypointKinds.Count > 0)
rawWaypointKinds[rawWaypointKinds.Count - 1] = SimpleNavWaypointKind.Stairs;
isStairLanding = true;
for (int k = 0; k < interior.Length; k++)
{
rawRouteWaypoints.Add(interior[k]);
rawWaypointKinds.Add(null); // interior ramp point, not a landmark
expandedSegmentDoors.Add(new List<string>(0)); // seam sub-segment, no door
}
}
}
Vector2 xz = f.CellToWorld(w.Ix, w.Iz);
rawRouteWaypoints.Add(new Vector3(xz.x, f.FloorY, xz.y));
rawWaypointKinds.Add(isStairLanding ? (SimpleNavWaypointKind?)SimpleNavWaypointKind.Stairs : null);
// Door list for the segment LEAVING this cell-waypoint (i -> i+1), appended
// only for non-terminal waypoints to keep one entry per emitted segment.
if (i < waypoints.Count - 1)
{
List<string> seg = i < segmentDoorNames.Count ? segmentDoorNames[i] : null;
expandedSegmentDoors.Add(seg ?? new List<string>(0));
}
}
AddRouteWaypoints(rawRouteWaypoints, expandedSegmentDoors, rawWaypointKinds, route);
route.EnsureSemanticWaypoints();
while (route.SegmentDoorNames.Count < route.Waypoints.Count - 1)
route.SegmentDoorNames.Add(new List<string>(0));
if (Main.Log != null)
{
int doorSegs = 0;
for (int i = 0; i < route.SegmentDoorNames.Count; i++)
if (route.SegmentDoorNames[i].Count > 0) doorSegs++;
Main.Log.LogInfo("SimpleNavPlanner.Plan ok target=" + (targetName ?? "<null>") +
" waypoints=" + route.Waypoints.Count +
" segmentsWithDoor=" + doorSegs +
" cost_m=" + totalCost.ToString("F2") + " planMs=" + planWatch.ElapsedMilliseconds +
" eyeY=" + EyeYOnFloor(goalFloor).ToString("F2") + " camAboveFeet=" + CameraAboveFeetM().ToString("F2"));
// Diagnostic: log every waypoint XYZ so we can compare against the bake PPM
// when the executor reports a wall-clipping route failure.
for (int i = 0; i < route.Waypoints.Count; i++)
{
Vector3 w = route.Waypoints[i];
SimpleNavWaypoint semantic = i < route.SemanticWaypoints.Count ? route.SemanticWaypoints[i] : null;
Main.Log.LogInfo(" wp[" + i + "]=(" + w.x.ToString("F2") + ", " + w.y.ToString("F2") + ", " + w.z.ToString("F2") + ")");
if (semantic != null && semantic.Kind != SimpleNavWaypointKind.Navigation)
{
Main.Log.LogInfo(" semantic kind=" + semantic.Kind +
" door=" + (string.IsNullOrEmpty(semantic.DoorName) ? "<none>" : semantic.DoorName));
}
}
}
return route;
}
/// <summary>Returns true if the bake is loaded and the planner is ready.</summary>
public static bool IsReady => EnsureLoaded();
/// <summary>
/// The player's body radius (m) from the live game: the CapsuleCollider radius times its larger
/// horizontal lossy scale (0.4 local x 2 = 0.8 m). Falls back to the bake's radius while there
/// is no player.
/// </summary>
public static float PlayerBodyRadiusM
{
get
{
BetterPlayerControl bpc = BetterPlayerControl.Instance;
CapsuleCollider cc = bpc != null ? bpc.GetComponent<CapsuleCollider>() : null;
if (cc != null)
{
Vector3 ls = cc.transform.lossyScale;
return cc.radius * Mathf.Max(Mathf.Abs(ls.x), Mathf.Abs(ls.z));
}
return BakeRadiusLoaded;
}
}
// The loaded bake's body radius, read without EnsureLoaded (these run during loading too).
private static float BakeRadiusLoaded =>
_bake != null && _bake.@params != null ? _bake.@params.capsule_radius_m : -1f;
// Whole bake cells needed to cover `metres` (0 before the bake's grid is known).
private static int CellsForM(float metres)
{
if (_cellSize <= 0f) return 0;
return Mathf.Max(0, Mathf.CeilToInt(metres / _cellSize - 1e-3f));
}
/// <summary>The body radius (m) the loaded bake dilated its blockers by, or -1 when no bake is loaded.</summary>
public static float BakeCapsuleRadiusM => EnsureLoaded() ? BakeRadiusLoaded : -1f;
// True for doors the bake records as operability-only CONTAINER doors (cupboards, fridge,
// cabinets) rather than passage doors.
public static bool IsContainerDoorName(string name)
{
return !string.IsNullOrEmpty(name) && EnsureLoaded() && _containerDoorNames.Contains(name);
}
// Resolve the floor a player STANDING at world Y belongs to (start-floor rule), as a
// stable string label (e.g. "ground"/"upper"). Used by the object picker to bucket
// candidates by floor before sorting by XZ distance, so cross-floor items don't read
// as "near" the way a flat XZ distance makes them. Returns false when the bake isn't
// loaded or Y matches no floor within tolerance.
public static bool TryGetPlayerFloorLabel(float worldY, out string floorLabel)
{
floorLabel = null;
if (!EnsureLoaded() || _floors == null)
return false;
Floor floor = FloorForY(worldY, StartFloorMatchToleranceM);
floorLabel = floor?.Label;
return floorLabel != null;
}
// Resolve the floor a player would STAND ON to interact with a TARGET at world Y, using
// the same FloorForTargetY rule the planner uses to choose where autowalk arrives (so a
// wall-mounted/tabletop/ceiling item resolves to the floor below it, matching where the
// route actually ends). Returns false only when the bake isn't loaded.
public static bool TryGetTargetFloorLabel(float worldY, out string floorLabel)
{
floorLabel = null;
if (!EnsureLoaded() || _floors == null)
return false;
Floor floor = FloorForTargetY(worldY);
floorLabel = floor?.Label;
return floorLabel != null;
}
// The bake's canonical fixture roster — the master list of valid interactable targets
// (filtered/deduped/merged/located by the bake). The picker enumerates this instead of
// FindObjectsOfType so set construction has a single source of truth. Returns an empty
// array when the bake didn't load or predates the roster (the caller treats that as
// "no objects" — there is no live-enumeration fallback by design).
public static IReadOnlyList<Fixture> GetFixtureRoster()
{
if (!EnsureLoaded() || _bake == null || _bake.fixtures == null)
return System.Array.Empty<Fixture>();
return _bake.fixtures;
}
/// <summary>
/// The grid frame of a baked floor ("ground", "upper"), for tools that map world positions
/// onto the bake's cells (the coverage sweep's coverage bitmaps).
/// </summary>
public static bool TryGetFloorFrame(string label, out float originX, out float originZ,
out float cellSize, out int nx, out int nz, out float floorY)
{
originX = originZ = cellSize = floorY = 0f;
nx = nz = 0;
Floor f = EnsureLoaded() ? FloorByLabel(label) : null;
if (f == null) return false;
originX = f.OriginX; originZ = f.OriginZ; cellSize = f.CellSize;
nx = f.Nx; nz = f.Nz; floorY = f.FloorY;
return true;
}
// Classify the navmesh state at a WORLD position, for the coverage sweep's stall triage.
// The "footprint" blocker mode lumps three unrelated stalls together (the blocker label is
// just the nearest collider — unreliable for big-AABB meshes and floor edges). This reads
// the player's ACTUAL stuck cell's navmesh state instead. Returns one of:
// "dead_pocket" — the cell is NOT navigable and has <=2 navigable neighbours: the
// follower left the navmesh into a near-sealed cell (off-path, not a graze).
// "open_space" — clearance is at the cap (wide open): stalled in open space, NOT grazing
// anything (a mislabeled/residual stall).
// "edge_graze" — navigable but clearance<=1 (hugging a wall/jamb): the real graze class.
// "on_mesh" — navigable with comfortable clearance (a stall with no navmesh cause here).
// "unknown" — floor unresolved.
// See [[project-navigation-footprint-stalls-decomposed-2026-06-16]].
public static string ClassifyStallCell(string floorLabel, float wx, float wz)
{
if (!EnsureLoaded()) return "unknown";
Floor f = FloorByLabel(floorLabel);
if (f == null) return "unknown";
f.WorldToCell(wx, wz, out int ix, out int iz);
if (!f.InBounds(ix, iz)) return "unknown";
bool selfNav = f.Navigable(ix, iz);
int navNeighbours = 0;
for (int dx = -1; dx <= 1; dx++)
for (int dz = -1; dz <= 1; dz++)
{
if (dx == 0 && dz == 0) continue;
if (f.Navigable(ix + dx, iz + dz)) navNeighbours++;
}
if (!selfNav)
return navNeighbours <= 2 ? "dead_pocket" : "off_mesh_open";
int clearance = f.Clearance(ix, iz);
if (clearance >= ClearanceTargetCells) return "open_space";
if (clearance <= 1) return "edge_graze";
return "on_mesh";
}
// Pick a CLEAN stand-cell near a world point: the navigable cell within radiusM whose
// clearance (cells-to-nearest-wall, the same metric A* uses) is highest, tie-broken by
// closeness to the anchor. Used by the coverage sweep to teleport the player without
// spawning hard against a collider/door (which stalls the leg instantly). Picking the
// HIGHEST-clearance cell already lands the player as far off walls as the 0.8m clearance
// cap allows — that is the anti-wedge guard. `minClearanceCells` additionally REQUIRES the
// chosen cell to be at least that far off any wall (so the relocation teleport can refuse a
// too-tight spot rather than drop the player somewhere a downstream leg would fail from for
// a bad-teleport reason); pass 0 to accept the best available. Floor is chosen by
// FloorForTargetY. Returns false if no qualifying navigable cell is in range.
public static bool TryGetCleanStandCell(float anchorX, float anchorY, float anchorZ,
float radiusM, out Vector3 cleanWorld,
int minClearanceCells = 0)
{
cleanWorld = Vector3.zero;
if (!EnsureLoaded() || _floors == null) return false;
Floor floor = FloorForTargetY(anchorY);
if (floor == null) return false;
int cx, cz;
floor.WorldToCell(anchorX, anchorZ, out cx, out cz);
int r = Mathf.Max(1, Mathf.CeilToInt(radiusM / floor.CellSize));
float r2 = radiusM * radiusM;
int bestClear = -1;
float bestDist2 = float.PositiveInfinity;
bool found = false;
int bIx = 0, bIz = 0;
for (int dx = -r; dx <= r; dx++)
{
for (int dz = -r; dz <= r; dz++)
{
int ix = cx + dx, iz = cz + dz;
if (!floor.Navigable(ix, iz)) continue;
int clear = floor.Clearance(ix, iz);
if (clear < minClearanceCells) continue;
Vector2 w = floor.CellToWorld(ix, iz);
float ddx = w.x - anchorX, ddz = w.y - anchorZ;
float d2 = ddx * ddx + ddz * ddz;
if (d2 > r2) continue;
if (clear > bestClear || (clear == bestClear && d2 < bestDist2))
{
bestClear = clear; bestDist2 = d2; bIx = ix; bIz = iz; found = true;
}
}
}
if (!found) return false;
Vector2 bw = floor.CellToWorld(bIx, bIz);
cleanWorld = new Vector3(bw.x, floor.FloorY, bw.y);
return true;
}
// ---- bake load ----
private static bool EnsureLoaded()
{
if (_loadAttempted) return _loadOk;
_loadAttempted = true;
string path = Path.Combine(Paths.PluginPath, BakeFileName);
if (!File.Exists(path))
{
if (Main.Log != null) Main.Log.LogWarning("SimpleNavPlanner: bake file missing at " + path);
return false;
}
try
{
using (var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(File.ReadAllText(path))))
{