Debian Codegraph @

RecastDemo/Source/Sample_TempObstacles.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 <new>
24 #include "SDL.h"
25 #include "SDL_opengl.h"
26 #ifdef __APPLE__
27 # include <OpenGL/glu.h>
28 #else
29 # include <GL/glu.h>
30 #endif
31 #include "imgui.h"
32 #include "InputGeom.h"
33 #include "Sample.h"
34 #include "Sample_TempObstacles.h"
35 #include "Recast.h"
36 #include "RecastDebugDraw.h"
37 #include "DetourAssert.h"
38 #include "DetourNavMesh.h"
39 #include "DetourNavMeshBuilder.h"
40 #include "DetourDebugDraw.h"
41 #include "DetourCommon.h"
42 #include "DetourTileCache.h"
43 #include "NavMeshTesterTool.h"
44 #include "OffMeshConnectionTool.h"
45 #include "ConvexVolumeTool.h"
46 #include "CrowdTool.h"
47 #include "RecastAlloc.h"
48 #include "RecastAssert.h"
49 #include "fastlz.h"
50
51 #ifdef WIN32
52 # define snprintf _snprintf
53 #endif
54
55
56 // This value specifies how many layers (or "floors") each navmesh tile is expected to have.
57 static const int EXPECTED_LAYERS_PER_TILE = 4;
58
59
60 static bool isectSegAABB(const float* sp, const float* sq,
61 const float* amin, const float* amax,
62 float& tmin, float& tmax)
63 {
64 static const float EPS = 1e-6f;
65
66 float d[3];
67 rcVsub(d, sq, sp);
68 tmin = 0; // set to -FLT_MAX to get first hit on line
69 tmax = FLT_MAX; // set to max distance ray can travel (for segment)
70
71 // For all three slabs
72 for (int i = 0; i < 3; i++)
73 {
74 if (fabsf(d[i]) < EPS)
75 {
76 // Ray is parallel to slab. No hit if origin not within slab
77 if (sp[i] < amin[i] || sp[i] > amax[i])
78 return false;
79 }
80 else
81 {
82 // Compute intersection t value of ray with near and far plane of slab
83 const float ood = 1.0f / d[i];
84 float t1 = (amin[i] - sp[i]) * ood;
85 float t2 = (amax[i] - sp[i]) * ood;
86 // Make t1 be intersection with near plane, t2 with far plane
87 if (t1 > t2) rcSwap(t1, t2);
88 // Compute the intersection of slab intersections intervals
89 if (t1 > tmin) tmin = t1;
90 if (t2 < tmax) tmax = t2;
91 // Exit with no collision as soon as slab intersection becomes empty
92 if (tmin > tmax) return false;
93 }
94 }
95
96 return true;
97 }
98
99 static int calcLayerBufferSize(const int gridWidth, const int gridHeight)
100 {
101 const int headerSize = dtAlign4(sizeof(dtTileCacheLayerHeader));
102 const int gridSize = gridWidth * gridHeight;
103 return headerSize + gridSize*4;
104 }
105
106
107
108
109 struct FastLZCompressor : public dtTileCacheCompressor
110 {
111 virtual ~FastLZCompressor();
112
113 virtual int maxCompressedSize(const int bufferSize)
114 {
115 return (int)(bufferSize* 1.05f);
116 }
117
118 virtual dtStatus compress(const unsigned char* buffer, const int bufferSize,
119 unsigned char* compressed, const int /*maxCompressedSize*/, int* compressedSize)
120 {
121 *compressedSize = fastlz_compress((const void *const)buffer, bufferSize, compressed);
122 return DT_SUCCESS;
123 }
124
125 virtual dtStatus decompress(const unsigned char* compressed, const int compressedSize,
126 unsigned char* buffer, const int maxBufferSize, int* bufferSize)
127 {
128 *bufferSize = fastlz_decompress(compressed, compressedSize, buffer, maxBufferSize);
129 return *bufferSize < 0 ? DT_FAILURE : DT_SUCCESS;
130 }
131 };
132
133 FastLZCompressor::~FastLZCompressor()
134 {
135 // Defined out of line to fix the weak v-tables warning
136 }
137
138 struct LinearAllocator : public dtTileCacheAlloc
139 {
140 unsigned char* buffer;
141 size_t capacity;
142 size_t top;
143 size_t high;
144
145 LinearAllocator(const size_t cap) : buffer(0), capacity(0), top(0), high(0)
146 {
147 resize(cap);
148 }
149
150 virtual ~LinearAllocator();
151
152 void resize(const size_t cap)
153 {
154 if (buffer) dtFree(buffer);
155 buffer = (unsigned char*)dtAlloc(cap, DT_ALLOC_PERM);
156 capacity = cap;
157 }
158
159 virtual void reset()
160 {
161 high = dtMax(high, top);
162 top = 0;
163 }
164
165 virtual void* alloc(const size_t size)
166 {
167 if (!buffer)
168 return 0;
169 if (top+size > capacity)
170 return 0;
171 unsigned char* mem = &buffer[top];
172 top += size;
173 return mem;
174 }
175
176 virtual void free(void* /*ptr*/)
177 {
178 // Empty
179 }
180 };
181
182 LinearAllocator::~LinearAllocator()
183 {
184 // Defined out of line to fix the weak v-tables warning
185 dtFree(buffer);
186 }
187
188 struct MeshProcess : public dtTileCacheMeshProcess
189 {
190 InputGeom* m_geom;
191
192 inline MeshProcess() : m_geom(0)
193 {
194 }
195
196 virtual ~MeshProcess();
197
198 inline void init(InputGeom* geom)
199 {
200 m_geom = geom;
201 }
202
203 virtual void process(struct dtNavMeshCreateParams* params,
204 unsigned char* polyAreas, unsigned short* polyFlags)
205 {
206 // Update poly flags from areas.
207 for (int i = 0; i < params->polyCount; ++i)
208 {
209 if (polyAreas[i] == DT_TILECACHE_WALKABLE_AREA)
210 polyAreas[i] = SAMPLE_POLYAREA_GROUND;
211
212 if (polyAreas[i] == SAMPLE_POLYAREA_GROUND ||
213 polyAreas[i] == SAMPLE_POLYAREA_GRASS ||
214 polyAreas[i] == SAMPLE_POLYAREA_ROAD)
215 {
216 polyFlags[i] = SAMPLE_POLYFLAGS_WALK;
217 }
218 else if (polyAreas[i] == SAMPLE_POLYAREA_WATER)
219 {
220 polyFlags[i] = SAMPLE_POLYFLAGS_SWIM;
221 }
222 else if (polyAreas[i] == SAMPLE_POLYAREA_DOOR)
223 {
224 polyFlags[i] = SAMPLE_POLYFLAGS_WALK | SAMPLE_POLYFLAGS_DOOR;
225 }
226 }
227
228 // Pass in off-mesh connections.
229 if (m_geom)
230 {
231 params->offMeshConVerts = m_geom->getOffMeshConnectionVerts();
232 params->offMeshConRad = m_geom->getOffMeshConnectionRads();
233 params->offMeshConDir = m_geom->getOffMeshConnectionDirs();
234 params->offMeshConAreas = m_geom->getOffMeshConnectionAreas();
235 params->offMeshConFlags = m_geom->getOffMeshConnectionFlags();
236 params->offMeshConUserID = m_geom->getOffMeshConnectionId();
237 params->offMeshConCount = m_geom->getOffMeshConnectionCount();
238 }
239 }
240 };
241
242 MeshProcess::~MeshProcess()
243 {
244 // Defined out of line to fix the weak v-tables warning
245 }
246
247 static const int MAX_LAYERS = 32;
248
249 struct TileCacheData
250 {
251 unsigned char* data;
252 int dataSize;
253 };
254
255 struct RasterizationContext
256 {
257 RasterizationContext() :
258 solid(0),
259 triareas(0),
260 lset(0),
261 chf(0),
262 ntiles(0)
263 {
264 memset(tiles, 0, sizeof(TileCacheData)*MAX_LAYERS);
265 }
266
267 ~RasterizationContext()
268 {
269 rcFreeHeightField(solid);
270 delete [] triareas;
271 rcFreeHeightfieldLayerSet(lset);
272 rcFreeCompactHeightfield(chf);
273 for (int i = 0; i < MAX_LAYERS; ++i)
274 {
275 dtFree(tiles[i].data);
276 tiles[i].data = 0;
277 }
278 }
279
280 rcHeightfield* solid;
281 unsigned char* triareas;
282 rcHeightfieldLayerSet* lset;
283 rcCompactHeightfield* chf;
284 TileCacheData tiles[MAX_LAYERS];
285 int ntiles;
286 };
287
288 int Sample_TempObstacles::rasterizeTileLayers(
289 const int tx, const int ty,
290 const rcConfig& cfg,
291 TileCacheData* tiles,
292 const int maxTiles)
293 {
294 if (!m_geom || !m_geom->getMesh() || !m_geom->getChunkyMesh())
295 {
296 m_ctx->log(RC_LOG_ERROR, "buildTile: Input mesh is not specified.");
297 return 0;
298 }
299
300 FastLZCompressor comp;
301 RasterizationContext rc;
302
303 const float* verts = m_geom->getMesh()->getVerts();
304 const int nverts = m_geom->getMesh()->getVertCount();
305 const rcChunkyTriMesh* chunkyMesh = m_geom->getChunkyMesh();
306
307 // Tile bounds.
308 const float tcs = cfg.tileSize * cfg.cs;
309
310 rcConfig tcfg;
311 memcpy(&tcfg, &cfg, sizeof(tcfg));
312
313 tcfg.bmin[0] = cfg.bmin[0] + tx*tcs;
314 tcfg.bmin[1] = cfg.bmin[1];
315 tcfg.bmin[2] = cfg.bmin[2] + ty*tcs;
316 tcfg.bmax[0] = cfg.bmin[0] + (tx+1)*tcs;
317 tcfg.bmax[1] = cfg.bmax[1];
318 tcfg.bmax[2] = cfg.bmin[2] + (ty+1)*tcs;
319 tcfg.bmin[0] -= tcfg.borderSize*tcfg.cs;
320 tcfg.bmin[2] -= tcfg.borderSize*tcfg.cs;
321 tcfg.bmax[0] += tcfg.borderSize*tcfg.cs;
322 tcfg.bmax[2] += tcfg.borderSize*tcfg.cs;
323
324 // Allocate voxel heightfield where we rasterize our input data to.
325 rc.solid = rcAllocHeightfield();
326 if (!rc.solid)
327 {
328 m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'solid'.");
329 return 0;
330 }
331 if (!rcCreateHeightfield(m_ctx, *rc.solid, tcfg.width, tcfg.height, tcfg.bmin, tcfg.bmax, tcfg.cs, tcfg.ch))
332 {
333 m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not create solid heightfield.");
334 return 0;
335 }
336
337 // Allocate array that can hold triangle flags.
338 // If you have multiple meshes you need to process, allocate
339 // and array which can hold the max number of triangles you need to process.
340 rc.triareas = new unsigned char[chunkyMesh->maxTrisPerChunk];
341 if (!rc.triareas)
342 {
343 m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'm_triareas' (%d).", chunkyMesh->maxTrisPerChunk);
344 return 0;
345 }
346
347 float tbmin[2], tbmax[2];
348 tbmin[0] = tcfg.bmin[0];
349 tbmin[1] = tcfg.bmin[2];
350 tbmax[0] = tcfg.bmax[0];
351 tbmax[1] = tcfg.bmax[2];
352 int cid[512];// TODO: Make grow when returning too many items.
353 const int ncid = rcGetChunksOverlappingRect(chunkyMesh, tbmin, tbmax, cid, 512);
354 if (!ncid)
355 {
356 return 0; // empty
357 }
358
359 for (int i = 0; i < ncid; ++i)
360 {
361 const rcChunkyTriMeshNode& node = chunkyMesh->nodes[cid[i]];
362 const int* tris = &chunkyMesh->tris[node.i*3];
363 const int ntris = node.n;
364
365 memset(rc.triareas, 0, ntris*sizeof(unsigned char));
366 rcMarkWalkableTriangles(m_ctx, tcfg.walkableSlopeAngle,
367 verts, nverts, tris, ntris, rc.triareas);
368
369 if (!rcRasterizeTriangles(m_ctx, verts, nverts, tris, rc.triareas, ntris, *rc.solid, tcfg.walkableClimb))
370 return 0;
371 }
372
373 // Once all geometry is rasterized, we do initial pass of filtering to
374 // remove unwanted overhangs caused by the conservative rasterization
375 // as well as filter spans where the character cannot possibly stand.
376 if (m_filterLowHangingObstacles)
377 rcFilterLowHangingWalkableObstacles(m_ctx, tcfg.walkableClimb, *rc.solid);
378 if (m_filterLedgeSpans)
379 rcFilterLedgeSpans(m_ctx, tcfg.walkableHeight, tcfg.walkableClimb, *rc.solid);
380 if (m_filterWalkableLowHeightSpans)
381 rcFilterWalkableLowHeightSpans(m_ctx, tcfg.walkableHeight, *rc.solid);
382
383
384 rc.chf = rcAllocCompactHeightfield();
385 if (!rc.chf)
386 {
387 m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'chf'.");
388 return 0;
389 }
390 if (!rcBuildCompactHeightfield(m_ctx, tcfg.walkableHeight, tcfg.walkableClimb, *rc.solid, *rc.chf))
391 {
392 m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build compact data.");
393 return 0;
394 }
395
396 // Erode the walkable area by agent radius.
397 if (!rcErodeWalkableArea(m_ctx, tcfg.walkableRadius, *rc.chf))
398 {
399 m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not erode.");
400 return 0;
401 }
402
403 // (Optional) Mark areas.
404 const ConvexVolume* vols = m_geom->getConvexVolumes();
405 for (int i = 0; i < m_geom->getConvexVolumeCount(); ++i)
406 {
407 rcMarkConvexPolyArea(m_ctx, vols[i].verts, vols[i].nverts,
408 vols[i].hmin, vols[i].hmax,
409 (unsigned char)vols[i].area, *rc.chf);
410 }
411
412 rc.lset = rcAllocHeightfieldLayerSet();
413 if (!rc.lset)
414 {
415 m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'lset'.");
416 return 0;
417 }
418 if (!rcBuildHeightfieldLayers(m_ctx, *rc.chf, tcfg.borderSize, tcfg.walkableHeight, *rc.lset))
419 {
420 m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build heighfield layers.");
421 return 0;
422 }
423
424 rc.ntiles = 0;
425 for (int i = 0; i < rcMin(rc.lset->nlayers, MAX_LAYERS); ++i)
426 {
427 TileCacheData* tile = &rc.tiles[rc.ntiles++];
428 const rcHeightfieldLayer* layer = &rc.lset->layers[i];
429
430 // Store header
431 dtTileCacheLayerHeader header;
432 header.magic = DT_TILECACHE_MAGIC;
433 header.version = DT_TILECACHE_VERSION;
434
435 // Tile layer location in the navmesh.
436 header.tx = tx;
437 header.ty = ty;
438 header.tlayer = i;
439 dtVcopy(header.bmin, layer->bmin);
440 dtVcopy(header.bmax, layer->bmax);
441
442 // Tile info.
443 header.width = (unsigned char)layer->width;
444 header.height = (unsigned char)layer->height;
445 header.minx = (unsigned char)layer->minx;
446 header.maxx = (unsigned char)layer->maxx;
447 header.miny = (unsigned char)layer->miny;
448 header.maxy = (unsigned char)layer->maxy;
449 header.hmin = (unsigned short)layer->hmin;
450 header.hmax = (unsigned short)layer->hmax;
451
452 dtStatus status = dtBuildTileCacheLayer(&comp, &header, layer->heights, layer->areas, layer->cons,
453 &tile->data, &tile->dataSize);
454 if (dtStatusFailed(status))
455 {
456 return 0;
457 }
458 }
459
460 // Transfer ownsership of tile data from build context to the caller.
461 int n = 0;
462 for (int i = 0; i < rcMin(rc.ntiles, maxTiles); ++i)
463 {
464 tiles[n++] = rc.tiles[i];
465 rc.tiles[i].data = 0;
466 rc.tiles[i].dataSize = 0;
467 }
468
469 return n;
470 }
471
472
473 void drawTiles(duDebugDraw* dd, dtTileCache* tc)
474 {
475 unsigned int fcol[6];
476 float bmin[3], bmax[3];
477
478 for (int i = 0; i < tc->getTileCount(); ++i)
479 {
480 const dtCompressedTile* tile = tc->getTile(i);
481 if (!tile->header) continue;
482
483 tc->calcTightTileBounds(tile->header, bmin, bmax);
484
485 const unsigned int col = duIntToCol(i,64);
486 duCalcBoxColors(fcol, col, col);
487 duDebugDrawBox(dd, bmin[0],bmin[1],bmin[2], bmax[0],bmax[1],bmax[2], fcol);
488 }
489
490 for (int i = 0; i < tc->getTileCount(); ++i)
491 {
492 const dtCompressedTile* tile = tc->getTile(i);
493 if (!tile->header) continue;
494
495 tc->calcTightTileBounds(tile->header, bmin, bmax);
496
497 const unsigned int col = duIntToCol(i,255);
498 const float pad = tc->getParams()->cs * 0.1f;
499 duDebugDrawBoxWire(dd, bmin[0]-pad,bmin[1]-pad,bmin[2]-pad,
500 bmax[0]+pad,bmax[1]+pad,bmax[2]+pad, col, 2.0f);
501 }
502
503 }
504
505 enum DrawDetailType
506 {
507 DRAWDETAIL_AREAS,
508 DRAWDETAIL_REGIONS,
509 DRAWDETAIL_CONTOURS,
510 DRAWDETAIL_MESH
511 };
512
513 void drawDetail(duDebugDraw* dd, dtTileCache* tc, const int tx, const int ty, int type)
514 {
515 struct TileCacheBuildContext
516 {
517 inline TileCacheBuildContext(struct dtTileCacheAlloc* a) : layer(0), lcset(0), lmesh(0), alloc(a) {}
518 inline ~TileCacheBuildContext() { purge(); }
519 void purge()
520 {
521 dtFreeTileCacheLayer(alloc, layer);
522 layer = 0;
523 dtFreeTileCacheContourSet(alloc, lcset);
524 lcset = 0;
525 dtFreeTileCachePolyMesh(alloc, lmesh);
526 lmesh = 0;
527 }
528 struct dtTileCacheLayer* layer;
529 struct dtTileCacheContourSet* lcset;
530 struct dtTileCachePolyMesh* lmesh;
531 struct dtTileCacheAlloc* alloc;
532 };
533
534 dtCompressedTileRef tiles[MAX_LAYERS];
535 const int ntiles = tc->getTilesAt(tx,ty,tiles,MAX_LAYERS);
536
537 dtTileCacheAlloc* talloc = tc->getAlloc();
538 dtTileCacheCompressor* tcomp = tc->getCompressor();
539 const dtTileCacheParams* params = tc->getParams();
540
541 for (int i = 0; i < ntiles; ++i)
542 {
543 const dtCompressedTile* tile = tc->getTileByRef(tiles[i]);
544
545 talloc->reset();
546
547 TileCacheBuildContext bc(talloc);
548 const int walkableClimbVx = (int)(params->walkableClimb / params->ch);
549 dtStatus status;
550
551 // Decompress tile layer data.
552 status = dtDecompressTileCacheLayer(talloc, tcomp, tile->data, tile->dataSize, &bc.layer);
553 if (dtStatusFailed(status))
554 return;
555 if (type == DRAWDETAIL_AREAS)
556 {
557 duDebugDrawTileCacheLayerAreas(dd, *bc.layer, params->cs, params->ch);
558 continue;
559 }
560
561 // Build navmesh
562 status = dtBuildTileCacheRegions(talloc, *bc.layer, walkableClimbVx);
563 if (dtStatusFailed(status))
564 return;
565 if (type == DRAWDETAIL_REGIONS)
566 {
567 duDebugDrawTileCacheLayerRegions(dd, *bc.layer, params->cs, params->ch);
568 continue;
569 }
570
571 bc.lcset = dtAllocTileCacheContourSet(talloc);
572 if (!bc.lcset)
573 return;
574 status = dtBuildTileCacheContours(talloc, *bc.layer, walkableClimbVx,
575 params->maxSimplificationError, *bc.lcset);
576 if (dtStatusFailed(status))
577 return;
578 if (type == DRAWDETAIL_CONTOURS)
579 {
580 duDebugDrawTileCacheContours(dd, *bc.lcset, tile->header->bmin, params->cs, params->ch);
581 continue;
582 }
583
584 bc.lmesh = dtAllocTileCachePolyMesh(talloc);
585 if (!bc.lmesh)
586 return;
587 status = dtBuildTileCachePolyMesh(talloc, *bc.lcset, *bc.lmesh);
588 if (dtStatusFailed(status))
589 return;
590
591 if (type == DRAWDETAIL_MESH)
592 {
593 duDebugDrawTileCachePolyMesh(dd, *bc.lmesh, tile->header->bmin, params->cs, params->ch);
594 continue;
595 }
596
597 }
598 }
599
600
601 void drawDetailOverlay(const dtTileCache* tc, const int tx, const int ty, double* proj, double* model, int* view)
602 {
603 dtCompressedTileRef tiles[MAX_LAYERS];
604 const int ntiles = tc->getTilesAt(tx,ty,tiles,MAX_LAYERS);
605 if (!ntiles)
606 return;
607
608 const int rawSize = calcLayerBufferSize(tc->getParams()->width, tc->getParams()->height);
609
610 char text[128];
611
612 for (int i = 0; i < ntiles; ++i)
613 {
614 const dtCompressedTile* tile = tc->getTileByRef(tiles[i]);
615
616 float pos[3];
617 pos[0] = (tile->header->bmin[0]+tile->header->bmax[0])/2.0f;
618 pos[1] = tile->header->bmin[1];
619 pos[2] = (tile->header->bmin[2]+tile->header->bmax[2])/2.0f;
620
621 GLdouble x, y, z;
622 if (gluProject((GLdouble)pos[0], (GLdouble)pos[1], (GLdouble)pos[2],
623 model, proj, view, &x, &y, &z))
624 {
625 snprintf(text,128,"(%d,%d)/%d", tile->header->tx,tile->header->ty,tile->header->tlayer);
626 imguiDrawText((int)x, (int)y-25, IMGUI_ALIGN_CENTER, text, imguiRGBA(0,0,0,220));
627 snprintf(text,128,"Compressed: %.1f kB", tile->dataSize/1024.0f);
628 imguiDrawText((int)x, (int)y-45, IMGUI_ALIGN_CENTER, text, imguiRGBA(0,0,0,128));
629 snprintf(text,128,"Raw:%.1fkB", rawSize/1024.0f);
630 imguiDrawText((int)x, (int)y-65, IMGUI_ALIGN_CENTER, text, imguiRGBA(0,0,0,128));
631 }
632 }
633 }
634
635 dtObstacleRef hitTestObstacle(const dtTileCache* tc, const float* sp, const float* sq)
636 {
637 float tmin = FLT_MAX;
638 const dtTileCacheObstacle* obmin = 0;
639 for (int i = 0; i < tc->getObstacleCount(); ++i)
640 {
641 const dtTileCacheObstacle* ob = tc->getObstacle(i);
642 if (ob->state == DT_OBSTACLE_EMPTY)
643 continue;
644
645 float bmin[3], bmax[3], t0,t1;
646 tc->getObstacleBounds(ob, bmin,bmax);
647
648 if (isectSegAABB(sp,sq, bmin,bmax, t0,t1))
649 {
650 if (t0 < tmin)
651 {
652 tmin = t0;
653 obmin = ob;
654 }
655 }
656 }
657 return tc->getObstacleRef(obmin);
658 }
659
660 void drawObstacles(duDebugDraw* dd, const dtTileCache* tc)
661 {
662 // Draw obstacles
663 for (int i = 0; i < tc->getObstacleCount(); ++i)
664 {
665 const dtTileCacheObstacle* ob = tc->getObstacle(i);
666 if (ob->state == DT_OBSTACLE_EMPTY) continue;
667 float bmin[3], bmax[3];
668 tc->getObstacleBounds(ob, bmin,bmax);
669
670 unsigned int col = 0;
671 if (ob->state == DT_OBSTACLE_PROCESSING)
672 col = duRGBA(255,255,0,128);
673 else if (ob->state == DT_OBSTACLE_PROCESSED)
674 col = duRGBA(255,192,0,192);
675 else if (ob->state == DT_OBSTACLE_REMOVING)
676 col = duRGBA(220,0,0,128);
677
678 duDebugDrawCylinder(dd, bmin[0],bmin[1],bmin[2], bmax[0],bmax[1],bmax[2], col);
679 duDebugDrawCylinderWire(dd, bmin[0],bmin[1],bmin[2], bmax[0],bmax[1],bmax[2], duDarkenCol(col), 2);
680 }
681 }
682
683 class TempObstacleHilightTool : public SampleTool
684 {
685 Sample_TempObstacles* m_sample;
686 float m_hitPos[3];
687 bool m_hitPosSet;
688 int m_drawType;
689
690 public:
691
692 TempObstacleHilightTool() :
693 m_sample(0),
694 m_hitPosSet(false),
695 m_drawType(DRAWDETAIL_AREAS)
696 {
697 m_hitPos[0] = m_hitPos[1] = m_hitPos[2] = 0;
698 }
699
700 virtual ~TempObstacleHilightTool();
701
702 virtual int type() { return TOOL_TILE_HIGHLIGHT; }
703
704 virtual void init(Sample* sample)
705 {
706 m_sample = (Sample_TempObstacles*)sample;
707 }
708
709 virtual void reset() {}
710
711 virtual void handleMenu()
712 {
713 imguiLabel("Highlight Tile Cache");
714 imguiValue("Click LMB to highlight a tile.");
715 imguiSeparator();
716 if (imguiCheck("Draw Areas", m_drawType == DRAWDETAIL_AREAS))
717 m_drawType = DRAWDETAIL_AREAS;
718 if (imguiCheck("Draw Regions", m_drawType == DRAWDETAIL_REGIONS))
719 m_drawType = DRAWDETAIL_REGIONS;
720 if (imguiCheck("Draw Contours", m_drawType == DRAWDETAIL_CONTOURS))
721 m_drawType = DRAWDETAIL_CONTOURS;
722 if (imguiCheck("Draw Mesh", m_drawType == DRAWDETAIL_MESH))
723 m_drawType = DRAWDETAIL_MESH;
724 }
725
726 virtual void handleClick(const float* /*s*/, const float* p, bool /*shift*/)
727 {
728 m_hitPosSet = true;
729 rcVcopy(m_hitPos,p);
730 }
731
732 virtual void handleToggle() {}
733
734 virtual void handleStep() {}
735
736 virtual void handleUpdate(const float /*dt*/) {}
737
738 virtual void handleRender()
739 {
740 if (m_hitPosSet && m_sample)
741 {
742 const float s = m_sample->getAgentRadius();
743 glColor4ub(0,0,0,128);
744 glLineWidth(2.0f);
745 glBegin(GL_LINES);
746 glVertex3f(m_hitPos[0]-s,m_hitPos[1]+0.1f,m_hitPos[2]);
747 glVertex3f(m_hitPos[0]+s,m_hitPos[1]+0.1f,m_hitPos[2]);
748 glVertex3f(m_hitPos[0],m_hitPos[1]-s+0.1f,m_hitPos[2]);
749 glVertex3f(m_hitPos[0],m_hitPos[1]+s+0.1f,m_hitPos[2]);
750 glVertex3f(m_hitPos[0],m_hitPos[1]+0.1f,m_hitPos[2]-s);
751 glVertex3f(m_hitPos[0],m_hitPos[1]+0.1f,m_hitPos[2]+s);
752 glEnd();
753 glLineWidth(1.0f);
754
755 int tx=0, ty=0;
756 m_sample->getTilePos(m_hitPos, tx, ty);
757 m_sample->renderCachedTile(tx,ty,m_drawType);
758 }
759 }
760
761 virtual void handleRenderOverlay(double* proj, double* model, int* view)
762 {
763 if (m_hitPosSet)
764 {
765 if (m_sample)
766 {
767 int tx=0, ty=0;
768 m_sample->getTilePos(m_hitPos, tx, ty);
769 m_sample->renderCachedTileOverlay(tx,ty,proj,model,view);
770 }
771 }
772 }
773 };
774
775 TempObstacleHilightTool::~TempObstacleHilightTool()
776 {
777 // Defined out of line to fix the weak v-tables warning
778 }
779
780 class TempObstacleCreateTool : public SampleTool
781 {
782 Sample_TempObstacles* m_sample;
783
784 public:
785
786 TempObstacleCreateTool() : m_sample(0)
787 {
788 }
789
790 virtual ~TempObstacleCreateTool();
791
792 virtual int type() { return TOOL_TEMP_OBSTACLE; }
793
794 virtual void init(Sample* sample)
795 {
796 m_sample = (Sample_TempObstacles*)sample;
797 }
798
799 virtual void reset() {}
800
801 virtual void handleMenu()
802 {
803 imguiLabel("Create Temp Obstacles");
804
805 if (imguiButton("Remove All"))
806 m_sample->clearAllTempObstacles();
807
808 imguiSeparator();
809
810 imguiValue("Click LMB to create an obstacle.");
811 imguiValue("Shift+LMB to remove an obstacle.");
812 }
813
814 virtual void handleClick(const float* s, const float* p, bool shift)
815 {
816 if (m_sample)
817 {
818 if (shift)
819 m_sample->removeTempObstacle(s,p);
820 else
821 m_sample->addTempObstacle(p);
822 }
823 }
824
825 virtual void handleToggle() {}
826 virtual void handleStep() {}
827 virtual void handleUpdate(const float /*dt*/) {}
828 virtual void handleRender() {}
829 virtual void handleRenderOverlay(double* /*proj*/, double* /*model*/, int* /*view*/) { }
830 };
831
832 TempObstacleCreateTool::~TempObstacleCreateTool()
833 {
834 // Defined out of line to fix the weak v-tables warning
835 }
836
837 Sample_TempObstacles::Sample_TempObstacles() :
838 m_keepInterResults(false),
839 m_tileCache(0),
840 m_cacheBuildTimeMs(0),
841 m_cacheCompressedSize(0),
842 m_cacheRawSize(0),
843 m_cacheLayerCount(0),
844 m_cacheBuildMemUsage(0),
845 m_drawMode(DRAWMODE_NAVMESH),
846 m_maxTiles(0),
847 m_maxPolysPerTile(0),
848 m_tileSize(48)
849 {
850 resetCommonSettings();
851
852 m_talloc = new LinearAllocator(32000);
853 m_tcomp = new FastLZCompressor;
854 m_tmproc = new MeshProcess;
855
856 setTool(new TempObstacleCreateTool);
857 }
858
859 Sample_TempObstacles::~Sample_TempObstacles()
860 {
861 dtFreeNavMesh(m_navMesh);
862 m_navMesh = 0;
863 dtFreeTileCache(m_tileCache);
864 }
865
866 void Sample_TempObstacles::handleSettings()
867 {
868 Sample::handleCommonSettings();
869
870 if (imguiCheck("Keep Itermediate Results", m_keepInterResults))
871 m_keepInterResults = !m_keepInterResults;
872
873 imguiLabel("Tiling");
874 imguiSlider("TileSize", &m_tileSize, 16.0f, 128.0f, 8.0f);
875
876 int gridSize = 1;
877 if (m_geom)
878 {
879 const float* bmin = m_geom->getNavMeshBoundsMin();
880 const float* bmax = m_geom->getNavMeshBoundsMax();
881 char text[64];
882 int gw = 0, gh = 0;
883 rcCalcGridSize(bmin, bmax, m_cellSize, &gw, &gh);
884 const int ts = (int)m_tileSize;
885 const int tw = (gw + ts-1) / ts;
886 const int th = (gh + ts-1) / ts;
887 snprintf(text, 64, "Tiles %d x %d", tw, th);
888 imguiValue(text);
889
890 // Max tiles and max polys affect how the tile IDs are caculated.
891 // There are 22 bits available for identifying a tile and a polygon.
892 int tileBits = rcMin((int)dtIlog2(dtNextPow2(tw*th*EXPECTED_LAYERS_PER_TILE)), 14);
893 if (tileBits > 14) tileBits = 14;
894 int polyBits = 22 - tileBits;
895 m_maxTiles = 1 << tileBits;
896 m_maxPolysPerTile = 1 << polyBits;
897 snprintf(text, 64, "Max Tiles %d", m_maxTiles);
898 imguiValue(text);
899 snprintf(text, 64, "Max Polys %d", m_maxPolysPerTile);
900 imguiValue(text);
901 gridSize = tw*th;
902 }
903 else
904 {
905 m_maxTiles = 0;
906 m_maxPolysPerTile = 0;
907 }
908
909 imguiSeparator();
910
911 imguiLabel("Tile Cache");
912 char msg[64];
913
914 const float compressionRatio = (float)m_cacheCompressedSize / (float)(m_cacheRawSize+1);
915
916 snprintf(msg, 64, "Layers %d", m_cacheLayerCount);
917 imguiValue(msg);
918 snprintf(msg, 64, "Layers (per tile) %.1f", (float)m_cacheLayerCount/(float)gridSize);
919 imguiValue(msg);
920
921 snprintf(msg, 64, "Memory %.1f kB / %.1f kB (%.1f%%)", m_cacheCompressedSize/1024.0f, m_cacheRawSize/1024.0f, compressionRatio*100.0f);
922 imguiValue(msg);
923 snprintf(msg, 64, "Navmesh Build Time %.1f ms", m_cacheBuildTimeMs);
924 imguiValue(msg);
925 snprintf(msg, 64, "Build Peak Mem Usage %.1f kB", m_cacheBuildMemUsage/1024.0f);
926 imguiValue(msg);
927
928 imguiSeparator();
929
930 imguiIndent();
931 imguiIndent();
932
933 if (imguiButton("Save"))
934 {
935 saveAll("all_tiles_tilecache.bin");
936 }
937
938 if (imguiButton("Load"))
939 {
940 dtFreeNavMesh(m_navMesh);
941 dtFreeTileCache(m_tileCache);
942 loadAll("all_tiles_tilecache.bin");
943 m_navQuery->init(m_navMesh, 2048);
944 }
945
946 imguiUnindent();
947 imguiUnindent();
948
949 imguiSeparator();
950 }
951
952 void Sample_TempObstacles::handleTools()
953 {
954 int type = !m_tool ? TOOL_NONE : m_tool->type();
955
956 if (imguiCheck("Test Navmesh", type == TOOL_NAVMESH_TESTER))
957 {
958 setTool(new NavMeshTesterTool);
959 }
960 if (imguiCheck("Highlight Tile Cache", type == TOOL_TILE_HIGHLIGHT))
961 {
962 setTool(new TempObstacleHilightTool);
963 }
964 if (imguiCheck("Create Temp Obstacles", type == TOOL_TEMP_OBSTACLE))
965 {
966 setTool(new TempObstacleCreateTool);
967 }
968 if (imguiCheck("Create Off-Mesh Links", type == TOOL_OFFMESH_CONNECTION))
969 {
970 setTool(new OffMeshConnectionTool);
971 }
972 if (imguiCheck("Create Convex Volumes", type == TOOL_CONVEX_VOLUME))
973 {
974 setTool(new ConvexVolumeTool);
975 }
976 if (imguiCheck("Create Crowds", type == TOOL_CROWD))
977 {
978 setTool(new CrowdTool);
979 }
980
981 imguiSeparatorLine();
982
983 imguiIndent();
984
985 if (m_tool)
986 m_tool->handleMenu();
987
988 imguiUnindent();
989 }
990
991 void Sample_TempObstacles::handleDebugMode()
992 {
993 // Check which modes are valid.
994 bool valid[MAX_DRAWMODE];
995 for (int i = 0; i < MAX_DRAWMODE; ++i)
996 valid[i] = false;
997
998 if (m_geom)
999 {
1000 valid[DRAWMODE_NAVMESH] = m_navMesh != 0;
1001 valid[DRAWMODE_NAVMESH_TRANS] = m_navMesh != 0;
1002 valid[DRAWMODE_NAVMESH_BVTREE] = m_navMesh != 0;
1003 valid[DRAWMODE_NAVMESH_NODES] = m_navQuery != 0;
1004 valid[DRAWMODE_NAVMESH_PORTALS] = m_navMesh != 0;
1005 valid[DRAWMODE_NAVMESH_INVIS] = m_navMesh != 0;
1006 valid[DRAWMODE_MESH] = true;
1007 valid[DRAWMODE_CACHE_BOUNDS] = true;
1008 }
1009
1010 int unavail = 0;
1011 for (int i = 0; i < MAX_DRAWMODE; ++i)
1012 if (!valid[i]) unavail++;
1013
1014 if (unavail == MAX_DRAWMODE)
1015 return;
1016
1017 imguiLabel("Draw");
1018 if (imguiCheck("Input Mesh", m_drawMode == DRAWMODE_MESH, valid[DRAWMODE_MESH]))
1019 m_drawMode = DRAWMODE_MESH;
1020 if (imguiCheck("Navmesh", m_drawMode == DRAWMODE_NAVMESH, valid[DRAWMODE_NAVMESH]))
1021 m_drawMode = DRAWMODE_NAVMESH;
1022 if (imguiCheck("Navmesh Invis", m_drawMode == DRAWMODE_NAVMESH_INVIS, valid[DRAWMODE_NAVMESH_INVIS]))
1023 m_drawMode = DRAWMODE_NAVMESH_INVIS;
1024 if (imguiCheck("Navmesh Trans", m_drawMode == DRAWMODE_NAVMESH_TRANS, valid[DRAWMODE_NAVMESH_TRANS]))
1025 m_drawMode = DRAWMODE_NAVMESH_TRANS;
1026 if (imguiCheck("Navmesh BVTree", m_drawMode == DRAWMODE_NAVMESH_BVTREE, valid[DRAWMODE_NAVMESH_BVTREE]))
1027 m_drawMode = DRAWMODE_NAVMESH_BVTREE;
1028 if (imguiCheck("Navmesh Nodes", m_drawMode == DRAWMODE_NAVMESH_NODES, valid[DRAWMODE_NAVMESH_NODES]))
1029 m_drawMode = DRAWMODE_NAVMESH_NODES;
1030 if (imguiCheck("Navmesh Portals", m_drawMode == DRAWMODE_NAVMESH_PORTALS, valid[DRAWMODE_NAVMESH_PORTALS]))
1031 m_drawMode = DRAWMODE_NAVMESH_PORTALS;
1032 if (imguiCheck("Cache Bounds", m_drawMode == DRAWMODE_CACHE_BOUNDS, valid[DRAWMODE_CACHE_BOUNDS]))
1033 m_drawMode = DRAWMODE_CACHE_BOUNDS;
1034
1035 if (unavail)
1036 {
1037 imguiValue("Tick 'Keep Itermediate Results'");
1038 imguiValue("rebuild some tiles to see");
1039 imguiValue("more debug mode options.");
1040 }
1041 }
1042
1043 void Sample_TempObstacles::handleRender()
1044 {
1045 if (!m_geom || !m_geom->getMesh())
1046 return;
1047
1048 const float texScale = 1.0f / (m_cellSize * 10.0f);
1049
1050 // Draw mesh
1051 if (m_drawMode != DRAWMODE_NAVMESH_TRANS)
1052 {
1053 // Draw mesh
1054 duDebugDrawTriMeshSlope(&m_dd, m_geom->getMesh()->getVerts(), m_geom->getMesh()->getVertCount(),
1055 m_geom->getMesh()->getTris(), m_geom->getMesh()->getNormals(), m_geom->getMesh()->getTriCount(),
1056 m_agentMaxSlope, texScale);
1057 m_geom->drawOffMeshConnections(&m_dd);
1058 }
1059
1060 if (m_tileCache && m_drawMode == DRAWMODE_CACHE_BOUNDS)
1061 drawTiles(&m_dd, m_tileCache);
1062
1063 if (m_tileCache)
1064 drawObstacles(&m_dd, m_tileCache);
1065
1066
1067 glDepthMask(GL_FALSE);
1068
1069 // Draw bounds
1070 const float* bmin = m_geom->getNavMeshBoundsMin();
1071 const float* bmax = m_geom->getNavMeshBoundsMax();
1072 duDebugDrawBoxWire(&m_dd, bmin[0],bmin[1],bmin[2], bmax[0],bmax[1],bmax[2], duRGBA(255,255,255,128), 1.0f);
1073
1074 // Tiling grid.
1075 int gw = 0, gh = 0;
1076 rcCalcGridSize(bmin, bmax, m_cellSize, &gw, &gh);
1077 const int tw = (gw + (int)m_tileSize-1) / (int)m_tileSize;
1078 const int th = (gh + (int)m_tileSize-1) / (int)m_tileSize;
1079 const float s = m_tileSize*m_cellSize;
1080 duDebugDrawGridXZ(&m_dd, bmin[0],bmin[1],bmin[2], tw,th, s, duRGBA(0,0,0,64), 1.0f);
1081
1082 if (m_navMesh && m_navQuery &&
1083 (m_drawMode == DRAWMODE_NAVMESH ||
1084 m_drawMode == DRAWMODE_NAVMESH_TRANS ||
1085 m_drawMode == DRAWMODE_NAVMESH_BVTREE ||
1086 m_drawMode == DRAWMODE_NAVMESH_NODES ||
1087 m_drawMode == DRAWMODE_NAVMESH_PORTALS ||
1088 m_drawMode == DRAWMODE_NAVMESH_INVIS))
1089 {
1090 if (m_drawMode != DRAWMODE_NAVMESH_INVIS)
1091 duDebugDrawNavMeshWithClosedList(&m_dd, *m_navMesh, *m_navQuery, m_navMeshDrawFlags/*|DU_DRAWNAVMESH_COLOR_TILES*/);
1092 if (m_drawMode == DRAWMODE_NAVMESH_BVTREE)
1093 duDebugDrawNavMeshBVTree(&m_dd, *m_navMesh);
1094 if (m_drawMode == DRAWMODE_NAVMESH_PORTALS)
1095 duDebugDrawNavMeshPortals(&m_dd, *m_navMesh);
1096 if (m_drawMode == DRAWMODE_NAVMESH_NODES)
1097 duDebugDrawNavMeshNodes(&m_dd, *m_navQuery);
1098 duDebugDrawNavMeshPolysWithFlags(&m_dd, *m_navMesh, SAMPLE_POLYFLAGS_DISABLED, duRGBA(0,0,0,128));
1099 }
1100
1101
1102 glDepthMask(GL_TRUE);
1103
1104 m_geom->drawConvexVolumes(&m_dd);
1105
1106 if (m_tool)
1107 m_tool->handleRender();
1108 renderToolStates();
1109
1110 glDepthMask(GL_TRUE);
1111 }
1112
1113 void Sample_TempObstacles::renderCachedTile(const int tx, const int ty, const int type)
1114 {
1115 if (m_tileCache)
1116 drawDetail(&m_dd,m_tileCache,tx,ty,type);
1117 }
1118
1119 void Sample_TempObstacles::renderCachedTileOverlay(const int tx, const int ty, double* proj, double* model, int* view)
1120 {
1121 if (m_tileCache)
1122 drawDetailOverlay(m_tileCache, tx, ty, proj, model, view);
1123 }
1124
1125 void Sample_TempObstacles::handleRenderOverlay(double* proj, double* model, int* view)
1126 {
1127 if (m_tool)
1128 m_tool->handleRenderOverlay(proj, model, view);
1129 renderOverlayToolStates(proj, model, view);
1130
1131 // Stats
1132 /* imguiDrawRect(280,10,300,100,imguiRGBA(0,0,0,64));
1133
1134 char text[64];
1135 int y = 110-30;
1136
1137 snprintf(text,64,"Lean Data: %.1fkB", m_tileCache->getRawSize()/1024.0f);
1138 imguiDrawText(300, y, IMGUI_ALIGN_LEFT, text, imguiRGBA(255,255,255,255));
1139 y -= 20;
1140
1141 snprintf(text,64,"Compressed: %.1fkB (%.1f%%)", m_tileCache->getCompressedSize()/1024.0f,
1142 m_tileCache->getRawSize() > 0 ? 100.0f*(float)m_tileCache->getCompressedSize()/(float)m_tileCache->getRawSize() : 0);
1143 imguiDrawText(300, y, IMGUI_ALIGN_LEFT, text, imguiRGBA(255,255,255,255));
1144 y -= 20;
1145
1146 if (m_rebuildTileCount > 0 && m_rebuildTime > 0.0f)
1147 {
1148 snprintf(text,64,"Changed obstacles, rebuild %d tiles: %.3f ms", m_rebuildTileCount, m_rebuildTime);
1149 imguiDrawText(300, y, IMGUI_ALIGN_LEFT, text, imguiRGBA(255,192,0,255));
1150 y -= 20;
1151 }
1152 */
1153 }
1154
1155 void Sample_TempObstacles::handleMeshChanged(class InputGeom* geom)
1156 {
1157 Sample::handleMeshChanged(geom);
1158
1159 dtFreeTileCache(m_tileCache);
1160 m_tileCache = 0;
1161
1162 dtFreeNavMesh(m_navMesh);
1163 m_navMesh = 0;
1164
1165 if (m_tool)
1166 {
1167 m_tool->reset();
1168 m_tool->init(this);
1169 m_tmproc->init(m_geom);
1170 }
1171 resetToolStates();
1172 initToolStates(this);
1173 }
1174
1175 void Sample_TempObstacles::addTempObstacle(const float* pos)
1176 {
1177 if (!m_tileCache)
1178 return;
1179 float p[3];
1180 dtVcopy(p, pos);
1181 p[1] -= 0.5f;
1182 m_tileCache->addObstacle(p, 1.0f, 2.0f, 0);
1183 }
1184
1185 void Sample_TempObstacles::removeTempObstacle(const float* sp, const float* sq)
1186 {
1187 if (!m_tileCache)
1188 return;
1189 dtObstacleRef ref = hitTestObstacle(m_tileCache, sp, sq);
1190 m_tileCache->removeObstacle(ref);
1191 }
1192
1193 void Sample_TempObstacles::clearAllTempObstacles()
1194 {
1195 if (!m_tileCache)
1196 return;
1197 for (int i = 0; i < m_tileCache->getObstacleCount(); ++i)
1198 {
1199 const dtTileCacheObstacle* ob = m_tileCache->getObstacle(i);
1200 if (ob->state == DT_OBSTACLE_EMPTY) continue;
1201 m_tileCache->removeObstacle(m_tileCache->getObstacleRef(ob));
1202 }
1203 }
1204
1205 bool Sample_TempObstacles::handleBuild()
1206 {
1207 dtStatus status;
1208
1209 if (!m_geom || !m_geom->getMesh())
1210 {
1211 m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: No vertices and triangles.");
1212 return false;
1213 }
1214
1215 m_tmproc->init(m_geom);
1216
1217 // Init cache
1218 const float* bmin = m_geom->getNavMeshBoundsMin();
1219 const float* bmax = m_geom->getNavMeshBoundsMax();
1220 int gw = 0, gh = 0;
1221 rcCalcGridSize(bmin, bmax, m_cellSize, &gw, &gh);
1222 const int ts = (int)m_tileSize;
1223 const int tw = (gw + ts-1) / ts;
1224 const int th = (gh + ts-1) / ts;
1225
1226 // Generation params.
1227 rcConfig cfg;
1228 memset(&cfg, 0, sizeof(cfg));
1229 cfg.cs = m_cellSize;
1230 cfg.ch = m_cellHeight;
1231 cfg.walkableSlopeAngle = m_agentMaxSlope;
1232 cfg.walkableHeight = (int)ceilf(m_agentHeight / cfg.ch);
1233 cfg.walkableClimb = (int)floorf(m_agentMaxClimb / cfg.ch);
1234 cfg.walkableRadius = (int)ceilf(m_agentRadius / cfg.cs);
1235 cfg.maxEdgeLen = (int)(m_edgeMaxLen / m_cellSize);
1236 cfg.maxSimplificationError = m_edgeMaxError;
1237 cfg.minRegionArea = (int)rcSqr(m_regionMinSize); // Note: area = size*size
1238 cfg.mergeRegionArea = (int)rcSqr(m_regionMergeSize); // Note: area = size*size
1239 cfg.maxVertsPerPoly = (int)m_vertsPerPoly;
1240 cfg.tileSize = (int)m_tileSize;
1241 cfg.borderSize = cfg.walkableRadius + 3; // Reserve enough padding.
1242 cfg.width = cfg.tileSize + cfg.borderSize*2;
1243 cfg.height = cfg.tileSize + cfg.borderSize*2;
1244 cfg.detailSampleDist = m_detailSampleDist < 0.9f ? 0 : m_cellSize * m_detailSampleDist;
1245 cfg.detailSampleMaxError = m_cellHeight * m_detailSampleMaxError;
1246 rcVcopy(cfg.bmin, bmin);
1247 rcVcopy(cfg.bmax, bmax);
1248
1249 // Tile cache params.
1250 dtTileCacheParams tcparams;
1251 memset(&tcparams, 0, sizeof(tcparams));
1252 rcVcopy(tcparams.orig, bmin);
1253 tcparams.cs = m_cellSize;
1254 tcparams.ch = m_cellHeight;
1255 tcparams.width = (int)m_tileSize;
1256 tcparams.height = (int)m_tileSize;
1257 tcparams.walkableHeight = m_agentHeight;
1258 tcparams.walkableRadius = m_agentRadius;
1259 tcparams.walkableClimb = m_agentMaxClimb;
1260 tcparams.maxSimplificationError = m_edgeMaxError;
1261 tcparams.maxTiles = tw*th*EXPECTED_LAYERS_PER_TILE;
1262 tcparams.maxObstacles = 128;
1263
1264 dtFreeTileCache(m_tileCache);
1265
1266 m_tileCache = dtAllocTileCache();
1267 if (!m_tileCache)
1268 {
1269 m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not allocate tile cache.");
1270 return false;
1271 }
1272 status = m_tileCache->init(&tcparams, m_talloc, m_tcomp, m_tmproc);
1273 if (dtStatusFailed(status))
1274 {
1275 m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not init tile cache.");
1276 return false;
1277 }
1278
1279 dtFreeNavMesh(m_navMesh);
1280
1281 m_navMesh = dtAllocNavMesh();
1282 if (!m_navMesh)
1283 {
1284 m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not allocate navmesh.");
1285 return false;
1286 }
1287
1288 dtNavMeshParams params;
1289 memset(&params, 0, sizeof(params));
1290 rcVcopy(params.orig, bmin);
1291 params.tileWidth = m_tileSize*m_cellSize;
1292 params.tileHeight = m_tileSize*m_cellSize;
1293 params.maxTiles = m_maxTiles;
1294 params.maxPolys = m_maxPolysPerTile;
1295
1296 status = m_navMesh->init(&params);
1297 if (dtStatusFailed(status))
1298 {
1299 m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not init navmesh.");
1300 return false;
1301 }
1302
1303 status = m_navQuery->init(m_navMesh, 2048);
1304 if (dtStatusFailed(status))
1305 {
1306 m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not init Detour navmesh query");
1307 return false;
1308 }
1309
1310
1311 // Preprocess tiles.
1312
1313 m_ctx->resetTimers();
1314
1315 m_cacheLayerCount = 0;
1316 m_cacheCompressedSize = 0;
1317 m_cacheRawSize = 0;
1318
1319 for (int y = 0; y < th; ++y)
1320 {
1321 for (int x = 0; x < tw; ++x)
1322 {
1323 TileCacheData tiles[MAX_LAYERS];
1324 memset(tiles, 0, sizeof(tiles));
1325 int ntiles = rasterizeTileLayers(x, y, cfg, tiles, MAX_LAYERS);
1326
1327 for (int i = 0; i < ntiles; ++i)
1328 {
1329 TileCacheData* tile = &tiles[i];
1330 status = m_tileCache->addTile(tile->data, tile->dataSize, DT_COMPRESSEDTILE_FREE_DATA, 0);
1331 if (dtStatusFailed(status))
1332 {
1333 dtFree(tile->data);
1334 tile->data = 0;
1335 continue;
1336 }
1337
1338 m_cacheLayerCount++;
1339 m_cacheCompressedSize += tile->dataSize;
1340 m_cacheRawSize += calcLayerBufferSize(tcparams.width, tcparams.height);
1341 }
1342 }
1343 }
1344
1345 // Build initial meshes
1346 m_ctx->startTimer(RC_TIMER_TOTAL);
1347 for (int y = 0; y < th; ++y)
1348 for (int x = 0; x < tw; ++x)
1349 m_tileCache->buildNavMeshTilesAt(x,y, m_navMesh);
1350 m_ctx->stopTimer(RC_TIMER_TOTAL);
1351
1352 m_cacheBuildTimeMs = m_ctx->getAccumulatedTime(RC_TIMER_TOTAL)/1000.0f;
1353 m_cacheBuildMemUsage = static_cast<unsigned int>(m_talloc->high);
1354
1355
1356 const dtNavMesh* nav = m_navMesh;
1357 int navmeshMemUsage = 0;
1358 for (int i = 0; i < nav->getMaxTiles(); ++i)
1359 {
1360 const dtMeshTile* tile = nav->getTile(i);
1361 if (tile->header)
1362 navmeshMemUsage += tile->dataSize;
1363 }
1364 printf("navmeshMemUsage = %.1f kB", navmeshMemUsage/1024.0f);
1365
1366
1367 if (m_tool)
1368 m_tool->init(this);
1369 initToolStates(this);
1370
1371 return true;
1372 }
1373
1374 void Sample_TempObstacles::handleUpdate(const float dt)
1375 {
1376 Sample::handleUpdate(dt);
1377
1378 if (!m_navMesh)
1379 return;
1380 if (!m_tileCache)
1381 return;
1382
1383 m_tileCache->update(dt, m_navMesh);
1384 }
1385
1386 void Sample_TempObstacles::getTilePos(const float* pos, int& tx, int& ty)
1387 {
1388 if (!m_geom) return;
1389
1390 const float* bmin = m_geom->getNavMeshBoundsMin();
1391
1392 const float ts = m_tileSize*m_cellSize;
1393 tx = (int)((pos[0] - bmin[0]) / ts);
1394 ty = (int)((pos[2] - bmin[2]) / ts);
1395 }
1396
1397 static const int TILECACHESET_MAGIC = 'T'<<24 | 'S'<<16 | 'E'<<8 | 'T'; //'TSET';
1398 static const int TILECACHESET_VERSION = 1;
1399
1400 struct TileCacheSetHeader
1401 {
1402 int magic;
1403 int version;
1404 int numTiles;
1405 dtNavMeshParams meshParams;
1406 dtTileCacheParams cacheParams;
1407 };
1408
1409 struct TileCacheTileHeader
1410 {
1411 dtCompressedTileRef tileRef;
1412 int dataSize;
1413 };
1414
1415 void Sample_TempObstacles::saveAll(const char* path)
1416 {
1417 if (!m_tileCache) return;
1418
1419 FILE* fp = fopen(path, "wb");
1420 if (!fp)
1421 return;
1422
1423 // Store header.
1424 TileCacheSetHeader header;
1425 header.magic = TILECACHESET_MAGIC;
1426 header.version = TILECACHESET_VERSION;
1427 header.numTiles = 0;
1428 for (int i = 0; i < m_tileCache->getTileCount(); ++i)
1429 {
1430 const dtCompressedTile* tile = m_tileCache->getTile(i);
1431 if (!tile || !tile->header || !tile->dataSize) continue;
1432 header.numTiles++;
1433 }
1434 memcpy(&header.cacheParams, m_tileCache->getParams(), sizeof(dtTileCacheParams));
1435 memcpy(&header.meshParams, m_navMesh->getParams(), sizeof(dtNavMeshParams));
1436 fwrite(&header, sizeof(TileCacheSetHeader), 1, fp);
1437
1438 // Store tiles.
1439 for (int i = 0; i < m_tileCache->getTileCount(); ++i)
1440 {
1441 const dtCompressedTile* tile = m_tileCache->getTile(i);
1442 if (!tile || !tile->header || !tile->dataSize) continue;
1443
1444 TileCacheTileHeader tileHeader;
1445 tileHeader.tileRef = m_tileCache->getTileRef(tile);
1446 tileHeader.dataSize = tile->dataSize;
1447 fwrite(&tileHeader, sizeof(tileHeader), 1, fp);
1448
1449 fwrite(tile->data, tile->dataSize, 1, fp);
1450 }
1451
1452 fclose(fp);
1453 }
1454
1455 void Sample_TempObstacles::loadAll(const char* path)
1456 {
1457 FILE* fp = fopen(path, "rb");
1458 if (!fp) return;
1459
1460 // Read header.
1461 TileCacheSetHeader header;
1462 size_t headerReadReturnCode = fread(&header, sizeof(TileCacheSetHeader), 1, fp);
1463 if( headerReadReturnCode != 1)
1464 {
1465 // Error or early EOF
1466 fclose(fp);
1467 return;
1468 }
1469 if (header.magic != TILECACHESET_MAGIC)
1470 {
1471 fclose(fp);
1472 return;
1473 }
1474 if (header.version != TILECACHESET_VERSION)
1475 {
1476 fclose(fp);
1477 return;
1478 }
1479
1480 m_navMesh = dtAllocNavMesh();
1481 if (!m_navMesh)
1482 {
1483 fclose(fp);
1484 return;
1485 }
1486 dtStatus status = m_navMesh->init(&header.meshParams);
1487 if (dtStatusFailed(status))
1488 {
1489 fclose(fp);
1490 return;
1491 }
1492
1493 m_tileCache = dtAllocTileCache();
1494 if (!m_tileCache)
1495 {
1496 fclose(fp);
1497 return;
1498 }
1499 status = m_tileCache->init(&header.cacheParams, m_talloc, m_tcomp, m_tmproc);
1500 if (dtStatusFailed(status))
1501 {
1502 fclose(fp);
1503 return;
1504 }
1505
1506 // Read tiles.
1507 for (int i = 0; i < header.numTiles; ++i)
1508 {
1509 TileCacheTileHeader tileHeader;
1510 size_t tileHeaderReadReturnCode = fread(&tileHeader, sizeof(tileHeader), 1, fp);
1511 if( tileHeaderReadReturnCode != 1)
1512 {
1513 // Error or early EOF
1514 fclose(fp);
1515 return;
1516 }
1517 if (!tileHeader.tileRef || !tileHeader.dataSize)
1518 break;
1519
1520 unsigned char* data = (unsigned char*)dtAlloc(tileHeader.dataSize, DT_ALLOC_PERM);
1521 if (!data) break;
1522 memset(data, 0, tileHeader.dataSize);
1523 size_t tileDataReadReturnCode = fread(data, tileHeader.dataSize, 1, fp);
1524 if( tileDataReadReturnCode != 1)
1525 {
1526 // Error or early EOF
1527 dtFree(data);
1528 fclose(fp);
1529 return;
1530 }
1531
1532 dtCompressedTileRef tile = 0;
1533 dtStatus addTileStatus = m_tileCache->addTile(data, tileHeader.dataSize, DT_COMPRESSEDTILE_FREE_DATA, &tile);
1534 if (dtStatusFailed(addTileStatus))
1535 {
1536 dtFree(data);
1537 }
1538
1539 if (tile)
1540 m_tileCache->buildNavMeshTile(tile, m_navMesh);
1541 }
1542
1543 fclose(fp);
1544 }