Subversion Repository Public Repository

Divide-Framework

This repository has no backups
This repository's network speed is throttled to 100KB/sec

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
#include "Headers/NavMesh.h"
#include "Headers/NavMeshDebugDraw.h"

#include <SimpleIni.h>
#include "Core/Headers/ParamHandler.h"
#include "Managers/Headers/SceneManager.h"

#include <DebugUtils/Include/RecastDump.h>
#include <DebugUtils/Include/DetourDebugDraw.h>
#include <DebugUtils/Include/RecastDebugDraw.h>

namespace Navigation {

    NavigationMesh::NavigationMesh() : GUIDWrapper() {
        ParamHandler& par = ParamHandler::getInstance();
		std::string path = par.getParam<std::string>("scriptLocation") + "/" +
				     par.getParam<std::string>("scenesLocation") + "/" +
					 par.getParam<std::string>("currentScene");

        _fileName   =  path + "/navMeshes/";
		_configFile = path + "/navMeshConfig.ini";
		_buildThreaded = true;
        _debugDraw = false;
        _renderConnections = false;
        _renderMode = RENDER_NAVMESH;
		_debugDrawInterface = New NavMeshDebugDraw();
		assert(_debugDrawInterface != NULL);
		_heightField  = NULL;
		_compactHeightField = NULL;
		_countourSet  = NULL;
		_polyMesh  = NULL;
		_polyMeshDetail = NULL;
		_navMesh  = NULL;
		_tempNavMesh = NULL;
		_building = false;
	}

	NavigationMesh::~NavigationMesh(){
		if(_buildThread) _buildThread->stopTask();

		freeIntermediates(true);
		dtFreeNavMesh(_navMesh);
		dtFreeNavMesh(_tempNavMesh);
		_navMesh = NULL;
		_tempNavMesh = NULL;
	}

	void NavigationMesh::freeIntermediates(bool freeAll){
		_navigationMeshLock.lock();

		rcFreeHeightField(_heightField);              
		rcFreeCompactHeightfield(_compactHeightField);
		_heightField = NULL;
		_compactHeightField = NULL;

		if(!_saveIntermediates || freeAll)	{
			rcFreeContourSet(_countourSet);        
			rcFreePolyMesh(_polyMesh);          
			rcFreePolyMeshDetail(_polyMeshDetail);  
			_countourSet = NULL;
			_polyMesh = NULL;
			_polyMeshDetail = NULL;
		}

		_navigationMeshLock.unlock();
	}

	bool NavigationMesh::loadConfigFromFile(){
		//Use SimpleIni library for cross-platform INI parsing
		CSimpleIniA ini;
		ini.SetUnicode();
		ini.LoadFile(_configFile.c_str());

        if(!ini.GetSection("Rasterization") ||
		   !ini.GetSection("Agent") ||
		   !ini.GetSection("Region") ||
		   !ini.GetSection("Polygonization") ||
		   !ini.GetSection("DetailMesh")) return false;
		
		//Load all key-value pairs for the "Rasterization" section
		_configParams.setCellSize(Util::convertData<F32,const char*>(ini.GetValue("Rasterization", "fCellSize", "0.3")));
		_configParams.setCellHeight(Util::convertData<F32, const char*>(ini.GetValue("Rasterization", "fCellHeight", "0.2")));
		_configParams.setTileSize(Util::convertData<I32,const char*>(ini.GetValue("Rasterization","iTileSize","48")));
		//Load all key-value pairs for the "Agent" section
		_configParams.setAgentHeight(Util::convertData<F32,const char*>(ini.GetValue("Agent", "fAgentHeight", "2.5")));
        _configParams.setAgentRadius(Util::convertData<F32,const char*>(ini.GetValue("Agent", "fAgentRadius", "0.5")));
		_configParams.setAgentMaxClimb(Util::convertData<F32,const char*>(ini.GetValue("Agent", "fAgentMaxClimb", "1")));
		_configParams.setAgentMaxSlope(Util::convertData<F32,const char*>(ini.GetValue("Agent", "fAgentMaxSlope", "20")));
		//Load all key-value pairs for the "Region" section
		_configParams.setRegionMergeSize(Util::convertData<F32,const char*>(ini.GetValue("Region", "fMergeSize", "20")));
		_configParams.setRegionMinSize(Util::convertData<F32,const char*>(ini.GetValue("Region", "fMinSize", "50")));
		//Load all key-value pairs for the "Polygonization" section
		_configParams.setEdgeMaxLen(Util::convertData<F32,const char*>(ini.GetValue("Polygonization", "fEdgeMaxLength", "12")));
		_configParams.setEdgeMaxError(Util::convertData<F32,const char*>(ini.GetValue("Polygonization", "fEdgeMaxError", "1.3")));
		_configParams.setVertsPerPoly(Util::convertData<I32,const char*>(ini.GetValue("Polygonization", "iVertsPerPoly", "6")));
		//Load all key-value pairs for the "DetailMesh" section
		_configParams.setDetailSampleDist(Util::convertData<F32,const char*>(ini.GetValue("DetailMesh", "fDetailSampleDist", "6")));
		_configParams.setDetailSampleMaxError(Util::convertData<F32,const char*>(ini.GetValue("DetailMesh", "fDetailSampleMaxError", "1")));
		_configParams.setKeepInterResults(Util::convertData<bool,const char*>(ini.GetValue("DetailMesh", "bKeepInterResults", "false")));

		return true;
	}

