forked from stride3d/stride
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDynamicNavigationMeshSystem.cs
More file actions
283 lines (240 loc) · 9.91 KB
/
DynamicNavigationMeshSystem.cs
File metadata and controls
283 lines (240 loc) · 9.91 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
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
#pragma warning disable SA1402 // File may only contain a single type
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Stride.Core;
using Stride.Core.Mathematics;
using Stride.Core.Reflection;
using Stride.Engine;
using Stride.Engine.Design;
using Stride.Engine.Processors;
using Stride.Games;
using Stride.Navigation.Processors;
using Stride.Physics;
namespace Stride.Navigation
{
/// <summary>
/// System that handles building of navigation meshes at runtime
/// </summary>
public class DynamicNavigationMeshSystem : GameSystem
{
/// <summary>
/// If <c>true</c>, this will automatically rebuild on addition/removal of static collider components
/// </summary>
[DataMember(5)]
public bool AutomaticRebuild { get; set; } = true;
/// <summary>
/// Collision filter that indicates which colliders are used in navmesh generation
/// </summary>
[DataMember(10)]
public CollisionFilterGroupFlags IncludedCollisionGroups { get; set; }
/// <summary>
/// Build settings used by Recast
/// </summary>
[DataMember(20)]
public NavigationMeshBuildSettings BuildSettings { get; set; }
/// <summary>
/// Settings for agents used with the dynamic navigation mesh
/// </summary>
[DataMember(30)]
public List<NavigationMeshGroup> Groups { get; private set; } = [];
private bool pendingRebuild = true;
private SceneInstance currentSceneInstance;
private NavigationMeshBuilder builder = new();
private CancellationTokenSource buildTaskCancellationTokenSource;
private SceneSystem sceneSystem;
private ScriptSystem scriptSystem;
private StaticColliderProcessor processor;
public DynamicNavigationMeshSystem(IServiceRegistry registry) : base(registry)
{
Enabled = false;
EnabledChanged += OnEnabledChanged;
}
/// <summary>
/// Raised when the navigation mesh for the current scene is updated
/// </summary>
public event EventHandler<NavigationMeshUpdatedEventArgs> NavigationMeshUpdated;
/// <summary>
/// The most recently built navigation mesh
/// </summary>
public NavigationMesh CurrentNavigationMesh { get; private set; }
/// <inheritdoc />
public override void Initialize()
{
base.Initialize();
var gameSettings = Services.GetService<IGameSettingsService>()?.Settings;
if (gameSettings != null)
{
InitializeSettingsFromGameSettings(gameSettings);
}
else
{
// Initial build settings
BuildSettings = ObjectFactoryRegistry.NewInstance<NavigationMeshBuildSettings>();
IncludedCollisionGroups = CollisionFilterGroupFlags.AllFilter;
Groups = new List<NavigationMeshGroup>
{
ObjectFactoryRegistry.NewInstance<NavigationMeshGroup>(),
};
}
sceneSystem = Services.GetSafeServiceAs<SceneSystem>();
scriptSystem = Services.GetSafeServiceAs<ScriptSystem>();
}
/// <summary>
/// Copies the default settings from the <see cref="GameSettings"/> for building navigation
/// </summary>
public void InitializeSettingsFromGameSettings(GameSettings gameSettings)
{
if (gameSettings == null)
throw new ArgumentNullException(nameof(gameSettings));
// Initialize build settings from game settings
var navigationSettings = gameSettings.Configurations.Get<NavigationSettings>();
InitializeSettingsFromNavigationSettings(navigationSettings);
}
/// <inheritdoc />
public override void Update(GameTime gameTime)
{
// This system should load from settings before becoming functional
if (!Enabled)
return;
if (currentSceneInstance != sceneSystem?.SceneInstance)
{
// ReSharper disable once PossibleNullReferenceException
UpdateScene(sceneSystem.SceneInstance);
}
if (pendingRebuild && currentSceneInstance != null)
{
scriptSystem.AddTask(async () =>
{
// TODO EntityProcessors
// Currently have to wait a frame for transformations to update
// for example when calling Rebuild from the event that a component was added to the scene, this component will not be in the correct location yet
// since the TransformProcessor runs the next frame
await scriptSystem.NextFrame();
await Rebuild();
});
pendingRebuild = false;
}
}
/// <summary>
/// Starts an asynchronous rebuild of the navigation mesh
/// </summary>
public async Task<NavigationMeshBuildResult> Rebuild()
{
if (currentSceneInstance == null)
return new NavigationMeshBuildResult();
// Cancel running build, TODO check if the running build can actual satisfy the current rebuild request and don't cancel in that case
buildTaskCancellationTokenSource?.Cancel();
buildTaskCancellationTokenSource = new CancellationTokenSource();
// Collect bounding boxes
var boundingBoxProcessor = currentSceneInstance.GetProcessor<BoundingBoxProcessor>();
if (boundingBoxProcessor == null)
return new NavigationMeshBuildResult();
List<BoundingBox> boundingBoxes = [];
foreach (var boundingBox in boundingBoxProcessor.BoundingBoxes)
{
boundingBox.Entity.Transform.WorldMatrix.Decompose(out var scale, out Quaternion _, out var translation);
boundingBoxes.Add(new BoundingBox(translation - boundingBox.Size * scale, translation + boundingBox.Size * scale));
}
var result = Task.Run(() =>
{
// Only have one active build at a time
lock (builder)
{
return builder.Build(BuildSettings, Groups, IncludedCollisionGroups, boundingBoxes, buildTaskCancellationTokenSource.Token);
}
});
await result;
FinalizeRebuild(result);
return result.Result;
}
internal void InitializeSettingsFromNavigationSettings(NavigationSettings navigationSettings)
{
BuildSettings = navigationSettings.BuildSettings;
IncludedCollisionGroups = navigationSettings.IncludedCollisionGroups;
Groups = navigationSettings.Groups;
Enabled = navigationSettings.EnableDynamicNavigationMesh;
pendingRebuild = true;
}
private void FinalizeRebuild(Task<NavigationMeshBuildResult> resultTask)
{
var result = resultTask.Result;
if (result.Success)
{
var args = new NavigationMeshUpdatedEventArgs
{
OldNavigationMesh = CurrentNavigationMesh,
BuildResult = result,
};
CurrentNavigationMesh = result.NavigationMesh;
NavigationMeshUpdated?.Invoke(this, args);
}
}
private void UpdateScene(SceneInstance newSceneInstance)
{
if (currentSceneInstance != null)
{
if (processor != null)
{
currentSceneInstance.Processors.Remove(processor);
processor.ColliderAdded -= ProcessorOnColliderAdded;
processor.ColliderRemoved -= ProcessorOnColliderRemoved;
}
// Clear builder
builder = new NavigationMeshBuilder();
}
// Set the correct scene
currentSceneInstance = newSceneInstance;
if (currentSceneInstance != null)
{
// Scan for components
processor = new StaticColliderProcessor();
processor.ColliderAdded += ProcessorOnColliderAdded;
processor.ColliderRemoved += ProcessorOnColliderRemoved;
currentSceneInstance.Processors.Add(processor);
pendingRebuild = true;
}
}
private void ProcessorOnColliderAdded(StaticColliderComponent component, StaticColliderData data)
{
builder.Add(data);
if (AutomaticRebuild)
{
pendingRebuild = true;
}
}
private void ProcessorOnColliderRemoved(StaticColliderComponent component, StaticColliderData data)
{
builder.Remove(data);
if (AutomaticRebuild)
{
pendingRebuild = true;
}
}
private void Cleanup()
{
UpdateScene(null);
CurrentNavigationMesh = null;
NavigationMeshUpdated?.Invoke(this, null);
}
private void OnEnabledChanged(object sender, EventArgs eventArgs)
{
if (!Enabled)
{
Cleanup();
}
else
{
pendingRebuild = true;
}
}
}
public class NavigationMeshUpdatedEventArgs : EventArgs
{
public NavigationMesh OldNavigationMesh;
public NavigationMeshBuildResult BuildResult;
}
}