Debian Codegraph @

DetourCrowd/Include/DetourCrowd.h

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 //
2 // Copyright (c) 2009-2010 Mikko Mononen [email protected]
3 //
4 // This software is provided 'as-is', without any express or implied
5 // warranty. In no event will the authors be held liable for any damages
6 // arising from the use of this software.
7 // Permission is granted to anyone to use this software for any purpose,
8 // including commercial applications, and to alter it and redistribute it
9 // freely, subject to the following restrictions:
10 // 1. The origin of this software must not be misrepresented; you must not
11 // claim that you wrote the original software. If you use this software
12 // in a product, an acknowledgment in the product documentation would be
13 // appreciated but is not required.
14 // 2. Altered source versions must be plainly marked as such, and must not be
15 // misrepresented as being the original software.
16 // 3. This notice may not be removed or altered from any source distribution.
17 //
18
19 #ifndef DETOURCROWD_H
20 #define DETOURCROWD_H
21
22 #include "DetourNavMeshQuery.h"
23 #include "DetourObstacleAvoidance.h"
24 #include "DetourLocalBoundary.h"
25 #include "DetourPathCorridor.h"
26 #include "DetourProximityGrid.h"
27 #include "DetourPathQueue.h"
28
29 /// The maximum number of neighbors that a crowd agent can take into account
30 /// for steering decisions.
31 /// @ingroup crowd
32 static const int DT_CROWDAGENT_MAX_NEIGHBOURS = 6;
33
34 /// The maximum number of corners a crowd agent will look ahead in the path.
35 /// This value is used for sizing the crowd agent corner buffers.
36 /// Due to the behavior of the crowd manager, the actual number of useful
37 /// corners will be one less than this number.
38 /// @ingroup crowd
39 static const int DT_CROWDAGENT_MAX_CORNERS = 4;
40
41 /// The maximum number of crowd avoidance configurations supported by the
42 /// crowd manager.
43 /// @ingroup crowd
44 /// @see dtObstacleAvoidanceParams, dtCrowd::setObstacleAvoidanceParams(), dtCrowd::getObstacleAvoidanceParams(),
45 /// dtCrowdAgentParams::obstacleAvoidanceType
46 static const int DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS = 8;
47
48 /// The maximum number of query filter types supported by the crowd manager.
49 /// @ingroup crowd
50 /// @see dtQueryFilter, dtCrowd::getFilter() dtCrowd::getEditableFilter(),
51 /// dtCrowdAgentParams::queryFilterType
52 static const int DT_CROWD_MAX_QUERY_FILTER_TYPE = 16;
53
54 /// Provides neighbor data for agents managed by the crowd.
55 /// @ingroup crowd
56 /// @see dtCrowdAgent::neis, dtCrowd
57 struct dtCrowdNeighbour
58 {
59 int idx; ///< The index of the neighbor in the crowd.
60 float dist; ///< The distance between the current agent and the neighbor.
61 };
62
63 /// The type of navigation mesh polygon the agent is currently traversing.
64 /// @ingroup crowd
65 enum CrowdAgentState
66 {
67 DT_CROWDAGENT_STATE_INVALID, ///< The agent is not in a valid state.
68 DT_CROWDAGENT_STATE_WALKING, ///< The agent is traversing a normal navigation mesh polygon.
69 DT_CROWDAGENT_STATE_OFFMESH ///< The agent is traversing an off-mesh connection.
70 };
71
72 /// Configuration parameters for a crowd agent.
73 /// @ingroup crowd
74 struct dtCrowdAgentParams
75 {
76 float radius; ///< Agent radius. [Limit: >= 0]
77 float height; ///< Agent height. [Limit: > 0]
78 float maxAcceleration; ///< Maximum allowed acceleration. [Limit: >= 0]
79 float maxSpeed; ///< Maximum allowed speed. [Limit: >= 0]
80
81 /// Defines how close a collision element must be before it is considered for steering behaviors. [Limits: > 0]
82 float collisionQueryRange;
83
84 float pathOptimizationRange; ///< The path visibility optimization range. [Limit: > 0]
85
86 /// How aggresive the agent manager should be at avoiding collisions with this agent. [Limit: >= 0]
87 float separationWeight;
88
89 /// Flags that impact steering behavior. (See: #UpdateFlags)
90 unsigned char updateFlags;
91
92 /// The index of the avoidance configuration to use for the agent.
93 /// [Limits: 0 <= value <= #DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS]
94 unsigned char obstacleAvoidanceType;
95
96 /// The index of the query filter used by this agent.
97 unsigned char queryFilterType;
98
99 /// User defined data attached to the agent.
100 void* userData;
101 };
102
103 enum MoveRequestState
104 {
105 DT_CROWDAGENT_TARGET_NONE = 0,
106 DT_CROWDAGENT_TARGET_FAILED,
107 DT_CROWDAGENT_TARGET_VALID,
108 DT_CROWDAGENT_TARGET_REQUESTING,
109 DT_CROWDAGENT_TARGET_WAITING_FOR_QUEUE,
110 DT_CROWDAGENT_TARGET_WAITING_FOR_PATH,
111 DT_CROWDAGENT_TARGET_VELOCITY
112 };
113
114 /// Represents an agent managed by a #dtCrowd object.
115 /// @ingroup crowd
116 struct dtCrowdAgent
117 {
118 /// True if the agent is active, false if the agent is in an unused slot in the agent pool.
119 bool active;
120
121 /// The type of mesh polygon the agent is traversing. (See: #CrowdAgentState)
122 unsigned char state;
123
124 /// True if the agent has valid path (targetState == DT_CROWDAGENT_TARGET_VALID) and the path does not lead to the requested position, else false.
125 bool partial;
126
127 /// The path corridor the agent is using.
128 dtPathCorridor corridor;
129
130 /// The local boundary data for the agent.
131 dtLocalBoundary boundary;
132
133 /// Time since the agent's path corridor was optimized.
134 float topologyOptTime;
135
136 /// The known neighbors of the agent.
137 dtCrowdNeighbour neis[DT_CROWDAGENT_MAX_NEIGHBOURS];
138
139 /// The number of neighbors.
140 int nneis;
141
142 /// The desired speed.
143 float desiredSpeed;
144
145 float npos[3]; ///< The current agent position. [(x, y, z)]
146 float disp[3]; ///< A temporary value used to accumulate agent displacement during iterative collision resolution. [(x, y, z)]
147 float dvel[3]; ///< The desired velocity of the agent. Based on the current path, calculated from scratch each frame. [(x, y, z)]
148 float nvel[3]; ///< The desired velocity adjusted by obstacle avoidance, calculated from scratch each frame. [(x, y, z)]
149 float vel[3]; ///< The actual velocity of the agent. The change from nvel -> vel is constrained by max acceleration. [(x, y, z)]
150
151 /// The agent's configuration parameters.
152 dtCrowdAgentParams params;
153
154 /// The local path corridor corners for the agent. (Staight path.) [(x, y, z) * #ncorners]
155 float cornerVerts[DT_CROWDAGENT_MAX_CORNERS*3];
156
157 /// The local path corridor corner flags. (See: #dtStraightPathFlags) [(flags) * #ncorners]
158 unsigned char cornerFlags[DT_CROWDAGENT_MAX_CORNERS];
159
160 /// The reference id of the polygon being entered at the corner. [(polyRef) * #ncorners]
161 dtPolyRef cornerPolys[DT_CROWDAGENT_MAX_CORNERS];
162
163 /// The number of corners.
164 int ncorners;
165
166 unsigned char targetState; ///< State of the movement request.
167 dtPolyRef targetRef; ///< Target polyref of the movement request.
168 float targetPos[3]; ///< Target position of the movement request (or velocity in case of DT_CROWDAGENT_TARGET_VELOCITY).
169 dtPathQueueRef targetPathqRef; ///< Path finder ref.
170 bool targetReplan; ///< Flag indicating that the current path is being replanned.
171 float targetReplanTime; /// <Time since the agent's target was replanned.
172 };
173
174 struct dtCrowdAgentAnimation
175 {
176 bool active;
177 float initPos[3], startPos[3], endPos[3];
178 dtPolyRef polyRef;
179 float t, tmax;
180 };
181
182 /// Crowd agent update flags.
183 /// @ingroup crowd
184 /// @see dtCrowdAgentParams::updateFlags
185 enum UpdateFlags
186 {
187 DT_CROWD_ANTICIPATE_TURNS = 1,
188 DT_CROWD_OBSTACLE_AVOIDANCE = 2,
189 DT_CROWD_SEPARATION = 4,
190 DT_CROWD_OPTIMIZE_VIS = 8, ///< Use #dtPathCorridor::optimizePathVisibility() to optimize the agent path.
191 DT_CROWD_OPTIMIZE_TOPO = 16 ///< Use dtPathCorridor::optimizePathTopology() to optimize the agent path.
192 };
193
194 struct dtCrowdAgentDebugInfo
195 {
196 int idx;
197 float optStart[3], optEnd[3];
198 dtObstacleAvoidanceDebugData* vod;
199 };
200
201 /// Provides local steering behaviors for a group of agents.
202 /// @ingroup crowd
203 class dtCrowd
204 {
205 int m_maxAgents;
206 dtCrowdAgent* m_agents;
207 dtCrowdAgent** m_activeAgents;
208 dtCrowdAgentAnimation* m_agentAnims;
209
210 dtPathQueue m_pathq;
211
212 dtObstacleAvoidanceParams m_obstacleQueryParams[DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS];
213 dtObstacleAvoidanceQuery* m_obstacleQuery;
214
215 dtProximityGrid* m_grid;
216
217 dtPolyRef* m_pathResult;
218 int m_maxPathResult;
219
220 float m_agentPlacementHalfExtents[3];
221
222 dtQueryFilter m_filters[DT_CROWD_MAX_QUERY_FILTER_TYPE];
223
224 float m_maxAgentRadius;
225
226 int m_velocitySampleCount;
227
228 dtNavMeshQuery* m_navquery;
229
230 void updateTopologyOptimization(dtCrowdAgent** agents, const int nagents, const float dt);
231 void updateMoveRequest(const float dt);
232 void checkPathValidity(dtCrowdAgent** agents, const int nagents, const float dt);
233
234 inline int getAgentIndex(const dtCrowdAgent* agent) const { return (int)(agent - m_agents); }
235
236 bool requestMoveTargetReplan(const int idx, dtPolyRef ref, const float* pos);
237
238 void purge();
239
240 public:
241 dtCrowd();
242 ~dtCrowd();
243
244 /// Initializes the crowd.
245 /// @param[in] maxAgents The maximum number of agents the crowd can manage. [Limit: >= 1]
246 /// @param[in] maxAgentRadius The maximum radius of any agent that will be added to the crowd. [Limit: > 0]
247 /// @param[in] nav The navigation mesh to use for planning.
248 /// @return True if the initialization succeeded.
249 bool init(const int maxAgents, const float maxAgentRadius, dtNavMesh* nav);
250
251 /// Sets the shared avoidance configuration for the specified index.
252 /// @param[in] idx The index. [Limits: 0 <= value < #DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS]
253 /// @param[in] params The new configuration.
254 void setObstacleAvoidanceParams(const int idx, const dtObstacleAvoidanceParams* params);
255
256 /// Gets the shared avoidance configuration for the specified index.
257 /// @param[in] idx The index of the configuration to retreive.
258 /// [Limits: 0 <= value < #DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS]
259 /// @return The requested configuration.
260 const dtObstacleAvoidanceParams* getObstacleAvoidanceParams(const int idx) const;
261
262 /// Gets the specified agent from the pool.
263 /// @param[in] idx The agent index. [Limits: 0 <= value < #getAgentCount()]
264 /// @return The requested agent.
265 const dtCrowdAgent* getAgent(const int idx);
266
267 /// Gets the specified agent from the pool.
268 /// @param[in] idx The agent index. [Limits: 0 <= value < #getAgentCount()]
269 /// @return The requested agent.
270 dtCrowdAgent* getEditableAgent(const int idx);
271
272 /// The maximum number of agents that can be managed by the object.
273 /// @return The maximum number of agents.
274 int getAgentCount() const;
275
276 /// Adds a new agent to the crowd.
277 /// @param[in] pos The requested position of the agent. [(x, y, z)]
278 /// @param[in] params The configutation of the agent.
279 /// @return The index of the agent in the agent pool. Or -1 if the agent could not be added.
280 int addAgent(const float* pos, const dtCrowdAgentParams* params);
281
282 /// Updates the specified agent's configuration.
283 /// @param[in] idx The agent index. [Limits: 0 <= value < #getAgentCount()]
284 /// @param[in] params The new agent configuration.
285 void updateAgentParameters(const int idx, const dtCrowdAgentParams* params);
286
287 /// Removes the agent from the crowd.
288 /// @param[in] idx The agent index. [Limits: 0 <= value < #getAgentCount()]
289 void removeAgent(const int idx);
290
291 /// Submits a new move request for the specified agent.
292 /// @param[in] idx The agent index. [Limits: 0 <= value < #getAgentCount()]
293 /// @param[in] ref The position's polygon reference.
294 /// @param[in] pos The position within the polygon. [(x, y, z)]
295 /// @return True if the request was successfully submitted.
296 bool requestMoveTarget(const int idx, dtPolyRef ref, const float* pos);
297
298 /// Submits a new move request for the specified agent.
299 /// @param[in] idx The agent index. [Limits: 0 <= value < #getAgentCount()]
300 /// @param[in] vel The movement velocity. [(x, y, z)]
301 /// @return True if the request was successfully submitted.
302 bool requestMoveVelocity(const int idx, const float* vel);
303
304 /// Resets any request for the specified agent.
305 /// @param[in] idx The agent index. [Limits: 0 <= value < #getAgentCount()]
306 /// @return True if the request was successfully reseted.
307 bool resetMoveTarget(const int idx);
308
309 /// Gets the active agents int the agent pool.
310 /// @param[out] agents An array of agent pointers. [(#dtCrowdAgent *) * maxAgents]
311 /// @param[in] maxAgents The size of the crowd agent array.
312 /// @return The number of agents returned in @p agents.
313 int getActiveAgents(dtCrowdAgent** agents, const int maxAgents);
314
315 /// Updates the steering and positions of all agents.
316 /// @param[in] dt The time, in seconds, to update the simulation. [Limit: > 0]
317 /// @param[out] debug A debug object to load with debug information. [Opt]
318 void update(const float dt, dtCrowdAgentDebugInfo* debug);
319
320 /// Gets the filter used by the crowd.
321 /// @return The filter used by the crowd.
322 inline const dtQueryFilter* getFilter(const int i) const { return (i >= 0 && i < DT_CROWD_MAX_QUERY_FILTER_TYPE) ? &m_filters[i] : 0; }
323
324 /// Gets the filter used by the crowd.
325 /// @return The filter used by the crowd.
326 inline dtQueryFilter* getEditableFilter(const int i) { return (i >= 0 && i < DT_CROWD_MAX_QUERY_FILTER_TYPE) ? &m_filters[i] : 0; }
327
328 /// Gets the search halfExtents [(x, y, z)] used by the crowd for query operations.
329 /// @return The search halfExtents used by the crowd. [(x, y, z)]
330 const float* getQueryHalfExtents() const { return m_agentPlacementHalfExtents; }
331
332 /// Same as getQueryHalfExtents. Left to maintain backwards compatibility.
333 /// @return The search halfExtents used by the crowd. [(x, y, z)]
334 const float* getQueryExtents() const { return m_agentPlacementHalfExtents; }
335
336 /// Gets the velocity sample count.
337 /// @return The velocity sample count.
338 inline int getVelocitySampleCount() const { return m_velocitySampleCount; }
339
340 /// Gets the crowd's proximity grid.
341 /// @return The crowd's proximity grid.
342 const dtProximityGrid* getGrid() const { return m_grid; }
343
344 /// Gets the crowd's path request queue.
345 /// @return The crowd's path request queue.
346 const dtPathQueue* getPathQueue() const { return &m_pathq; }
347
348 /// Gets the query object used by the crowd.
349 const dtNavMeshQuery* getNavMeshQuery() const { return m_navquery; }
350
351 private:
352 // Explicitly disabled copy constructor and copy assignment operator.
353 dtCrowd(const dtCrowd&);
354 dtCrowd& operator=(const dtCrowd&);
355 };
356
357 /// Allocates a crowd object using the Detour allocator.
358 /// @return A crowd object that is ready for initialization, or null on failure.
359 /// @ingroup crowd
360 dtCrowd* dtAllocCrowd();
361
362 /// Frees the specified crowd object using the Detour allocator.
363 /// @param[in] ptr A crowd object allocated using #dtAllocCrowd
364 /// @ingroup crowd
365 void dtFreeCrowd(dtCrowd* ptr);
366
367
368 #endif // DETOURCROWD_H
369
370 ///////////////////////////////////////////////////////////////////////////
371
372 // This section contains detailed documentation for members that don't have
373 // a source file. It reduces clutter in the main section of the header.
374
375 /**
376
377 @defgroup crowd Crowd
378
379 Members in this module implement local steering and dynamic avoidance features.
380
381 The crowd is the big beast of the navigation features. It not only handles a
382 lot of the path management for you, but also local steering and dynamic
383 avoidance between members of the crowd. I.e. It can keep your agents from
384 running into each other.
385
386 Main class: #dtCrowd
387
388 The #dtNavMeshQuery and #dtPathCorridor classes provide perfectly good, easy
389 to use path planning features. But in the end they only give you points that
390 your navigation client should be moving toward. When it comes to deciding things
391 like agent velocity and steering to avoid other agents, that is up to you to
392 implement. Unless, of course, you decide to use #dtCrowd.
393
394 Basically, you add an agent to the crowd, providing various configuration
395 settings such as maximum speed and acceleration. You also provide a local
396 target to more toward. The crowd manager then provides, with every update, the
397 new agent position and velocity for the frame. The movement will be
398 constrained to the navigation mesh, and steering will be applied to ensure
399 agents managed by the crowd do not collide with each other.
400
401 This is very powerful feature set. But it comes with limitations.
402
403 The biggest limitation is that you must give control of the agent's position
404 completely over to the crowd manager. You can update things like maximum speed
405 and acceleration. But in order for the crowd manager to do its thing, it can't
406 allow you to constantly be giving it overrides to position and velocity. So
407 you give up direct control of the agent's movement. It belongs to the crowd.
408
409 The second biggest limitation revolves around the fact that the crowd manager
410 deals with local planning. So the agent's target should never be more than
411 256 polygons aways from its current position. If it is, you risk
412 your agent failing to reach its target. So you may still need to do long
413 distance planning and provide the crowd manager with intermediate targets.
414
415 Other significant limitations:
416
417 - All agents using the crowd manager will use the same #dtQueryFilter.
418 - Crowd management is relatively expensive. The maximum agents under crowd
419 management at any one time is between 20 and 30. A good place to start
420 is a maximum of 25 agents for 0.5ms per frame.
421
422 @note This is a summary list of members. Use the index or search
423 feature to find minor members.
424
425 @struct dtCrowdAgentParams
426 @see dtCrowdAgent, dtCrowd::addAgent(), dtCrowd::updateAgentParameters()
427
428 @var dtCrowdAgentParams::obstacleAvoidanceType
429 @par
430
431 #dtCrowd permits agents to use different avoidance configurations. This value
432 is the index of the #dtObstacleAvoidanceParams within the crowd.
433
434 @see dtObstacleAvoidanceParams, dtCrowd::setObstacleAvoidanceParams(),
435 dtCrowd::getObstacleAvoidanceParams()
436
437 @var dtCrowdAgentParams::collisionQueryRange
438 @par
439
440 Collision elements include other agents and navigation mesh boundaries.
441
442 This value is often based on the agent radius and/or maximum speed. E.g. radius * 8
443
444 @var dtCrowdAgentParams::pathOptimizationRange
445 @par
446
447 Only applicalbe if #updateFlags includes the #DT_CROWD_OPTIMIZE_VIS flag.
448
449 This value is often based on the agent radius. E.g. radius * 30
450
451 @see dtPathCorridor::optimizePathVisibility()
452
453 @var dtCrowdAgentParams::separationWeight
454 @par
455
456 A higher value will result in agents trying to stay farther away from each other at
457 the cost of more difficult steering in tight spaces.
458
459 */
460