	bool NavigationMesh::build(SceneGraphNode* const sgn, bool threaded){
		if(!loadConfigFromFile()){
			ERROR_FN(Locale::get("NAV_MESH_CONFIG_NOT_FOUND"));
			return false;
		}

		_sgn = (sgn != NULL) ? sgn : _sgn = GET_ACTIVE_SCENEGRAPH()->getRoot();

		if(_buildThreaded && threaded) return buildThreaded();

		boost::mutex::scoped_lock(_buildLock);

        if(_buildThreaded && threaded){
		    if(!_buildLock.owns_lock()) return false;
        }else{
			return buildProcess();
		}
		return true;
	}

	bool NavigationMesh::buildThreaded(){
		boost::mutex::scoped_lock(_buildLock);
		if(!_buildLock.owns_lock()) return false;

		if(_buildThread) _buildThread->stopTask();
		
		Kernel* kernel = Application::getInstance().getKernel();
		_buildThread.reset(New Task(kernel->getThreadPool(),3,true,true,DELEGATE_BIND(&NavigationMesh::launchThreadedBuild,this)));

		return true;
	}

	void NavigationMesh::launchThreadedBuild(void *data){
		static_cast<NavigationMesh*>(data)->buildProcess();
	}

	bool NavigationMesh::buildProcess(){
		_building = true;
		// Create mesh
        U32 timeStart = GETMSTIME();
		bool success = generateMesh();
        U32 timeEnd = GETMSTIME();
        U32 timeDiff = timeEnd - timeStart;
        if(success){
            PRINT_FN(Locale::get("NAV_MESH_GENERATION_COMPLETE"),getMsToSec(timeDiff));
        }else{
            ERROR_FN(Locale::get("NAV_MESH_GENERATION_INCOMPLETE"),getMsToSec(timeDiff));
        }

		_navigationMeshLock.lock();
		// Copy new NavigationMesh into old.
		dtNavMesh *old = _navMesh;
		// I am trusting that this is atomic.
		_navMesh = _tempNavMesh; 
		dtFreeNavMesh(old);
		_debugDrawInterface->setDirty(true);
		_tempNavMesh = NULL;
		_navigationMeshLock.unlock();

		// Free structs used during build
		freeIntermediates(false);

		_building = false;

		return success;
	}

