Debian Codegraph @

RecastDemo/Source/CrowdTool.cpp

raw symbols SCIP
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 #include <math.h>
20 #include <stdio.h>
21 #include <string.h>
22 #include <float.h>
23 #include "SDL.h"
24 #include "SDL_opengl.h"
25 #ifdef __APPLE__
26 # include <OpenGL/glu.h>
27 #else
28 # include <GL/glu.h>
29 #endif
30 #include "imgui.h"
31 #include "CrowdTool.h"
32 #include "InputGeom.h"
33 #include "Sample.h"
34 #include "DetourCrowd.h"
35 #include "DetourDebugDraw.h"
36 #include "DetourObstacleAvoidance.h"
37 #include "DetourCommon.h"
38 #include "DetourNode.h"
39 #include "SampleInterfaces.h"
40
41 #ifdef WIN32
42 # define snprintf _snprintf
43 #endif
44
45 static bool isectSegAABB(const float* sp, const float* sq,
46 const float* amin, const float* amax,
47 float& tmin, float& tmax)
48 {
49 static const float EPS = 1e-6f;
50
51 float d[3];
52 dtVsub(d, sq, sp);
53 tmin = 0; // set to -FLT_MAX to get first hit on line
54 tmax = FLT_MAX; // set to max distance ray can travel (for segment)
55
56 // For all three slabs
57 for (int i = 0; i < 3; i++)
58 {
59 if (fabsf(d[i]) < EPS)
60 {
61 // Ray is parallel to slab. No hit if origin not within slab
62 if (sp[i] < amin[i] || sp[i] > amax[i])
63 return false;
64 }
65 else
66 {
67 // Compute intersection t value of ray with near and far plane of slab
68 const float ood = 1.0f / d[i];
69 float t1 = (amin[i] - sp[i]) * ood;
70 float t2 = (amax[i] - sp[i]) * ood;
71 // Make t1 be intersection with near plane, t2 with far plane
72 if (t1 > t2) dtSwap(t1, t2);
73 // Compute the intersection of slab intersections intervals
74 if (t1 > tmin) tmin = t1;
75 if (t2 < tmax) tmax = t2;
76 // Exit with no collision as soon as slab intersection becomes empty
77 if (tmin > tmax) return false;
78 }
79 }
80
81 return true;
82 }
83
84 static void getAgentBounds(const dtCrowdAgent* ag, float* bmin, float* bmax)
85 {
86 const float* p = ag->npos;
87 const float r = ag->params.radius;
88 const float h = ag->params.height;
89 bmin[0] = p[0] - r;
90 bmin[1] = p[1];
91 bmin[2] = p[2] - r;
92 bmax[0] = p[0] + r;
93 bmax[1] = p[1] + h;
94 bmax[2] = p[2] + r;
95 }
96
97 CrowdToolState::CrowdToolState() :
98 m_sample(0),
99 m_nav(0),
100 m_crowd(0),
101 m_targetRef(0),
102 m_run(true)
103 {
104 m_toolParams.m_expandSelectedDebugDraw = true;
105 m_toolParams.m_showCorners = false;
106 m_toolParams.m_showCollisionSegments = false;
107 m_toolParams.m_showPath = false;
108 m_toolParams.m_showVO = false;
109 m_toolParams.m_showOpt = false;
110 m_toolParams.m_showNeis = false;
111 m_toolParams.m_expandDebugDraw = false;
112 m_toolParams.m_showLabels = false;
113 m_toolParams.m_showGrid = false;
114 m_toolParams.m_showNodes = false;
115 m_toolParams.m_showPerfGraph = false;
116 m_toolParams.m_showDetailAll = false;
117 m_toolParams.m_expandOptions = true;
118 m_toolParams.m_anticipateTurns = true;
119 m_toolParams.m_optimizeVis = true;
120 m_toolParams.m_optimizeTopo = true;
121 m_toolParams.m_obstacleAvoidance = true;
122 m_toolParams.m_obstacleAvoidanceType = 3.0f;
123 m_toolParams.m_separation = false;
124 m_toolParams.m_separationWeight = 2.0f;
125
126 memset(m_trails, 0, sizeof(m_trails));
127
128 m_vod = dtAllocObstacleAvoidanceDebugData();
129 m_vod->init(2048);
130
131 memset(&m_agentDebug, 0, sizeof(m_agentDebug));
132 m_agentDebug.idx = -1;
133 m_agentDebug.vod = m_vod;
134 }
135
136 CrowdToolState::~CrowdToolState()
137 {
138 dtFreeObstacleAvoidanceDebugData(m_vod);
139 }
140
141 void CrowdToolState::init(class Sample* sample)
142 {
143 if (m_sample != sample)
144 {
145 m_sample = sample;
146 }
147
148 dtNavMesh* nav = m_sample->getNavMesh();
149 dtCrowd* crowd = m_sample->getCrowd();
150
151 if (nav && crowd && (m_nav != nav || m_crowd != crowd))
152 {
153 m_nav = nav;
154 m_crowd = crowd;
155
156 crowd->init(MAX_AGENTS, m_sample->getAgentRadius(), nav);
157
158 // Make polygons with 'disabled' flag invalid.
159 crowd->getEditableFilter(0)->setExcludeFlags(SAMPLE_POLYFLAGS_DISABLED);
160
161 // Setup local avoidance params to different qualities.
162 dtObstacleAvoidanceParams params;
163 // Use mostly default settings, copy from dtCrowd.
164 memcpy(&params, crowd->getObstacleAvoidanceParams(0), sizeof(dtObstacleAvoidanceParams));
165
166 // Low (11)
167 params.velBias = 0.5f;
168 params.adaptiveDivs = 5;
169 params.adaptiveRings = 2;
170 params.adaptiveDepth = 1;
171 crowd->setObstacleAvoidanceParams(0, &params);
172
173 // Medium (22)
174 params.velBias = 0.5f;
175 params.adaptiveDivs = 5;
176 params.adaptiveRings = 2;
177 params.adaptiveDepth = 2;
178 crowd->setObstacleAvoidanceParams(1, &params);
179
180 // Good (45)
181 params.velBias = 0.5f;
182 params.adaptiveDivs = 7;
183 params.adaptiveRings = 2;
184 params.adaptiveDepth = 3;
185 crowd->setObstacleAvoidanceParams(2, &params);
186
187 // High (66)
188 params.velBias = 0.5f;
189 params.adaptiveDivs = 7;
190 params.adaptiveRings = 3;
191 params.adaptiveDepth = 3;
192
193 crowd->setObstacleAvoidanceParams(3, &params);
194 }
195 }
196
197 void CrowdToolState::reset()
198 {
199 }
200
201 void CrowdToolState::handleRender()
202 {
203 duDebugDraw& dd = m_sample->getDebugDraw();
204 const float rad = m_sample->getAgentRadius();
205
206 dtNavMesh* nav = m_sample->getNavMesh();
207 dtCrowd* crowd = m_sample->getCrowd();
208 if (!nav || !crowd)
209 return;
210
211 if (m_toolParams.m_showNodes && crowd->getPathQueue())
212 {
213 const dtNavMeshQuery* navquery = crowd->getPathQueue()->getNavQuery();
214 if (navquery)
215 duDebugDrawNavMeshNodes(&dd, *navquery);
216 }
217
218 dd.depthMask(false);
219
220 // Draw paths
221 if (m_toolParams.m_showPath)
222 {
223 for (int i = 0; i < crowd->getAgentCount(); i++)
224 {
225 if (m_toolParams.m_showDetailAll == false && i != m_agentDebug.idx)
226 continue;
227 const dtCrowdAgent* ag =crowd->getAgent(i);
228 if (!ag->active)
229 continue;
230 const dtPolyRef* path = ag->corridor.getPath();
231 const int npath = ag->corridor.getPathCount();
232 for (int j = 0; j < npath; ++j)
233 duDebugDrawNavMeshPoly(&dd, *nav, path[j], duRGBA(255,255,255,24));
234 }
235 }
236
237 if (m_targetRef)
238 duDebugDrawCross(&dd, m_targetPos[0],m_targetPos[1]+0.1f,m_targetPos[2], rad, duRGBA(255,255,255,192), 2.0f);
239
240 // Occupancy grid.
241 if (m_toolParams.m_showGrid)
242 {
243 float gridy = -FLT_MAX;
244 for (int i = 0; i < crowd->getAgentCount(); ++i)
245 {
246 const dtCrowdAgent* ag = crowd->getAgent(i);
247 if (!ag->active) continue;
248 const float* pos = ag->corridor.getPos();
249 gridy = dtMax(gridy, pos[1]);
250 }
251 gridy += 1.0f;
252
253 dd.begin(DU_DRAW_QUADS);
254 const dtProximityGrid* grid = crowd->getGrid();
255 const int* bounds = grid->getBounds();
256 const float cs = grid->getCellSize();
257 for (int y = bounds[1]; y <= bounds[3]; ++y)
258 {
259 for (int x = bounds[0]; x <= bounds[2]; ++x)
260 {
261 const int count = grid->getItemCountAt(x,y);
262 if (!count) continue;
263 unsigned int col = duRGBA(128,0,0,dtMin(count*40,255));
264 dd.vertex(x*cs, gridy, y*cs, col);
265 dd.vertex(x*cs, gridy, y*cs+cs, col);
266 dd.vertex(x*cs+cs, gridy, y*cs+cs, col);
267 dd.vertex(x*cs+cs, gridy, y*cs, col);
268 }
269 }
270 dd.end();
271 }
272
273 // Trail
274 for (int i = 0; i < crowd->getAgentCount(); ++i)
275 {
276 const dtCrowdAgent* ag = crowd->getAgent(i);
277 if (!ag->active) continue;
278
279 const AgentTrail* trail = &m_trails[i];
280 const float* pos = ag->npos;
281
282 dd.begin(DU_DRAW_LINES,3.0f);
283 float prev[3], preva = 1;
284 dtVcopy(prev, pos);
285 for (int j = 0; j < AGENT_MAX_TRAIL-1; ++j)
286 {
287 const int idx = (trail->htrail + AGENT_MAX_TRAIL-j) % AGENT_MAX_TRAIL;
288 const float* v = &trail->trail[idx*3];
289 float a = 1 - j/(float)AGENT_MAX_TRAIL;
290 dd.vertex(prev[0],prev[1]+0.1f,prev[2], duRGBA(0,0,0,(int)(128*preva)));
291 dd.vertex(v[0],v[1]+0.1f,v[2], duRGBA(0,0,0,(int)(128*a)));
292 preva = a;
293 dtVcopy(prev, v);
294 }
295 dd.end();
296
297 }
298
299 // Corners & co
300 for (int i = 0; i < crowd->getAgentCount(); i++)
301 {
302 if (m_toolParams.m_showDetailAll == false && i != m_agentDebug.idx)
303 continue;
304 const dtCrowdAgent* ag =crowd->getAgent(i);
305 if (!ag->active)
306 continue;
307
308 const float radius = ag->params.radius;
309 const float* pos = ag->npos;
310
311 if (m_toolParams.m_showCorners)
312 {
313 if (ag->ncorners)
314 {
315 dd.begin(DU_DRAW_LINES, 2.0f);
316 for (int j = 0; j < ag->ncorners; ++j)
317 {
318 const float* va = j == 0 ? pos : &ag->cornerVerts[(j-1)*3];
319 const float* vb = &ag->cornerVerts[j*3];
320 dd.vertex(va[0],va[1]+radius,va[2], duRGBA(128,0,0,192));
321 dd.vertex(vb[0],vb[1]+radius,vb[2], duRGBA(128,0,0,192));
322 }
323 if (ag->ncorners && ag->cornerFlags[ag->ncorners-1] & DT_STRAIGHTPATH_OFFMESH_CONNECTION)
324 {
325 const float* v = &ag->cornerVerts[(ag->ncorners-1)*3];
326 dd.vertex(v[0],v[1],v[2], duRGBA(192,0,0,192));
327 dd.vertex(v[0],v[1]+radius*2,v[2], duRGBA(192,0,0,192));
328 }
329
330 dd.end();
331
332
333 if (m_toolParams.m_anticipateTurns)
334 {
335 /* float dvel[3], pos[3];
336 calcSmoothSteerDirection(ag->pos, ag->cornerVerts, ag->ncorners, dvel);
337 pos[0] = ag->pos[0] + dvel[0];
338 pos[1] = ag->pos[1] + dvel[1];
339 pos[2] = ag->pos[2] + dvel[2];
340
341 const float off = ag->radius+0.1f;
342 const float* tgt = &ag->cornerVerts[0];
343 const float y = ag->pos[1]+off;
344
345 dd.begin(DU_DRAW_LINES, 2.0f);
346
347 dd.vertex(ag->pos[0],y,ag->pos[2], duRGBA(255,0,0,192));
348 dd.vertex(pos[0],y,pos[2], duRGBA(255,0,0,192));
349
350 dd.vertex(pos[0],y,pos[2], duRGBA(255,0,0,192));
351 dd.vertex(tgt[0],y,tgt[2], duRGBA(255,0,0,192));
352
353 dd.end();*/
354 }
355 }
356 }
357
358 if (m_toolParams.m_showCollisionSegments)
359 {
360 const float* center = ag->boundary.getCenter();
361 duDebugDrawCross(&dd, center[0],center[1]+radius,center[2], 0.2f, duRGBA(192,0,128,255), 2.0f);
362 duDebugDrawCircle(&dd, center[0],center[1]+radius,center[2], ag->params.collisionQueryRange,
363 duRGBA(192,0,128,128), 2.0f);
364
365 dd.begin(DU_DRAW_LINES, 3.0f);
366 for (int j = 0; j < ag->boundary.getSegmentCount(); ++j)
367 {
368 const float* s = ag->boundary.getSegment(j);
369 unsigned int col = duRGBA(192,0,128,192);
370 if (dtTriArea2D(pos, s, s+3) < 0.0f)
371 col = duDarkenCol(col);
372
373 duAppendArrow(&dd, s[0],s[1]+0.2f,s[2], s[3],s[4]+0.2f,s[5], 0.0f, 0.3f, col);
374 }
375 dd.end();
376 }
377
378 if (m_toolParams.m_showNeis)
379 {
380 duDebugDrawCircle(&dd, pos[0],pos[1]+radius,pos[2], ag->params.collisionQueryRange,
381 duRGBA(0,192,128,128), 2.0f);
382
383 dd.begin(DU_DRAW_LINES, 2.0f);
384 for (int j = 0; j < ag->nneis; ++j)
385 {
386 // Get 'n'th active agent.
387 // TODO: fix this properly.
388 const dtCrowdAgent* nei = crowd->getAgent(ag->neis[j].idx);
389 if (nei)
390 {
391 dd.vertex(pos[0],pos[1]+radius,pos[2], duRGBA(0,192,128,128));
392 dd.vertex(nei->npos[0],nei->npos[1]+radius,nei->npos[2], duRGBA(0,192,128,128));
393 }
394 }
395 dd.end();
396 }
397
398 if (m_toolParams.m_showOpt)
399 {
400 dd.begin(DU_DRAW_LINES, 2.0f);
401 dd.vertex(m_agentDebug.optStart[0],m_agentDebug.optStart[1]+0.3f,m_agentDebug.optStart[2], duRGBA(0,128,0,192));
402 dd.vertex(m_agentDebug.optEnd[0],m_agentDebug.optEnd[1]+0.3f,m_agentDebug.optEnd[2], duRGBA(0,128,0,192));
403 dd.end();
404 }
405 }
406
407 // Agent cylinders.
408 for (int i = 0; i < crowd->getAgentCount(); ++i)
409 {
410 const dtCrowdAgent* ag = crowd->getAgent(i);
411 if (!ag->active) continue;
412
413 const float radius = ag->params.radius;
414 const float* pos = ag->npos;
415
416 unsigned int col = duRGBA(0,0,0,32);
417 if (m_agentDebug.idx == i)
418 col = duRGBA(255,0,0,128);
419
420 duDebugDrawCircle(&dd, pos[0], pos[1], pos[2], radius, col, 2.0f);
421 }
422
423 for (int i = 0; i < crowd->getAgentCount(); ++i)
424 {
425 const dtCrowdAgent* ag = crowd->getAgent(i);
426 if (!ag->active) continue;
427
428 const float height = ag->params.height;
429 const float radius = ag->params.radius;
430 const float* pos = ag->npos;
431
432 unsigned int col = duRGBA(220,220,220,128);
433 if (ag->targetState == DT_CROWDAGENT_TARGET_REQUESTING || ag->targetState == DT_CROWDAGENT_TARGET_WAITING_FOR_QUEUE)
434 col = duLerpCol(col, duRGBA(128,0,255,128), 32);
435 else if (ag->targetState == DT_CROWDAGENT_TARGET_WAITING_FOR_PATH)
436 col = duLerpCol(col, duRGBA(128,0,255,128), 128);
437 else if (ag->targetState == DT_CROWDAGENT_TARGET_FAILED)
438 col = duRGBA(255,32,16,128);
439 else if (ag->targetState == DT_CROWDAGENT_TARGET_VELOCITY)
440 col = duLerpCol(col, duRGBA(64,255,0,128), 128);
441
442 duDebugDrawCylinder(&dd, pos[0]-radius, pos[1]+radius*0.1f, pos[2]-radius,
443 pos[0]+radius, pos[1]+height, pos[2]+radius, col);
444 }
445
446
447 if (m_toolParams.m_showVO)
448 {
449 for (int i = 0; i < crowd->getAgentCount(); i++)
450 {
451 if (m_toolParams.m_showDetailAll == false && i != m_agentDebug.idx)
452 continue;
453 const dtCrowdAgent* ag =crowd->getAgent(i);
454 if (!ag->active)
455 continue;
456
457 // Draw detail about agent sela
458 const dtObstacleAvoidanceDebugData* vod = m_agentDebug.vod;
459
460 const float dx = ag->npos[0];
461 const float dy = ag->npos[1]+ag->params.height;
462 const float dz = ag->npos[2];
463
464 duDebugDrawCircle(&dd, dx,dy,dz, ag->params.maxSpeed, duRGBA(255,255,255,64), 2.0f);
465
466 dd.begin(DU_DRAW_QUADS);
467 for (int j = 0; j < vod->getSampleCount(); ++j)
468 {
469 const float* p = vod->getSampleVelocity(j);
470 const float sr = vod->getSampleSize(j);
471 const float pen = vod->getSamplePenalty(j);
472 const float pen2 = vod->getSamplePreferredSidePenalty(j);
473 unsigned int col = duLerpCol(duRGBA(255,255,255,220), duRGBA(128,96,0,220), (int)(pen*255));
474 col = duLerpCol(col, duRGBA(128,0,0,220), (int)(pen2*128));
475 dd.vertex(dx+p[0]-sr, dy, dz+p[2]-sr, col);
476 dd.vertex(dx+p[0]-sr, dy, dz+p[2]+sr, col);
477 dd.vertex(dx+p[0]+sr, dy, dz+p[2]+sr, col);
478 dd.vertex(dx+p[0]+sr, dy, dz+p[2]-sr, col);
479 }
480 dd.end();
481 }
482 }
483
484 // Velocity stuff.
485 for (int i = 0; i < crowd->getAgentCount(); ++i)
486 {
487 const dtCrowdAgent* ag = crowd->getAgent(i);
488 if (!ag->active) continue;
489
490 const float radius = ag->params.radius;
491 const float height = ag->params.height;
492 const float* pos = ag->npos;
493 const float* vel = ag->vel;
494 const float* dvel = ag->dvel;
495
496 unsigned int col = duRGBA(220,220,220,192);
497 if (ag->targetState == DT_CROWDAGENT_TARGET_REQUESTING || ag->targetState == DT_CROWDAGENT_TARGET_WAITING_FOR_QUEUE)
498 col = duLerpCol(col, duRGBA(128,0,255,192), 32);
499 else if (ag->targetState == DT_CROWDAGENT_TARGET_WAITING_FOR_PATH)
500 col = duLerpCol(col, duRGBA(128,0,255,192), 128);
501 else if (ag->targetState == DT_CROWDAGENT_TARGET_FAILED)
502 col = duRGBA(255,32,16,192);
503 else if (ag->targetState == DT_CROWDAGENT_TARGET_VELOCITY)
504 col = duLerpCol(col, duRGBA(64,255,0,192), 128);
505
506 duDebugDrawCircle(&dd, pos[0], pos[1]+height, pos[2], radius, col, 2.0f);
507
508 duDebugDrawArrow(&dd, pos[0],pos[1]+height,pos[2],
509 pos[0]+dvel[0],pos[1]+height+dvel[1],pos[2]+dvel[2],
510 0.0f, 0.4f, duRGBA(0,192,255,192), (m_agentDebug.idx == i) ? 2.0f : 1.0f);
511
512 duDebugDrawArrow(&dd, pos[0],pos[1]+height,pos[2],
513 pos[0]+vel[0],pos[1]+height+vel[1],pos[2]+vel[2],
514 0.0f, 0.4f, duRGBA(0,0,0,160), 2.0f);
515 }
516
517 dd.depthMask(true);
518 }
519
520
521 void CrowdToolState::handleRenderOverlay(double* proj, double* model, int* view)
522 {
523 GLdouble x, y, z;
524
525 // Draw start and end point labels
526 if (m_targetRef && gluProject((GLdouble)m_targetPos[0], (GLdouble)m_targetPos[1], (GLdouble)m_targetPos[2],
527 model, proj, view, &x, &y, &z))
528 {
529 imguiDrawText((int)x, (int)(y+25), IMGUI_ALIGN_CENTER, "TARGET", imguiRGBA(0,0,0,220));
530 }
531
532 char label[32];
533
534 if (m_toolParams.m_showNodes)
535 {
536 dtCrowd* crowd = m_sample->getCrowd();
537 if (crowd && crowd->getPathQueue())
538 {
539 const dtNavMeshQuery* navquery = crowd->getPathQueue()->getNavQuery();
540 const dtNodePool* pool = navquery->getNodePool();
541 if (pool)
542 {
543 const float off = 0.5f;
544 for (int i = 0; i < pool->getHashSize(); ++i)
545 {
546 for (dtNodeIndex j = pool->getFirst(i); j != DT_NULL_IDX; j = pool->getNext(j))
547 {
548 const dtNode* node = pool->getNodeAtIdx(j+1);
549 if (!node) continue;
550
551 if (gluProject((GLdouble)node->pos[0],(GLdouble)node->pos[1]+off,(GLdouble)node->pos[2],
552 model, proj, view, &x, &y, &z))
553 {
554 const float heuristic = node->total;// - node->cost;
555 snprintf(label, 32, "%.2f", heuristic);
556 imguiDrawText((int)x, (int)y+15, IMGUI_ALIGN_CENTER, label, imguiRGBA(0,0,0,220));
557 }
558 }
559 }
560 }
561 }
562 }
563
564 if (m_toolParams.m_showLabels)
565 {
566 dtCrowd* crowd = m_sample->getCrowd();
567 if (crowd)
568 {
569 for (int i = 0; i < crowd->getAgentCount(); ++i)
570 {
571 const dtCrowdAgent* ag = crowd->getAgent(i);
572 if (!ag->active) continue;
573 const float* pos = ag->npos;
574 const float h = ag->params.height;
575 if (gluProject((GLdouble)pos[0], (GLdouble)pos[1]+h, (GLdouble)pos[2],
576 model, proj, view, &x, &y, &z))
577 {
578 snprintf(label, 32, "%d", i);
579 imguiDrawText((int)x, (int)y+15, IMGUI_ALIGN_CENTER, label, imguiRGBA(0,0,0,220));
580 }
581 }
582 }
583 }
584 if (m_agentDebug.idx != -1)
585 {
586 dtCrowd* crowd = m_sample->getCrowd();
587 if (crowd)
588 {
589 for (int i = 0; i < crowd->getAgentCount(); i++)
590 {
591 if (m_toolParams.m_showDetailAll == false && i != m_agentDebug.idx)
592 continue;
593 const dtCrowdAgent* ag =crowd->getAgent(i);
594 if (!ag->active)
595 continue;
596 const float radius = ag->params.radius;
597 if (m_toolParams.m_showNeis)
598 {
599 for (int j = 0; j < ag->nneis; ++j)
600 {
601 const dtCrowdAgent* nei = crowd->getAgent(ag->neis[j].idx);
602 if (!nei->active) continue;
603
604 if (gluProject((GLdouble)nei->npos[0], (GLdouble)nei->npos[1]+radius, (GLdouble)nei->npos[2],
605 model, proj, view, &x, &y, &z))
606 {
607 snprintf(label, 32, "%.3f", ag->neis[j].dist);
608 imguiDrawText((int)x, (int)y+15, IMGUI_ALIGN_CENTER, label, imguiRGBA(255,255,255,220));
609 }
610 }
611 }
612 }
613 }
614 }
615
616
617 if (m_toolParams.m_showPerfGraph)
618 {
619 GraphParams gp;
620 gp.setRect(300, 10, 500, 200, 8);
621 gp.setValueRange(0.0f, 2.0f, 4, "ms");
622
623 drawGraphBackground(&gp);
624 drawGraph(&gp, &m_crowdTotalTime, 1, "Total", duRGBA(255,128,0,255));
625
626 gp.setRect(300, 10, 500, 50, 8);
627 gp.setValueRange(0.0f, 2000.0f, 1, "");
628 drawGraph(&gp, &m_crowdSampleCount, 0, "Sample Count", duRGBA(96,96,96,128));
629 }
630
631 }
632
633 void CrowdToolState::handleUpdate(const float dt)
634 {
635 if (m_run)
636 updateTick(dt);
637 }
638
639 void CrowdToolState::addAgent(const float* p)
640 {
641 if (!m_sample) return;
642 dtCrowd* crowd = m_sample->getCrowd();
643
644 dtCrowdAgentParams ap;
645 memset(&ap, 0, sizeof(ap));
646 ap.radius = m_sample->getAgentRadius();
647 ap.height = m_sample->getAgentHeight();
648 ap.maxAcceleration = 8.0f;
649 ap.maxSpeed = 3.5f;
650 ap.collisionQueryRange = ap.radius * 12.0f;
651 ap.pathOptimizationRange = ap.radius * 30.0f;
652 ap.updateFlags = 0;
653 if (m_toolParams.m_anticipateTurns)
654 ap.updateFlags |= DT_CROWD_ANTICIPATE_TURNS;
655 if (m_toolParams.m_optimizeVis)
656 ap.updateFlags |= DT_CROWD_OPTIMIZE_VIS;
657 if (m_toolParams.m_optimizeTopo)
658 ap.updateFlags |= DT_CROWD_OPTIMIZE_TOPO;
659 if (m_toolParams.m_obstacleAvoidance)
660 ap.updateFlags |= DT_CROWD_OBSTACLE_AVOIDANCE;
661 if (m_toolParams.m_separation)
662 ap.updateFlags |= DT_CROWD_SEPARATION;
663 ap.obstacleAvoidanceType = (unsigned char)m_toolParams.m_obstacleAvoidanceType;
664 ap.separationWeight = m_toolParams.m_separationWeight;
665
666 int idx = crowd->addAgent(p, &ap);
667 if (idx != -1)
668 {
669 if (m_targetRef)
670 crowd->requestMoveTarget(idx, m_targetRef, m_targetPos);
671
672 // Init trail
673 AgentTrail* trail = &m_trails[idx];
674 for (int i = 0; i < AGENT_MAX_TRAIL; ++i)
675 dtVcopy(&trail->trail[i*3], p);
676 trail->htrail = 0;
677 }
678 }
679
680 void CrowdToolState::removeAgent(const int idx)
681 {
682 if (!m_sample) return;
683 dtCrowd* crowd = m_sample->getCrowd();
684
685 crowd->removeAgent(idx);
686
687 if (idx == m_agentDebug.idx)
688 m_agentDebug.idx = -1;
689 }
690
691 void CrowdToolState::hilightAgent(const int idx)
692 {
693 m_agentDebug.idx = idx;
694 }
695
696 static void calcVel(float* vel, const float* pos, const float* tgt, const float speed)
697 {
698 dtVsub(vel, tgt, pos);
699 vel[1] = 0.0;
700 dtVnormalize(vel);
701 dtVscale(vel, vel, speed);
702 }
703
704 void CrowdToolState::setMoveTarget(const float* p, bool adjust)
705 {
706 if (!m_sample) return;
707
708 // Find nearest point on navmesh and set move request to that location.
709 dtNavMeshQuery* navquery = m_sample->getNavMeshQuery();
710 dtCrowd* crowd = m_sample->getCrowd();
711 const dtQueryFilter* filter = crowd->getFilter(0);
712 const float* halfExtents = crowd->getQueryExtents();
713
714 if (adjust)
715 {
716 float vel[3];
717 // Request velocity
718 if (m_agentDebug.idx != -1)
719 {
720 const dtCrowdAgent* ag = crowd->getAgent(m_agentDebug.idx);
721 if (ag && ag->active)
722 {
723 calcVel(vel, ag->npos, p, ag->params.maxSpeed);
724 crowd->requestMoveVelocity(m_agentDebug.idx, vel);
725 }
726 }
727 else
728 {
729 for (int i = 0; i < crowd->getAgentCount(); ++i)
730 {
731 const dtCrowdAgent* ag = crowd->getAgent(i);
732 if (!ag->active) continue;
733 calcVel(vel, ag->npos, p, ag->params.maxSpeed);
734 crowd->requestMoveVelocity(i, vel);
735 }
736 }
737 }
738 else
739 {
740 navquery->findNearestPoly(p, halfExtents, filter, &m_targetRef, m_targetPos);
741
742 if (m_agentDebug.idx != -1)
743 {
744 const dtCrowdAgent* ag = crowd->getAgent(m_agentDebug.idx);
745 if (ag && ag->active)
746 crowd->requestMoveTarget(m_agentDebug.idx, m_targetRef, m_targetPos);
747 }
748 else
749 {
750 for (int i = 0; i < crowd->getAgentCount(); ++i)
751 {
752 const dtCrowdAgent* ag = crowd->getAgent(i);
753 if (!ag->active) continue;
754 crowd->requestMoveTarget(i, m_targetRef, m_targetPos);
755 }
756 }
757 }
758 }
759
760 int CrowdToolState::hitTestAgents(const float* s, const float* p)
761 {
762 if (!m_sample) return -1;
763 dtCrowd* crowd = m_sample->getCrowd();
764
765 int isel = -1;
766 float tsel = FLT_MAX;
767
768 for (int i = 0; i < crowd->getAgentCount(); ++i)
769 {
770 const dtCrowdAgent* ag = crowd->getAgent(i);
771 if (!ag->active) continue;
772 float bmin[3], bmax[3];
773 getAgentBounds(ag, bmin, bmax);
774 float tmin, tmax;
775 if (isectSegAABB(s, p, bmin,bmax, tmin, tmax))
776 {
777 if (tmin > 0 && tmin < tsel)
778 {
779 isel = i;
780 tsel = tmin;
781 }
782 }
783 }
784
785 return isel;
786 }
787
788 void CrowdToolState::updateAgentParams()
789 {
790 if (!m_sample) return;
791 dtCrowd* crowd = m_sample->getCrowd();
792 if (!crowd) return;
793
794 unsigned char updateFlags = 0;
795 unsigned char obstacleAvoidanceType = 0;
796
797 if (m_toolParams.m_anticipateTurns)
798 updateFlags |= DT_CROWD_ANTICIPATE_TURNS;
799 if (m_toolParams.m_optimizeVis)
800 updateFlags |= DT_CROWD_OPTIMIZE_VIS;
801 if (m_toolParams.m_optimizeTopo)
802 updateFlags |= DT_CROWD_OPTIMIZE_TOPO;
803 if (m_toolParams.m_obstacleAvoidance)
804 updateFlags |= DT_CROWD_OBSTACLE_AVOIDANCE;
805 if (m_toolParams.m_obstacleAvoidance)
806 updateFlags |= DT_CROWD_OBSTACLE_AVOIDANCE;
807 if (m_toolParams.m_separation)
808 updateFlags |= DT_CROWD_SEPARATION;
809
810 obstacleAvoidanceType = (unsigned char)m_toolParams.m_obstacleAvoidanceType;
811
812 dtCrowdAgentParams params;
813
814 for (int i = 0; i < crowd->getAgentCount(); ++i)
815 {
816 const dtCrowdAgent* ag = crowd->getAgent(i);
817 if (!ag->active) continue;
818 memcpy(&params, &ag->params, sizeof(dtCrowdAgentParams));
819 params.updateFlags = updateFlags;
820 params.obstacleAvoidanceType = obstacleAvoidanceType;
821 params.separationWeight = m_toolParams.m_separationWeight;
822 crowd->updateAgentParameters(i, &params);
823 }
824 }
825
826 void CrowdToolState::updateTick(const float dt)
827 {
828 if (!m_sample) return;
829 dtNavMesh* nav = m_sample->getNavMesh();
830 dtCrowd* crowd = m_sample->getCrowd();
831 if (!nav || !crowd) return;
832
833 TimeVal startTime = getPerfTime();
834
835 crowd->update(dt, &m_agentDebug);
836
837 TimeVal endTime = getPerfTime();
838
839 // Update agent trails
840 for (int i = 0; i < crowd->getAgentCount(); ++i)
841 {
842 const dtCrowdAgent* ag = crowd->getAgent(i);
843 AgentTrail* trail = &m_trails[i];
844 if (!ag->active)
845 continue;
846 // Update agent movement trail.
847 trail->htrail = (trail->htrail + 1) % AGENT_MAX_TRAIL;
848 dtVcopy(&trail->trail[trail->htrail*3], ag->npos);
849 }
850
851 m_agentDebug.vod->normalizeSamples();
852
853 m_crowdSampleCount.addSample((float)crowd->getVelocitySampleCount());
854 m_crowdTotalTime.addSample(getPerfTimeUsec(endTime - startTime) / 1000.0f);
855 }
856
857
858
859
860 CrowdTool::CrowdTool() :
861 m_sample(0),
862 m_state(0),
863 m_mode(TOOLMODE_CREATE)
864 {
865 }
866
867 void CrowdTool::init(Sample* sample)
868 {
869 if (m_sample != sample)
870 {
871 m_sample = sample;
872 }
873
874 if (!sample)
875 return;
876
877 m_state = (CrowdToolState*)sample->getToolState(type());
878 if (!m_state)
879 {
880 m_state = new CrowdToolState();
881 sample->setToolState(type(), m_state);
882 }
883 m_state->init(sample);
884 }
885
886 void CrowdTool::reset()
887 {
888 }
889
890 void CrowdTool::handleMenu()
891 {
892 if (!m_state)
893 return;
894 CrowdToolParams* params = m_state->getToolParams();
895
896 if (imguiCheck("Create Agents", m_mode == TOOLMODE_CREATE))
897 m_mode = TOOLMODE_CREATE;
898 if (imguiCheck("Move Target", m_mode == TOOLMODE_MOVE_TARGET))
899 m_mode = TOOLMODE_MOVE_TARGET;
900 if (imguiCheck("Select Agent", m_mode == TOOLMODE_SELECT))
901 m_mode = TOOLMODE_SELECT;
902 if (imguiCheck("Toggle Polys", m_mode == TOOLMODE_TOGGLE_POLYS))
903 m_mode = TOOLMODE_TOGGLE_POLYS;
904
905 imguiSeparatorLine();
906
907 if (imguiCollapse("Options", 0, params->m_expandOptions))
908 params->m_expandOptions = !params->m_expandOptions;
909
910 if (params->m_expandOptions)
911 {
912 imguiIndent();
913 if (imguiCheck("Optimize Visibility", params->m_optimizeVis))
914 {
915 params->m_optimizeVis = !params->m_optimizeVis;
916 m_state->updateAgentParams();
917 }
918 if (imguiCheck("Optimize Topology", params->m_optimizeTopo))
919 {
920 params->m_optimizeTopo = !params->m_optimizeTopo;
921 m_state->updateAgentParams();
922 }
923 if (imguiCheck("Anticipate Turns", params->m_anticipateTurns))
924 {
925 params->m_anticipateTurns = !params->m_anticipateTurns;
926 m_state->updateAgentParams();
927 }
928 if (imguiCheck("Obstacle Avoidance", params->m_obstacleAvoidance))
929 {
930 params->m_obstacleAvoidance = !params->m_obstacleAvoidance;
931 m_state->updateAgentParams();
932 }
933 if (imguiSlider("Avoidance Quality", &params->m_obstacleAvoidanceType, 0.0f, 3.0f, 1.0f))
934 {
935 m_state->updateAgentParams();
936 }
937 if (imguiCheck("Separation", params->m_separation))
938 {
939 params->m_separation = !params->m_separation;
940 m_state->updateAgentParams();
941 }
942 if (imguiSlider("Separation Weight", &params->m_separationWeight, 0.0f, 20.0f, 0.01f))
943 {
944 m_state->updateAgentParams();
945 }
946
947 imguiUnindent();
948 }
949
950 if (imguiCollapse("Selected Debug Draw", 0, params->m_expandSelectedDebugDraw))
951 params->m_expandSelectedDebugDraw = !params->m_expandSelectedDebugDraw;
952
953 if (params->m_expandSelectedDebugDraw)
954 {
955 imguiIndent();
956 if (imguiCheck("Show Corners", params->m_showCorners))
957 params->m_showCorners = !params->m_showCorners;
958 if (imguiCheck("Show Collision Segs", params->m_showCollisionSegments))
959 params->m_showCollisionSegments = !params->m_showCollisionSegments;
960 if (imguiCheck("Show Path", params->m_showPath))
961 params->m_showPath = !params->m_showPath;
962 if (imguiCheck("Show VO", params->m_showVO))
963 params->m_showVO = !params->m_showVO;
964 if (imguiCheck("Show Path Optimization", params->m_showOpt))
965 params->m_showOpt = !params->m_showOpt;
966 if (imguiCheck("Show Neighbours", params->m_showNeis))
967 params->m_showNeis = !params->m_showNeis;
968 imguiUnindent();
969 }
970
971 if (imguiCollapse("Debug Draw", 0, params->m_expandDebugDraw))
972 params->m_expandDebugDraw = !params->m_expandDebugDraw;
973
974 if (params->m_expandDebugDraw)
975 {
976 imguiIndent();
977 if (imguiCheck("Show Labels", params->m_showLabels))
978 params->m_showLabels = !params->m_showLabels;
979 if (imguiCheck("Show Prox Grid", params->m_showGrid))
980 params->m_showGrid = !params->m_showGrid;
981 if (imguiCheck("Show Nodes", params->m_showNodes))
982 params->m_showNodes = !params->m_showNodes;
983 if (imguiCheck("Show Perf Graph", params->m_showPerfGraph))
984 params->m_showPerfGraph = !params->m_showPerfGraph;
985 if (imguiCheck("Show Detail All", params->m_showDetailAll))
986 params->m_showDetailAll = !params->m_showDetailAll;
987 imguiUnindent();
988 }
989 }
990
991 void CrowdTool::handleClick(const float* s, const float* p, bool shift)
992 {
993 if (!m_sample) return;
994 if (!m_state) return;
995 InputGeom* geom = m_sample->getInputGeom();
996 if (!geom) return;
997 dtCrowd* crowd = m_sample->getCrowd();
998 if (!crowd) return;
999
1000 if (m_mode == TOOLMODE_CREATE)
1001 {
1002 if (shift)
1003 {
1004 // Delete
1005 int ahit = m_state->hitTestAgents(s,p);
1006 if (ahit != -1)
1007 m_state->removeAgent(ahit);
1008 }
1009 else
1010 {
1011 // Add
1012 m_state->addAgent(p);
1013 }
1014 }
1015 else if (m_mode == TOOLMODE_MOVE_TARGET)
1016 {
1017 m_state->setMoveTarget(p, shift);
1018 }
1019 else if (m_mode == TOOLMODE_SELECT)
1020 {
1021 // Highlight
1022 int ahit = m_state->hitTestAgents(s,p);
1023 m_state->hilightAgent(ahit);
1024 }
1025 else if (m_mode == TOOLMODE_TOGGLE_POLYS)
1026 {
1027 dtNavMesh* nav = m_sample->getNavMesh();
1028 dtNavMeshQuery* navquery = m_sample->getNavMeshQuery();
1029 if (nav && navquery)
1030 {
1031 dtQueryFilter filter;
1032 const float* halfExtents = crowd->getQueryExtents();
1033 float tgt[3];
1034 dtPolyRef ref;
1035 navquery->findNearestPoly(p, halfExtents, &filter, &ref, tgt);
1036 if (ref)
1037 {
1038 unsigned short flags = 0;
1039 if (dtStatusSucceed(nav->getPolyFlags(ref, &flags)))
1040 {
1041 flags ^= SAMPLE_POLYFLAGS_DISABLED;
1042 nav->setPolyFlags(ref, flags);
1043 }
1044 }
1045 }
1046 }
1047
1048 }
1049
1050 void CrowdTool::handleStep()
1051 {
1052 if (!m_state) return;
1053
1054 const float dt = 1.0f/20.0f;
1055 m_state->updateTick(dt);
1056
1057 m_state->setRunning(false);
1058 }
1059
1060 void CrowdTool::handleToggle()
1061 {
1062 if (!m_state) return;
1063 m_state->setRunning(!m_state->isRunning());
1064 }
1065
1066 void CrowdTool::handleUpdate(const float dt)
1067 {
1068 rcIgnoreUnused(dt);
1069 }
1070
1071 void CrowdTool::handleRender()
1072 {
1073 }
1074
1075 void CrowdTool::handleRenderOverlay(double* proj, double* model, int* view)
1076 {
1077 rcIgnoreUnused(model);
1078 rcIgnoreUnused(proj);
1079
1080 // Tool help
1081 const int h = view[3];
1082 int ty = h-40;
1083
1084 if (m_mode == TOOLMODE_CREATE)
1085 {
1086 imguiDrawText(280, ty, IMGUI_ALIGN_LEFT, "LMB: add agent. Shift+LMB: remove agent.", imguiRGBA(255,255,255,192));
1087 }
1088 else if (m_mode == TOOLMODE_MOVE_TARGET)
1089 {
1090 imguiDrawText(280, ty, IMGUI_ALIGN_LEFT, "LMB: set move target. Shift+LMB: adjust set velocity.", imguiRGBA(255,255,255,192));
1091 ty -= 20;
1092 imguiDrawText(280, ty, IMGUI_ALIGN_LEFT, "Setting velocity will move the agents without pathfinder.", imguiRGBA(255,255,255,192));
1093 }
1094 else if (m_mode == TOOLMODE_SELECT)
1095 {
1096 imguiDrawText(280, ty, IMGUI_ALIGN_LEFT, "LMB: select agent.", imguiRGBA(255,255,255,192));
1097 }
1098 ty -= 20;
1099 imguiDrawText(280, ty, IMGUI_ALIGN_LEFT, "SPACE: Run/Pause simulation. 1: Step simulation.", imguiRGBA(255,255,255,192));
1100 ty -= 20;
1101
1102 if (m_state && m_state->isRunning())
1103 imguiDrawText(280, ty, IMGUI_ALIGN_LEFT, "- RUNNING -", imguiRGBA(255,32,16,255));
1104 else
1105 imguiDrawText(280, ty, IMGUI_ALIGN_LEFT, "- PAUSED -", imguiRGBA(255,255,255,128));
1106 }