feat(pathfinding): controlled native NPC waypoint navigation and safety limits (#120)

* feat(pathfinding): add bounded deterministic NPC waypoint cursor and stall detection

* feat(pathfinding): expose permission-checked internal NPC route interface

* feat(pathfinding): add opt-in owner-authorized NPC waypoint motor using native OpenSim NPC physics

* test(pathfinding): cover NPC waypoints, progress timing, limits and validation

* test(pathfinding): cover NPC waypoints, progress timing, limits and validation

* test(pathfinding): guard NPC owner/physics, bounded scheduler and no fake LSL stubs

* docs(config): add separately disabled NPC navigation with quotas and scene tick limits

* ci(pathfinding): add actual NPC motor ownership and waypoint regression checks

* docs(release): track real NPC motor as experimental but do not claim complete pathfinding

* fix(pathfinding): forbid zero-UUID NPC caller that bypasses underlying OpenSim owner policy

* test(pathfinding): prevent UID-zero bypass in NPC ownership authorization
This commit is contained in:
OpenGenesis (MPL 2.0) authored and GitHub committed 2026-10-09 19:57:25 +02:00
1 parent ee8ee5ab23
commit ac6a165563
9 files changed
+518

No files matched your search

+8
View File
@@ -314,6 +314,14 @@ jobs:
shell: bash
run: dotnet run --configuration Release --project tools/ci/OglTerrainNavigationRegression/OglTerrainNavigationRegression.csproj
- name: Verify native owner-checked NPC path-following module
shell: bash
run: python3 tools/ci/verify_ogl_npc_navigation.py
- name: Regression-test OGL NPC waypoint controller
shell: bash
run: dotnet run --configuration Release --project tools/ci/OglNpcNavigationRegression/OglNpcNavigationRegression.csproj
- name: Verify OGLVoice secure provider discovery integration
shell: bash
run: python3 tools/ci/verify_oglvoice_discovery.py
@@ -0,0 +1,72 @@
// SPDX-License-Identifier: MPL-2.0
using System;
using System.Collections.Generic;
namespace NexVerse.Core.Pathfinding
{
/// <summary>
/// A bounded waypoint cursor for experimental real NPC path following.
/// Does not move scene entities or bypass the physics subsystem.
/// </summary>
public sealed class OglNpcWaypointCursor
{
private readonly OglNavigationPoint[] m_Points;
private int m_Index;
private DateTimeOffset m_LastAdvance;
public OglNpcWaypointCursor(IReadOnlyList<OglNavigationPoint> points,
DateTimeOffset createdAt, int maximumPoints = 256)
{
if (points == null || points.Count == 0 ||
points.Count > maximumPoints || maximumPoints < 1 || maximumPoints > 1024)
throw new ArgumentException("Invalid or unbounded NPC navigation route", nameof(points));
m_Points = new OglNavigationPoint[points.Count];
for (int i = 0; i < points.Count; ++i)
{
OglNavigationPoint p = points[i];
if (!float.IsFinite(p.X) || !float.IsFinite(p.Y) || !float.IsFinite(p.Z))
throw new ArgumentException("Nonfinite waypoint", nameof(points));
m_Points[i] = p;
}
m_LastAdvance = createdAt;
}
public bool Completed => m_Index >= m_Points.Length;
public int Remaining => Math.Max(0, m_Points.Length - m_Index);
public OglNavigationPoint Current
{
get
{
if (Completed)
throw new InvalidOperationException("NPC route already complete");
return m_Points[m_Index];
}
}
public bool UpdatePosition(float x, float y, float reachRadius,
DateTimeOffset now)
{
if (!float.IsFinite(x) || !float.IsFinite(y) ||
!float.IsFinite(reachRadius) || reachRadius < 0.5f ||
reachRadius > 8f)
return false;
float reachSquared = reachRadius * reachRadius;
bool progressed = false;
while (!Completed)
{
OglNavigationPoint point = m_Points[m_Index];
float dx = point.X - x, dy = point.Y - y;
if (dx * dx + dy * dy > reachSquared)
break;
m_Index++;
m_LastAdvance = now;
progressed = true;
}
return progressed;
}
public bool Stalled(DateTimeOffset now, TimeSpan maximumWaypointWait) =>
!Completed && maximumWaypointWait > TimeSpan.Zero &&
now - m_LastAdvance > maximumWaypointWait;
}
}
@@ -0,0 +1,17 @@
// SPDX-License-Identifier: MPL-2.0
using OpenMetaverse;
namespace NexVerse.RegionModules.Pathfinding
{
/// <summary>
/// Internal trusted-region NPC navigation API. Does not register any new
/// LSL/OSSL methods or expose a public admin HTTP endpoint.
/// </summary>
public interface IOglNpcRouteService
{
bool TryNavigate(UUID npcId, UUID callerId, Vector3 destination,
out string reason);
bool Stop(UUID npcId, UUID callerId);
int ActiveRouteCount { get; }
}
}
@@ -0,0 +1,311 @@
// SPDX-License-Identifier: MPL-2.0
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using log4net;
using Mono.Addins;
using NexVerse.Core.Pathfinding;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace NexVerse.RegionModules.Pathfinding
{
/// <summary>
/// Opt-in NPC waypoint follower using the EXISTING OpenSimulator NPC
/// motor/physics. No LSL parity claim or unsafe direct position changes.
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule",
Id = "OglNpcPathFollowerModule")]
public sealed class OglNpcPathFollowerModule : ISharedRegionModule
{
private sealed class Job
{
public readonly UUID Caller;
public readonly OglNpcWaypointCursor Cursor;
public Job(UUID caller, OglNpcWaypointCursor cursor)
{
Caller = caller;
Cursor = cursor;
}
}
private sealed class RegionRoutes : IOglNpcRouteService
{
public readonly Scene Scene;
private readonly object m_Sync = new();
private readonly Dictionary<UUID, Job> m_Jobs = new();
private readonly int m_MaxActive;
private readonly int m_MaxWaypoints;
private readonly TimeSpan m_WaypointTimeout;
public bool Disposed;
public RegionRoutes(Scene scene, int maxActive, int maxWaypoints,
TimeSpan waypointTimeout)
{
Scene = scene;
m_MaxActive = maxActive;
m_MaxWaypoints = maxWaypoints;
m_WaypointTimeout = waypointTimeout;
}
public int ActiveRouteCount
{
get { lock (m_Sync) return m_Jobs.Count; }
}
public bool TryNavigate(UUID npcId, UUID callerId, Vector3 destination,
out string reason)
{
reason = "navigation_unavailable";
if (Disposed || npcId.IsZero() || callerId.IsZero() || !float.IsFinite(destination.X) ||
!float.IsFinite(destination.Y) || !float.IsFinite(destination.Z))
return false;
INPCModule npc = Scene.RequestModuleInterface<INPCModule>();
IOglTerrainNavigationRegion nav =
Scene.RequestModuleInterface<IOglTerrainNavigationRegion>();
if (npc == null || nav?.IsNavigationReady != true ||
!npc.IsNPC(npcId, Scene) ||
!npc.CheckPermissions(npcId, callerId) ||
!Scene.TryGetScenePresence(npcId, out ScenePresence sp) ||
sp == null || sp.IsDeleted || !sp.IsNPC)
{
reason = "npc_permission_or_navigation_missing";
return false;
}
if (!nav.TryFindTerrainPath(sp.AbsolutePosition.X,
sp.AbsolutePosition.Y, destination.X, destination.Y,
out IReadOnlyList<OglNavigationPoint> points))
{
reason = "route_not_found";
return false;
}
OglNpcWaypointCursor cursor;
try
{
cursor = new OglNpcWaypointCursor(points,
DateTimeOffset.UtcNow, m_MaxWaypoints);
}
catch (ArgumentException)
{
reason = "route_too_long_or_invalid";
return false;
}
lock (m_Sync)
{
if (Disposed || !nav.IsNavigationReady)
{
reason = "navigation_invalidated";
return false;
}
if (!m_Jobs.ContainsKey(npcId) && m_Jobs.Count >= m_MaxActive)
{
reason = "npc_route_quota";
return false;
}
cursor.UpdatePosition(sp.AbsolutePosition.X,
sp.AbsolutePosition.Y, 2.0f, DateTimeOffset.UtcNow);
if (!cursor.Completed)
{
OglNavigationPoint p = cursor.Current;
if (!npc.MoveToTarget(npcId, Scene,
new Vector3(p.X, p.Y, p.Z + 1.0f),
true, true, false))
{
reason = "npc_move_rejected";
return false;
}
m_Jobs[npcId] = new Job(callerId, cursor);
}
else
{
npc.StopMoveToTarget(npcId, Scene);
m_Jobs.Remove(npcId);
}
}
reason = "accepted";
return true;
}
public bool Stop(UUID npcId, UUID callerId)
{
INPCModule npc = Scene.RequestModuleInterface<INPCModule>();
if (callerId.IsZero() || npc == null || !npc.CheckPermissions(npcId, callerId))
return false;
lock (m_Sync)
{
if (!m_Jobs.Remove(npcId))
return false;
npc.StopMoveToTarget(npcId, Scene);
return true;
}
}
public void Tick()
{
lock (m_Sync)
{
if (Disposed || m_Jobs.Count == 0)
return;
INPCModule npc = Scene.RequestModuleInterface<INPCModule>();
IOglTerrainNavigationRegion nav =
Scene.RequestModuleInterface<IOglTerrainNavigationRegion>();
List<UUID> removed = new();
foreach (KeyValuePair<UUID, Job> pair in m_Jobs)
{
UUID id = pair.Key;
Job job = pair.Value;
if (npc == null || !npc.IsNPC(id, Scene) ||
!npc.CheckPermissions(id, job.Caller) ||
!Scene.TryGetScenePresence(id, out ScenePresence sp) ||
sp == null || sp.IsDeleted ||
nav?.IsNavigationReady != true ||
job.Cursor.Stalled(DateTimeOffset.UtcNow, m_WaypointTimeout))
{
if (npc != null && npc.IsNPC(id, Scene))
npc.StopMoveToTarget(id, Scene);
removed.Add(id);
continue;
}
if (!job.Cursor.UpdatePosition(sp.AbsolutePosition.X,
sp.AbsolutePosition.Y, 2.0f, DateTimeOffset.UtcNow))
continue;
if (job.Cursor.Completed)
{
npc.StopMoveToTarget(id, Scene);
removed.Add(id);
}
else
{
OglNavigationPoint next = job.Cursor.Current;
if (!npc.MoveToTarget(id, Scene,
new Vector3(next.X, next.Y, next.Z + 1.0f),
true, true, false))
{
npc.StopMoveToTarget(id, Scene);
removed.Add(id);
}
}
}
foreach (UUID id in removed)
m_Jobs.Remove(id);
}
}
public void Dispose()
{
lock (m_Sync)
{
Disposed = true;
INPCModule npc = Scene.RequestModuleInterface<INPCModule>();
foreach (UUID id in m_Jobs.Keys)
if (npc != null && npc.IsNPC(id, Scene))
npc.StopMoveToTarget(id, Scene);
m_Jobs.Clear();
}
}
}
private static readonly ILog m_Log =
LogManager.GetLogger(typeof(OglNpcPathFollowerModule));
private readonly ConcurrentDictionary<UUID, RegionRoutes> m_Regions = new();
private bool m_Enabled;
private int m_MaxActive = 32;
private int m_MaxWaypoints = 256;
private int m_TickMs = 1000;
private int m_WaypointWaitSeconds = 45;
private int m_Ticking;
private int m_Closed;
private Timer m_Timer;
public string Name => "OGL NPC Path Follower (experimental)";
public Type ReplaceableInterface => null;
public void Initialise(IConfigSource config)
{
IConfig settings = config.Configs["OGLNpcNavigation"];
m_Enabled = settings?.GetBoolean("Enabled", false) ?? false;
if (!m_Enabled) return;
m_MaxActive = Math.Clamp(settings.GetInt("MaxActivePerRegion", 32), 1, 64);
m_MaxWaypoints = Math.Clamp(settings.GetInt("MaxWaypoints", 256), 8, 256);
m_TickMs = Math.Clamp(settings.GetInt("TickMilliseconds", 1000), 250, 5000);
m_WaypointWaitSeconds = Math.Clamp(settings.GetInt("WaypointTimeoutSeconds", 45),
10, 120);
}
public void AddRegion(Scene scene)
{
if (!m_Enabled || scene == null) return;
RegionRoutes routes = new(scene, m_MaxActive, m_MaxWaypoints,
TimeSpan.FromSeconds(m_WaypointWaitSeconds));
if (m_Regions.TryAdd(scene.RegionInfo.RegionID, routes))
scene.RegisterModuleInterface<IOglNpcRouteService>(routes);
}
public void RegionLoaded(Scene scene) { }
public void PostInitialise()
{
if (!m_Enabled) return;
m_Timer = new Timer(_ => TickAll(), null,
TimeSpan.FromMilliseconds(m_TickMs),
TimeSpan.FromMilliseconds(m_TickMs));
}
private void TickAll()
{
if (Volatile.Read(ref m_Closed) != 0 ||
Interlocked.Exchange(ref m_Ticking, 1) != 0)
return;
try
{
foreach (RegionRoutes route in m_Regions.Values)
{
try { route.Tick(); }
catch (Exception e)
{
m_Log.Error("[OGL-PATH]: NPC route scheduler failure.", e);
}
}
}
finally
{
Interlocked.Exchange(ref m_Ticking, 0);
}
}
public void RemoveRegion(Scene scene)
{
if (scene != null &&
m_Regions.TryRemove(scene.RegionInfo.RegionID, out RegionRoutes routes))
{
scene.UnregisterModuleInterface<IOglNpcRouteService>(routes);
routes.Dispose();
}
}
public void Close()
{
Interlocked.Exchange(ref m_Closed, 1);
m_Timer?.Dispose();
foreach (RegionRoutes routes in m_Regions.Values)
{
routes.Scene.UnregisterModuleInterface<IOglNpcRouteService>(routes);
routes.Dispose();
}
m_Regions.Clear();
}
}
}
+10
View File
@@ -1203,6 +1203,16 @@
; ScriptEnginesPath = "ScriptEngines"
[OGLNpcNavigation]
; Experimenteller NPC-Wegpunkt-Follower ueber INPCModule/Physik.
; Funktioniert nur zusammen mit aktiviertem OGLPathfinding (Terrain).
; KEINE vollstaendige SL Pathfinding LSL-API, standardmaessig AUS.
Enabled = false
MaxActivePerRegion = 32
MaxWaypoints = 256
TickMilliseconds = 1000
WaypointTimeoutSeconds = 45
[OGLPathfinding]
; Experimenteller Terrain-Snapshot fuer OpenGenesisLINK 0.9.3.10 Dev.
; Kein komplettes NavMesh, keine Kollisions-Meshes und noch keine LSL-NPC-Steuerung.
+2
View File
@@ -55,6 +55,8 @@ Details: [OGLVOICE_ARCHITECTURE.md](OGLVOICE_ARCHITECTURE.md).
- [ ] Linksets, Treppen, Türen, Off-mesh-Links und path-cost areas; keine physikalisch ungültigen Abkürzungen.
- [ ] Agent-spezifische Navigation: Radius, Höhe, Steigung, erlaubte Bereiche und dynamische Kollisionen.
- [ ] NPC-/Character-Komponenten und kontrollierte Bewegungssteuerung mit Tick-/CPU-Budgets.
- [x] **Interner, experimenteller NPC-Wegpunkt-Follower:** `OglNpcPathFollowerModule` nutzt das bestehende `INPCModule.MoveToTarget`/Physik statt Teleports; prueft NPC-Eigentuemerrechte, aktive Region-Navigation, CPU-/Routenlimits, Fortschritt/Timeout und Stop bei Terraforming. Opt-in `[OGLNpcNavigation] Enabled=false`. **Noch kein LSL-Binding, kein echter Live-Test, keine Mesh-Hindernis-/NavMesh-Paritaet.**
- [ ] LSL-API-`llCreateCharacter`, `llDeleteCharacter`, `llNavigateTo`, `llPursue`, `llFleeFrom`, `llWanderWithin`, `llPatrolPoints`, `llGetClosestNavPoint` und `path_update` gemäß geprüfter aktueller SL-Signaturen; keine Stubs als erledigt zählen.
- [ ] Region-/Parzellenrechte, Script-Quota, Missbrauchsschutz und Lastgrenzen.
- [ ] Deterministischer CI-Regressionssatz und laufende Region mit tatsächlich bewegtem NPC und Live-Viewer-Abnahme.
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<Nullable>disable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Compile Include="../../../NexVerse/Core/Pathfinding/OglGridPathfinder.cs" Link="OglGridPathfinder.cs" />
<Compile Include="../../../NexVerse/Core/Pathfinding/OglTerrainNavigationSnapshot.cs" Link="OglTerrainNavigationSnapshot.cs" />
<Compile Include="../../../NexVerse/Core/Pathfinding/OglNpcWaypointCursor.cs" Link="OglNpcWaypointCursor.cs" />
</ItemGroup>
</Project>
@@ -0,0 +1,63 @@
using System;
using System.Linq;
using NexVerse.Core.Pathfinding;
static void Check(bool ok, string message)
{
if (!ok) throw new InvalidOperationException("OGL NPC navigation: " + message);
}
DateTimeOffset now = DateTimeOffset.FromUnixTimeSeconds(1791568800);
OglNpcWaypointCursor cursor = new(new[] {
new OglNavigationPoint(2, 2, 20),
new OglNavigationPoint(6, 2, 20),
new OglNavigationPoint(10, 2, 20)
}, now);
Check(cursor.Remaining == 3 && !cursor.Completed, "initial cursor");
Check(!cursor.UpdatePosition(0, 0, 1.5f, now), "not reached first waypoint");
Check(cursor.UpdatePosition(2, 2, 1.5f, now.AddSeconds(1)),
"reaches first waypoint");
Check(cursor.Remaining == 2 && cursor.Current.X == 6, "next target");
Check(!cursor.Stalled(now.AddSeconds(20), TimeSpan.FromSeconds(30)),
"no premature timeout");
Check(cursor.Stalled(now.AddSeconds(35), TimeSpan.FromSeconds(30)),
"stuck NPC requires route cancellation");
Check(!cursor.UpdatePosition(float.NaN, 0, 1, now), "reject nonfinite position");
Check(!cursor.UpdatePosition(6, 2, 0.1f, now), "reject unreasonable waypoint radius");
Check(cursor.UpdatePosition(6, 2, 1.5f, now.AddSeconds(36)),
"progress resets timeout");
Check(!cursor.Stalled(now.AddSeconds(55), TimeSpan.FromSeconds(30)),
"timeout resets on progress");
Check(cursor.UpdatePosition(10, 2, 1.5f, now.AddSeconds(56)), "final waypoint");
Check(cursor.Completed && cursor.Remaining == 0, "route completion");
try
{
_ = cursor.Current;
throw new Exception("complete cursor unexpectedly had a waypoint");
}
catch (InvalidOperationException) { }
try
{
_ = new OglNpcWaypointCursor(Array.Empty<OglNavigationPoint>(), now);
throw new Exception("empty waypoint route accepted");
}
catch (ArgumentException) { }
try
{
_ = new OglNpcWaypointCursor(Enumerable.Range(0, 257)
.Select(x => new OglNavigationPoint(x, 0, 0)).ToArray(), now);
throw new Exception("oversized waypoint route accepted");
}
catch (ArgumentException) { }
try
{
_ = new OglNpcWaypointCursor(new[] {
new OglNavigationPoint(float.PositiveInfinity, 0, 0) }, now);
throw new Exception("nonfinite waypoint accepted");
}
catch (ArgumentException) { }
Console.WriteLine("OGL NPC waypoint follower: bounds, sequencing, finish and stall timeout OK");
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env python3
"""Bounded NPC navigation must use native NPC physics and enforce ownership."""
from pathlib import Path
r = Path(__file__).resolve().parents[2]
module = (r/"NexVerse/RegionModules/Pathfinding/OglNpcPathFollowerModule.cs").read_text()
cursor = (r/"NexVerse/Core/Pathfinding/OglNpcWaypointCursor.cs").read_text()
contract = (r/"NexVerse/RegionModules/Pathfinding/IOglNpcRouteService.cs").read_text()
config = (r/"bin/OpenSim.ini.example").read_text()
for item in ("INPCModule", "CheckPermissions(npcId, callerId)",
"IsNPC", "MoveToTarget(", "StopMoveToTarget(",
"IOglTerrainNavigationRegion", "IsNavigationReady",
"m_MaxActive", "m_MaxWaypoints", "m_WaypointTimeout",
"m_Timer", "Interlocked.Exchange(ref m_Ticking",
"UnregisterModuleInterface<IOglNpcRouteService>"):
assert item in module, item
assert module.count("callerId.IsZero()") >= 2, "reject NPC superuser bypass"
assert "TryNavigate(" in contract
assert "Stalled(" in cursor and "maximumPoints" in cursor
assert "[OGLNpcNavigation]" in config and "Enabled = false" in config
assert "sp.AbsolutePosition =" not in module
assert "llNavigateTo" not in module
print("OGL owner-checked native NPC waypoint motor integration: OK")