	bool NavigationMesh::generateMesh(){
		assert(_sgn != NULL);

        std::string nodeName((_sgn->getNode<SceneNode>()->getType() != TYPE_ROOT) ? "_node_[_" + _sgn->getName() + "_]" : "_root_node");
		// Parse objects from level into RC-compatible format
        _fileName.append(nodeName);
		_fileName.append(".nm");
        PRINT_FN(Locale::get("NAV_MESH_GENERATION_START"),nodeName.c_str());

		NavModelData data;
		std::string geometrySaveFile(_fileName);
		Util::replaceStringInPlace(geometrySaveFile,".nm",".ig");
				
		data.clear(false);
		data.setName(nodeName);

		if(!NavigationMeshLoader::loadMeshFile(data, geometrySaveFile.c_str())){
			if(!NavigationMeshLoader::parse(_sgn->getBoundingBox(), data, _sgn)){
				ERROR_FN(Locale::get("ERROR_NAV_PARSE_FAILED"), nodeName.c_str());
			}
		}

		// Check for no geometry
		if(!data.getVertCount()){
			data.isValid(false);
			return false;
		}

		// Free intermediate and final results
		freeIntermediates(true);
		// Recast initialisation data
		rcContextDivide ctx(true);

		rcConfig cfg;
		memset(&cfg, 0, sizeof(cfg));

		cfg.cs                     = _configParams.getCellSize();
		cfg.ch                     = _configParams.getCellHeight();
 		cfg.walkableHeight         = _configParams.base_getWalkableHeight();
		cfg.walkableClimb          = _configParams.base_getWalkableClimb();
		cfg.walkableRadius         = _configParams.base_getWalkableRadius();
		cfg.walkableSlopeAngle     = _configParams.getAgentMaxSlope();
		cfg.borderSize             = _configParams.base_getWalkableRadius()/* + (I32)BORDER_PADDING*/;
		cfg.detailSampleDist       = _configParams.getDetailSampleDist();
		cfg.detailSampleMaxError   = _configParams.getDetailSampleMaxError();
		cfg.maxEdgeLen             = _configParams.getEdgeMaxLen();
		cfg.maxSimplificationError = _configParams.getEdgeMaxError();
		cfg.maxVertsPerPoly        = _configParams.getVertsPerPoly();
		cfg.minRegionArea          = _configParams.getRegionMinSize();
		cfg.mergeRegionArea        = _configParams.getRegionMergeSize();
		cfg.tileSize               = _configParams.getTileSize();
		
		_saveIntermediates = _configParams.getKeepInterResults();
		rcCalcBounds(data.getVerts(), data.getVertCount(), cfg.bmin, cfg.bmax);
		rcCalcGridSize(cfg.bmin, cfg.bmax, cfg.cs, &cfg.width, &cfg.height);
		PRINT_FN(Locale::get("NAV_MESH_BOUNDS"),cfg.bmax[0],cfg.bmax[1],cfg.bmax[2],cfg.bmin[0],cfg.bmin[1],cfg.bmin[2]);

        if(!createPolyMesh(cfg, data, &ctx)){
            data.isValid(false);
		    return false;
        }

		//Detour initialisation data
		dtNavMeshCreateParams params;
		memset(&params, 0, sizeof(params));
		rcVcopy(params.bmax, cfg.bmax);
		rcVcopy(params.bmin, cfg.bmin);

		params.ch = cfg.ch;
		params.cs = cfg.cs;
		params.walkableHeight = cfg.walkableHeight;
		params.walkableRadius = cfg.walkableRadius;
		params.walkableClimb  = cfg.walkableClimb;

		params.tileX     = 0;
		params.tileY     = 0;
		params.tileLayer = 0;
		params.buildBvTree = true;

		params.verts     = _polyMesh->verts;
		params.vertCount = _polyMesh->nverts;
		params.polys     = _polyMesh->polys;
		params.polyAreas = _polyMesh->areas;
		params.polyFlags = _polyMesh->flags;
		params.polyCount = _polyMesh->npolys;
		params.nvp       = _polyMesh->nvp;

		params.detailMeshes     = _polyMeshDetail->meshes;
		params.detailVerts      = _polyMeshDetail->verts;
		params.detailVertsCount = _polyMeshDetail->nverts;
		params.detailTris       = _polyMeshDetail->tris;
		params.detailTriCount   = _polyMeshDetail->ntris;

        if(!createNavigationMesh(params)){
            data.isValid(false);
		    return false;
        }

		data.isValid(true);
		
		return NavigationMeshLoader::saveMeshFile(data, geometrySaveFile.c_str());//input geometry;
	}

	bool NavigationMesh::createPolyMesh(rcConfig &cfg, NavModelData &data, rcContextDivide *ctx){

        if(_fileName.empty())  _fileName = data.getName();
        
		// Create a heightfield to voxelise our input geometry
		_heightField = rcAllocHeightfield();

		if(!_heightField){
			ERROR_FN(Locale::get("ERROR_NAV_OUT_OF_MEMORY"), "rcAllocHeightfield", _fileName.c_str());
			return false;
		}

        // Reset build times gathering.
	    ctx->resetTimers();
    	// Start the build process.
	    ctx->startTimer(RC_TIMER_TOTAL);
		ctx->log(RC_LOG_PROGRESS, "Building navigation:");
	    ctx->log(RC_LOG_PROGRESS, " - %d x %d cells", cfg.width, cfg.height);
        ctx->log(RC_LOG_PROGRESS, " - %.1fK verts, %.1fK tris", data.getVertCount()/1000.0f, data.getTriCount()/1000.0f);

		if(!rcCreateHeightfield(ctx, *_heightField, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs, cfg.ch)){
			ERROR_FN(Locale::get("ERROR_NAV_HEIGHTFIELD"), _fileName.c_str());
			return false;
		}

		U8* areas = New U8[data.getTriCount()];

		if (!areas){
			ERROR_FN(Locale::get("ERROR_NAV_OUT_OF_MEMORY"), "areaFlag allocation", _fileName.c_str());
			return false;
		}

		memset(areas, 0, data.getTriCount()*sizeof(U8));

    	// Filter triangles by angle and rasterize
		rcMarkWalkableTriangles(ctx, 
								cfg.walkableSlopeAngle,
								data.getVerts(), 
								data.getVertCount(),
								data.getTris(),
								data.getTriCount(),
								areas);

		rcRasterizeTriangles(ctx,
						     data.getVerts(),
							 data.getVertCount(),
							 data.getTris(),
							 areas,
							 data.getTriCount(),
							 *_heightField,
							 cfg.walkableClimb);


		if(!_saveIntermediates)	SAFE_DELETE_ARRAY(areas);
		
		// Filter out areas with low ceilings and other stuff
		rcFilterLowHangingWalkableObstacles(ctx, 
										    cfg.walkableClimb,
											*_heightField);

		rcFilterLedgeSpans(ctx,
						   cfg.walkableHeight,
						   cfg.walkableClimb,
						   *_heightField);

		rcFilterWalkableLowHeightSpans(ctx,
									   cfg.walkableHeight,
									   *_heightField);

		_compactHeightField = rcAllocCompactHeightfield();

		if(!_compactHeightField || !rcBuildCompactHeightfield(ctx, 
															  cfg.walkableHeight,
															  cfg.walkableClimb,
															  *_heightField,
															  *_compactHeightField)){

			ERROR_FN(Locale::get("ERROR_NAV_COMPACT_HEIGHTFIELD"), _fileName.c_str());
			return false;
		}

		bool buildState =  rcErodeWalkableArea(ctx, 
											   cfg.walkableRadius,
											   *_compactHeightField);

		if(!buildState)	{
			ERROR_FN(Locale::get("ERROR_NAV_WALKABLE"), _fileName.c_str());
			return false;
		}

		if(false){
			buildState = rcBuildRegionsMonotone(ctx, 
												*_compactHeightField,
												cfg.borderSize,
												cfg.minRegionArea,
												cfg.mergeRegionArea);
			if(!buildState){
				ERROR_FN(Locale::get("ERROR_NAV_REGIONS"), _fileName.c_str());
				return false;
			}
		}else{
			buildState = rcBuildDistanceField(ctx, 
											  *_compactHeightField);
			if(!buildState)	return false;

			buildState = rcBuildRegions(ctx, 
										*_compactHeightField,
										cfg.borderSize, 
										cfg.minRegionArea, 
										cfg.mergeRegionArea);
			if(!buildState)	return false;
		}

		_countourSet = rcAllocContourSet();
		if(!_countourSet || !rcBuildContours(ctx, 
											 *_compactHeightField,
											 cfg.maxSimplificationError,
											 cfg.maxEdgeLen,
											 *_countourSet)){

			ERROR_FN(Locale::get("ERROR_NAV_COUNTOUR"), _fileName.c_str());
			return false;
		}

		_polyMesh = rcAllocPolyMesh();
		if(!_polyMesh || !rcBuildPolyMesh(ctx, 
										  *_countourSet,
										  cfg.maxVertsPerPoly,
										  *_polyMesh)){

			ERROR_FN(Locale::get("ERROR_NAV_POLY_MESH"), _fileName.c_str());
			return false;
		}

		_polyMeshDetail = rcAllocPolyMeshDetail();
		if(!_polyMeshDetail || !rcBuildPolyMeshDetail(ctx,
													  *_polyMesh,
													  *_compactHeightField,
													  cfg.detailSampleDist,
													  cfg.detailSampleMaxError,
													  *_polyMeshDetail)){

			ERROR_FN(Locale::get("ERROR_NAV_POLY_MESH_DETAIL"), _fileName.c_str());
			return false;
		}

		// Show performance stats.
        ctx->stopTimer(RC_TIMER_TOTAL);
	    duLogBuildTimes(*ctx, ctx->getAccumulatedTime(RC_TIMER_TOTAL));
	    ctx->log(RC_LOG_PROGRESS, ">> Polymesh: %d vertices  %d polygons", _polyMesh->nverts, _polyMesh->npolys);
	    F32 totalBuildTimeMs = (F32)ctx->getAccumulatedTime(RC_TIMER_TOTAL)/1000.0f;

	    PRINT_FN("[RC_LOG_PROGRESS] Polymesh: %d vertices  %d polygons %5.2f ms\n", _polyMesh->nverts, _polyMesh->npolys,totalBuildTimeMs);

		return true;
	}

	bool NavigationMesh::createNavigationMesh(dtNavMeshCreateParams &params){
		U8 *tileData = NULL;
		I32 tileDataSize = 0;
		if(!dtCreateNavMeshData(&params, &tileData, &tileDataSize)){
			ERROR_FN(Locale::get("ERROR_NAV_MESH_DATA"), _fileName.c_str());
			return false;
		}

		_tempNavMesh = dtAllocNavMesh();
		if(!_tempNavMesh){
			ERROR_FN(Locale::get("ERROR_NAV_DT_OUT_OF_MEMORY"), _fileName.c_str());
			return false;
		}

		dtStatus s = _tempNavMesh->init(tileData, tileDataSize, DT_TILE_FREE_DATA);
		if(dtStatusFailed(s)){
			ERROR_FN(Locale::get("ERROR_NAV_DT_INIT"), _fileName.c_str());
			return false;
		}

		// Initialise all flags to something helpful.
		for(U32 i = 0; i < (U32)_tempNavMesh->getMaxTiles(); ++i){
			const dtMeshTile* tile = ((const dtNavMesh*)_tempNavMesh)->getTile(i);

			if(!tile->header) continue;

			const dtPolyRef base = _tempNavMesh->getPolyRefBase(tile);

			for(U32 j = 0; j < (U32)tile->header->polyCount; ++j) {
				const dtPolyRef ref = base | j;
				U16 f = 0;
				_tempNavMesh->getPolyFlags(ref, &f);
				_tempNavMesh->setPolyFlags(ref, f | 1);
			}
		}

		return true;
	}
	
	void NavigationMesh::render(){

         RenderMode mode = _renderMode;

         if(_building) {

            mode = RENDER_NAVMESH;
            _debugDrawInterface->overrideColor(duRGBA(255, 0, 0, 80));
         }

		 _debugDrawInterface->beginBatch();

         _navigationMeshLock.lock();
         switch(mode)
         {
            case RENDER_NAVMESH:   
				if(_navMesh)        duDebugDrawNavMesh        (_debugDrawInterface, *_navMesh, 0);   
				break;
            case RENDER_CONTOURS:  
				if(_countourSet)    duDebugDrawContours       (_debugDrawInterface, *_countourSet);
				break;
            case RENDER_POLYMESH: 
				if(_polyMesh)       duDebugDrawPolyMesh       (_debugDrawInterface, *_polyMesh); 
				break;
            case RENDER_DETAILMESH:
				if(_polyMeshDetail) duDebugDrawPolyMeshDetail (_debugDrawInterface, *_polyMeshDetail);
				break;
            case RENDER_PORTALS: 
				if(_navMesh)        duDebugDrawNavMeshPortals (_debugDrawInterface, *_navMesh);  
				break;
         }

		 if(!_building){
			if(_countourSet && _renderConnections)   duDebugDrawRegionConnections(_debugDrawInterface, *_countourSet);
		 }

         _navigationMeshLock.unlock();

		 _debugDrawInterface->endBatch();
    }

#pragma message("ToDo: Enable file support for navMeshes! - Ionut")
	bool NavigationMesh::load(SceneGraphNode* const sgn){
		if(!_fileName.length()) return false;
		std::string file = _fileName;

		if(sgn == NULL){
			file.append("_root_node");
		}else{
			file.append("_node_[_" + sgn->getName() + "_]");
		}

		file.append(".nm");
		// Parse objects from level into RC-compatible format
		FILE* fp = fopen(file.c_str(), "rb");
		if(!fp) return false;

		// Read header.
		NavMeshSetHeader header;
		fread(&header, sizeof(NavMeshSetHeader), 1, fp);
			
		if(header.magic != NAVMESHSET_MAGIC){
			fclose(fp);
			return false;
		}

		if(header.version != NAVMESHSET_VERSION){
			fclose(fp);
			return false;
		}

		boost::mutex::scoped_lock(_navigationMeshLock);

		if(_navMesh) dtFreeNavMesh(_navMesh);

		_navMesh = dtAllocNavMesh();

		if(!_navMesh)	{
			fclose(fp);
			return false;
		}

		dtStatus status = _navMesh->init(&header.params);

		if(dtStatusFailed(status)){
			fclose(fp);
			return false;
		}

		// Read tiles.
		for(U32 i = 0; i < (U32)header.numTiles; ++i){
			NavMeshTileHeader tileHeader;
			fread(&tileHeader, sizeof(tileHeader), 1, fp);
			if(!tileHeader.tileRef || !tileHeader.dataSize) return false;//break;

			U8* data = (U8*)dtAlloc(tileHeader.dataSize, DT_ALLOC_PERM);

			if(!data) return false;//break;

			memset(data, 0, tileHeader.dataSize);
			fread(data, tileHeader.dataSize, 1, fp);

			_navMesh->addTile(data, tileHeader.dataSize, DT_TILE_FREE_DATA, tileHeader.tileRef, 0);
		}

		fclose(fp);

		return true;

	}

	bool NavigationMesh::save(){

		if(!_fileName.length() || !_navMesh) return false;

		// Save our NavigationMesh into a file to load from next time
		FILE* fp = fopen(_fileName.c_str(), "wb");
		if(!fp)	 return false;

		boost::mutex::scoped_lock(_navigationMeshLock);

		// Store header.
		NavMeshSetHeader header;
		header.magic = NAVMESHSET_MAGIC;
		header.version = NAVMESHSET_VERSION;
		header.numTiles = 0;

		for(U32 i = 0; i < (U32)_navMesh->getMaxTiles(); ++i)	{
			const dtMeshTile* tile = ((const dtNavMesh*)_navMesh)->getTile(i);

			if (!tile || !tile->header || !tile->dataSize) continue;
			header.numTiles++;
		}

		memcpy(&header.params, _navMesh->getParams(), sizeof(dtNavMeshParams));
		fwrite(&header, sizeof(NavMeshSetHeader), 1, fp);

		// Store tiles.
		for(U32 i = 0; i < (U32)_navMesh->getMaxTiles(); ++i)	{
			const dtMeshTile* tile = ((const dtNavMesh*)_navMesh)->getTile(i);

			if(!tile || !tile->header || !tile->dataSize) continue;

			NavMeshTileHeader tileHeader;
			tileHeader.tileRef = _navMesh->getTileRef(tile);
			tileHeader.dataSize = tile->dataSize;

			fwrite(&tileHeader, sizeof(tileHeader), 1, fp);
			fwrite(tile->data, tile->dataSize, 1, fp);
		}

		fclose(fp);

		return true;
	}
};

Commits for Divide-Framework/trunk/Source Code/AI/PathFinding/NavMeshes/NavMesh.cpp

Diff revisions: vs.
Revision Author Commited Message
168 Diff Diff k1ngp1n picture k1ngp1n Sat 26 Oct, 2013 19:03:21 +0000

- Reworked the Camera class[[BR]]
— Now fully quaternion based [[BR]]
— Basic camera types added but not used yet (third person, first person, orbit) [[BR]]
- Cleaned up Material and Texture handling [[BR]]
- Added clipping plane support [[BR]]
— Similar to OpenGL fixed-function clip planes but fully shader driven [[BR]]
— Added a new class, “Plane”, that helps define clip planes [[BR]]
- Optimized the Singleton class to allow faster “getInstance” calls without performance penalties [[BR]]
-- “createInstance” must be called for each singleton class before usage. Or “gerOrCreateInstance” can be used, which is basically the former “getInstance” implementation [[BR]]
- Improved console logging by changing some heap allocations to stack and removing dependencies on the std::string class [[BR]]
- Added a lot of performance optimizations related to coding standards and redundant calculations [[BR]]
— e.g. Frustum AABB check didn’t need to recompute the AABB points as they were calculated already [[BR]]
— e.g. A vector did not need to be set to 0 on initialization as that is already it’s default state on creation [[BR]]
— e.g. Faster Framerate and Timing calculations by using less member variables that are not needed outsied of calling functions [[BR]]
- The SceneState now contains the SceneRenderState and is passed on to the SceneGraph’s update calls [[BR]]
- Better material export/import to/from XML format [[BR]]
- More bug fixes and cleanups [[BR]]

163 Diff Diff k1ngp1n picture k1ngp1n Thu 18 Jul, 2013 12:24:26 +0000

[Ionut] [[BR]]
- Fixed a rendering bug with the previous terrain rendering system (number of strips was not calculated correctly. had to add the primitive restart indices to the list as well) [[BR]]
- Fixed a rendering bug with the previous double sided Quad3D patch (water planes should not be double sided. The first parameter of the bool mask of the resource descriptor for water planes now controls whether the Quad will be single or double sided) [[BR]]
- NavMesh debug draw now uses a caching system for rendering instead of re-submitting the same geometry every frame [[BR]]
— Fixed a bug that prevented GLIM primitives to be cached if they had “canZombify” set to false [[BR]]
- Navigation meshes are now saved and loaded from file on creation. Delete the “nm” file from the navMeshes subfolder to recreate a navigation mesh for a scene. [[BR]]
- LightManager is now a FrameListener. ShadowMap generation is called with the “FramePreRenderEnd” event [[BR]]
- Terrain NavMesh uses the lowest LoD possible for now to improve creation times until all bugs are resolved [[BR]]
- Geometry importer now uses the “replace” operation for the base texture of objects [[BR]]
- glUniformBufferObjects are now a little less dependent on the GLM library [[BR]]
- Primitive restart is now toggled on or off at each VAO draw call [[BR]]
- Some GFXDevice inlining [[BR]]

162 Diff Diff k1ngp1n picture k1ngp1n Mon 15 Jul, 2013 19:14:45 +0000

[Ionut] [[BR]]
- Improved terrain rendering a lot by using OpenGL’s primitive restart feature. Now terrain is rendered in n-draw calls where n is the number of terrain chunks in the quadtree (main scene has 4 chunks per terrain). [[BR]]
- Some terrain nav mesh generation code fixed. Still not 100% working [[BR]]

161 Diff Diff k1ngp1n picture k1ngp1n Fri 12 Jul, 2013 19:51:50 +0000

[Ionut] [[BR]]
- Solved Navigation Mesh creation from Object3D nodes [[BR]]

159 Diff Diff k1ngp1n picture k1ngp1n Tue 09 Jul, 2013 16:47:05 +0000

[Ionut] [[BR]]
- Added NavMesh config file for AITenisScene [[BR]]
- Improved ReCast debug logging [[BR]]
- Fixed Triangle Strip to Triangle List conversion [[BR]]
- Made Quad3D double-sided

158 Diff Diff k1ngp1n picture k1ngp1n Sun 07 Jul, 2013 17:52:10 +0000

[Ionut] [[BR]]
- Fixed a bug with NavMesh generation : triangles were using decremented indices (the original code used OBJ meshes as input, and those use ‘1’ as the first index instead of ‘0’) [[BR]]
- Fixed NavMesh debug draw (BeginBatch/EndBatch was called with every ‘Begin/End’ command from NavMeshDebugDraw thus reseting the IMEmulation primitive data) [[BR]]

157 Diff Diff k1ngp1n picture k1ngp1n Sat 06 Jul, 2013 00:07:09 +0000

[Ionut] [[BR]]
- Added per-scene ini config file for NavMesh creation [[BR]]
- Improved some IMEmulation cleanup code and fixed a memory leak with NavMesh debug rendering [[BR]]
- NavMesh debug rendering can now be toggled on/off in the Editor [[BR]]

156 Diff Diff k1ngp1n picture k1ngp1n Thu 04 Jul, 2013 21:50:54 +0000

[Ionut] [[BR]]
- More work on Navigation Mesh creation [[BR]]
- IMEmulation primitives were not recycled properly (old, unused primitives were saved, new ones were deleted and recreated – behavior reversed ) [[BR]]

152 Diff Diff k1ngp1n picture k1ngp1n Thu 20 Jun, 2013 14:23:31 +0000

[Ionut] [[BR]]
- New rendering pipeline (experimental and unstable): [[BR]]
— OpenGL 3.x clean context (glLight commands are still used for now, but UBO support is there, but not used yet) [[BR]]
— Custom matrix stacks and UBO based shader data (UBOs cause some link errors on some nVidia cards)[[BR]]
— Multi-threaded texture loading and shader compilation (mt shader compilation disabled for now. needs more tests) [[BR]]
— VAO rendering is self contained (no more enable/disable calls before a draw request) [[BR]]
— Render instance class used for rendering information [[BR]]
[[BR]]
- New unique ID generation base class: GUIDWrapper. Each class that derives from this, gets an application wide unique id on construction [[BR]]
- Added base code for an in-game editor using CEGUI [[BR]]
- Replaced some mutex locks with lockless data structures or atomic data [[BR]]
- CEGUI 0.8.2, FTGL-GL3 and GLIM 0.4 modified to support GLEW_MX if defined [[BR]]
- Dropped VS2008 support [[BR]]
- Networking library, server framework and ReCast files are now projects inside the Divide Framework solution [[BR]]
- New console command “setFov” that modifies the horizontal FoV value in realtime [[BR]]
- New console command “recompileShader” that reparses shader files, recompiles shaders and relinks shader programs who’s names match or contain the argument string [[BR]]
- New debug utility: axis angle drawn in corner of the screen if needed [[BR]]
- More ‘const’-s pasted around the code, more loop performance tweaks (allocations before a loop, tighter loops, etc), more utility member functions added to various classes [[BR]]

151 k1ngp1n picture k1ngp1n Tue 07 May, 2013 00:00:52 +0000

[Ionut] [[BR]]
- Better ReCast integration [[BR]]
— Any entity can be used as an obstacle in the NavMesh if that’s specified in each scene’s assets.xml file for said entity [[BR]]
— New console command, “createNavMesh”, that passes geometry data to ReCast [[BR]]
-— NavMesh generation is not yet complete [[BR]]
- Better PhysX integration [[BR]]
— Each scene passes data to and gets data from the Physics API better and safer[[BR]]
- Multi-threaded support extended: [[BR]]
— Event class replaced with Task [[BR]]
— Kernel uses a threadpool for scene tasks [[BR]]
— Each task can be added to a different threadpool if needed [[BR]]
— Most critical sections use the new boost::atomic wrapper for thread safety [[BR]]
- Rendering system updated [[BR]]
— VBO’s keep track of the geometry type internally [[BR]]
— Rendering by specific element list is internal to the VBO [[BR]]
— VBO’s can draw a “lite” version that doesn’t send Tangent, BiTangent and TexCoord data for depth rendering (disabled) [[BR]]
- Reflectors now offer a preview of the generated reflective texture if needed [[BR]]
- Buttons are now added and rendered by CEGUI [[BR]]
[[BR]]
Deprecation: [[BR]]
- Removed fixed pipeline material system [[BR]]
- Removed BoundingBox late update system [[BR]]
- Shadow references in the material system are now depth references [[BR]]
[[BR]]
Bug fixes: [[BR]]
- Problematic FBO double bind check removed [[BR]]
- Faster terrain rendering via chunk size selection through each scene’s terrain.xml[[BR]]
- Rendering is paused when the window is minimized [[BR]]
- CEGUI and impostors now render properly in deferred rendering mode [[BR]]
- Fixed various level 4 (VS2008) warnings [[BR]]
- Better state management and cleaning [[BR]]
- Better SceneGraph node management and trasformation/AABB update calls [[BR]]
- AITenisScene has proper collisions now [[BR]]