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
#include "Headers/NavMeshLoader.h"

#include "Core/Headers/ParamHandler.h"
#include "Core/Math/Headers/Transform.h"
#include "Managers/Headers/SceneManager.h"
#include "Geometry/Shapes/Headers/Object3D.h"
#include "Environment/Terrain/Headers/Terrain.h"
#include "Environment/Water/Headers/Water.h"

#include <fstream>

namespace Divide {
namespace AI {
namespace Navigation {
namespace NavigationMeshLoader {
static vec3<F32> _minVertValue, _maxVertValue;
static const U32 cubeFaces[6][4] = {{0, 4, 6, 2},
                                    {0, 2, 3, 1},
                                    {0, 1, 5, 4},
                                    {3, 2, 6, 7},
                                    {7, 6, 4, 5},
                                    {3, 7, 5, 1}};

char* parseRow(char* buf, char* bufEnd, char* row, I32 len) {
    bool cont = false;
    bool start = true;
    bool done = false;
    I32 n = 0;

    while (!done && buf < bufEnd) {
        char c = *buf;
        buf++;
        // multi row
        switch (c) {
            case '\\':
                cont = true;
                break;  // multi row
            case '\n': {
                if (start) break;
                done = true;
            } break;
            case '\r':
                break;
            case '\t':
            case ' ':
                if (start) break;
            default: {
                start = false;
                cont = false;
                row[n++] = c;
                if (n >= len - 1) done = true;
            } break;
        }
    }
    row[n] = '\0';
    return buf;
}

I32 parseFace(char* row, I32* data, I32 n, I32 vcnt) {
    I32 j = 0;
    while (*row != '\0') {
        // Skip initial white space
        while (*row != '\0' && (*row == ' ' || *row == '\t')) row++;
        char* s = row;
        // Find vertex delimiter and terminated the string there for conversion.
        while (*row != '\0' && *row != ' ' && *row != '\t') {
            if (*row == '/') *row = '\0';
            row++;
        }

        if (*s == '\0') continue;

        I32 vi = atoi(s);
        data[j++] = vi < 0 ? vi + vcnt : vi - 1;
        if (j >= n) return j;
    }
    return j;
}

bool loadMeshFile(NavModelData& outData, const char* filename) {
    FILE* fp = fopen(filename, "rb");
    if (!fp) return false;

    outData.setName(filename);
    fseek(fp, 0, SEEK_END);

    I32 bufSize = ftell(fp);
    fseek(fp, 0, SEEK_SET);

    char* buf = MemoryManager_NEW char[bufSize];
    if (!buf) {
        fclose(fp);
        return false;
    }

    fread(buf, bufSize, 1, fp);
    fclose(fp);

    char* src = buf;
    char* srcEnd = buf + bufSize;
    char row[512];
    I32 face[32];
    F32 x, y, z;
    I32 nv;
    I32 result;
    while (src < srcEnd) {
        // Parse one row
        row[0] = '\0';
        src = parseRow(src, srcEnd, row, sizeof(row) / sizeof(char));
        // Skip comments
        if (row[0] == '#') continue;

        if (row[0] == 'v' && row[1] != 'n' && row[1] != 't') {
            // Vertex pos
            result = sscanf(row + 1, "%f %f %f", &x, &y, &z);
            if (result != 0) addVertex(&outData, vec3<F32>(x, y, z));
        }
        if (row[0] == 'f') {
            // Faces
            nv = parseFace(row + 1, face, 32, outData._vertexCount);
            for (I32 i = 2; i < nv; ++i) {
                const I32 a = face[0];
                const I32 b = face[i - 1];
                const I32 c = face[i];
                if (a < 0 || a >= (I32)outData._vertexCount || b < 0 ||
                    b >= (I32)outData._vertexCount || c < 0 ||
                    c >= (I32)outData._vertexCount) {
                    continue;
                }

                addTriangle(&outData, vec3<U32>(a, b, c));
            }
        }
    }

    MemoryManager::DELETE_ARRAY(buf);

    // Calculate normals.
    outData._normals = MemoryManager_NEW F32[outData._triangleCount * 3];

    for (I32 i = 0; i < (I32)outData._triangleCount * 3; i += 3) {
        const F32* v0 = &outData._vertices[outData._triangles[i] * 3];
        const F32* v1 = &outData._vertices[outData._triangles[i + 1] * 3];
        const F32* v2 = &outData._vertices[outData._triangles[i + 2] * 3];

        F32 e0[3], e1[3];
        for (I32 j = 0; j < 3; ++j) {
            e0[j] = v1[j] - v0[j];
            e1[j] = v2[j] - v0[j];
        }

        F32* n = &outData._normals[i];
        n[0] = e0[1] * e1[2] - e0[2] * e1[1];
        n[1] = e0[2] * e1[0] - e0[0] * e1[2];
        n[2] = e0[0] * e1[1] - e0[1] * e1[0];
        F32 d = sqrtf(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]);
        if (d > 0) {
            d = 1.0f / d;
            n[0] *= d;
            n[1] *= d;
            n[2] *= d;
        }
    }

    return true;
}

bool saveMeshFile(const NavModelData& inData, const char* filename) {
    if (!inData.getVertCount() || !inData.getTriCount()) return false;

    // Create the file if it doesn't exists
    FILE* fp = nullptr;
    fopen_s(&fp, filename, "w");
    if (fp) fclose(fp);

    std::ofstream myfile;
    myfile.open(filename);
    if (!myfile.is_open()) return false;

    F32* vstart = inData._vertices;
    I32* tstart = inData._triangles;
    for (U32 i = 0; i < inData.getVertCount(); i++) {
        F32* vp = vstart + i * 3;
        myfile << "v " << (*(vp)) << " " << *(vp + 1) << " " << (*(vp + 2))
               << "\n";
    }
    for (U32 i = 0; i < inData.getTriCount(); i++) {
        I32* tp = tstart + i * 3;
        myfile << "f " << (*(tp) + 1) << " " << (*(tp + 1) + 1) << " "
               << (*(tp + 2) + 1) << "\n";
    }

    myfile.close();
    return true;
}

NavModelData mergeModels(NavModelData& a, NavModelData& b,
                         bool delOriginals /* = false*/) {
    NavModelData mergedData;
    if (a.getVerts() || b.getVerts()) {
        if (!a.getVerts())
            return b;
        else if (!b.getVerts())
            return a;

        mergedData.clear();

        I32 totalVertCt = (a.getVertCount() + b.getVertCount());
        I32 newCap = 8;

        while (newCap < totalVertCt) newCap *= 2;

        mergedData._vertices = MemoryManager_NEW F32[newCap * 3];
        mergedData._vertexCapacity = newCap;
        mergedData._vertexCount = totalVertCt;

        memcpy(mergedData._vertices, a.getVerts(),
               a.getVertCount() * 3 * sizeof(F32));
        memcpy(mergedData._vertices + a.getVertCount() * 3, b.getVerts(),
               b.getVertCount() * 3 * sizeof(F32));

        I32 totalTriCt = (a.getTriCount() + b.getTriCount());
        newCap = 8;

        while (newCap < totalTriCt) newCap *= 2;

        mergedData._triangles = MemoryManager_NEW I32[newCap * 3];
        mergedData._triangleCapacity = newCap;
        mergedData._triangleCount = totalTriCt;
        I32 aFaceSize = a.getTriCount() * 3;
        memcpy(mergedData._triangles, a.getTris(), aFaceSize * sizeof(I32));

        I32 bFaceSize = b.getTriCount() * 3;
        I32* bFacePt = mergedData._triangles +
                       a.getTriCount() * 3;  // i like pointing at faces
        memcpy(bFacePt, b.getTris(), bFaceSize * sizeof(I32));

        for (U32 i = 0; i < (U32)bFaceSize; i++)
            *(bFacePt + i) += a.getVertCount();

        if (mergedData._vertexCount > 0) {
            if (delOriginals) {
                a.clear();
                b.clear();
            }
        } else
            mergedData.clear();
    }

    mergedData.setName(a.getName() + "+" + b.getName());
    return mergedData;
}

void addVertex(NavModelData* modelData, const vec3<F32>& vertex) {
    if (modelData->getVertCount() + 1 > modelData->_vertexCapacity) {
        modelData->_vertexCapacity =
            !modelData->_vertexCapacity ? 8 : modelData->_vertexCapacity * 2;

        F32* nv = MemoryManager_NEW F32[modelData->_vertexCapacity * 3];

        if (modelData->getVertCount()) {
            memcpy(nv, modelData->getVerts(),
                   modelData->getVertCount() * 3 * sizeof(F32));
        }
        if (modelData->getVerts()) {
            MemoryManager::DELETE_ARRAY(modelData->_vertices);
        }
        modelData->_vertices = nv;
    }

    F32* dst = &modelData->_vertices[modelData->getVertCount() * 3];
    *dst++ = vertex.x;
    *dst++ = vertex.y;
    *dst++ = vertex.z;

    modelData->_vertexCount++;
}

void addTriangle(NavModelData* modelData, const vec3<U32>& triangleIndices,
                 U32 triangleIndexOffset, const SamplePolyAreas& areaType) {
    if (modelData->getTriCount() + 1 > modelData->_triangleCapacity) {
        modelData->_triangleCapacity = !modelData->_triangleCapacity
                                           ? 8
                                           : modelData->_triangleCapacity * 2;
        I32* nv = MemoryManager_NEW I32[modelData->_triangleCapacity * 3];

        if (modelData->getTriCount()) {
            memcpy(nv, modelData->_triangles,
                   modelData->getTriCount() * 3 * sizeof(I32));
        }
        if (modelData->getTris()) {
            MemoryManager::DELETE_ARRAY(modelData->_triangles);
        }
        modelData->_triangles = nv;
    }

    I32* dst = &modelData->_triangles[modelData->getTriCount() * 3];

    *dst++ = static_cast<I32>(triangleIndices.x + triangleIndexOffset);
    *dst++ = static_cast<I32>(triangleIndices.y + triangleIndexOffset);
    *dst++ = static_cast<I32>(triangleIndices.z + triangleIndexOffset);

    modelData->getAreaTypes().push_back(areaType);
    modelData->_triangleCount++;
}

const vec3<F32> borderOffset(BORDER_PADDING);
bool parse(const BoundingBox& box, NavModelData& outData, SceneGraphNode* sgn) {
    assert(sgn != nullptr);

    if (sgn->getComponent<NavigationComponent>()->navigationContext() !=
            NavigationComponent::NODE_IGNORE &&  // Ignore if specified
        box.getHeight() > 0.05f)  // Skip small objects
    {
        SceneNode* sn = sgn->getNode();

        SceneNodeType nodeType = sn->getType();
        U32 ignoredNodeType = enum_to_uint(SceneNodeType::TYPE_ROOT) |
                              enum_to_uint(SceneNodeType::TYPE_LIGHT) |
                              enum_to_uint(SceneNodeType::TYPE_PARTICLE_EMITTER) |
                              enum_to_uint(SceneNodeType::TYPE_TRIGGER) | 
                              enum_to_uint(SceneNodeType::TYPE_SKY) | 
                              enum_to_uint(SceneNodeType::TYPE_VEGETATION_GRASS);

        U32 allowedNodeType =
            enum_to_uint(SceneNodeType::TYPE_WATER) |
            enum_to_uint(SceneNodeType::TYPE_OBJECT3D) |
            enum_to_uint(SceneNodeType::TYPE_VEGETATION_TREES);

        if (!bitCompare(allowedNodeType, enum_to_uint(nodeType))) {
            if (!bitCompare(ignoredNodeType, enum_to_uint(nodeType))) {
                Console::printfn(Locale::get("WARN_NAV_UNSUPPORTED"),
                                 sn->getName().c_str());
                goto next;
            }
        }

        if (nodeType == SceneNodeType::TYPE_OBJECT3D) {
            U32 ignored3DObjectType =
                enum_to_uint(Object3D::ObjectType::MESH) |
                enum_to_uint(Object3D::ObjectType::TEXT_3D) |
                enum_to_uint(Object3D::ObjectType::FLYWEIGHT);
            if (bitCompare(ignored3DObjectType,
                           enum_to_uint(dynamic_cast<Object3D*>(sn)->getObjectType())))
            {
                goto next;
            }
        }

        MeshDetailLevel level = DETAIL_ABSOLUTE;
        VertexBuffer* geometry = nullptr;
        SamplePolyAreas areaType = SAMPLE_AREA_OBSTACLE;

        switch (nodeType) {
            case SceneNodeType::TYPE_WATER: {
                if (!sgn->getComponent<NavigationComponent>()
                         ->navMeshDetailOverride())
                    level = DETAIL_BOUNDINGBOX;
                areaType = SAMPLE_POLYAREA_WATER;
            } break;
            case SceneNodeType::TYPE_OBJECT3D: {
                // Check if we need to override detail level
                if (!sgn->getComponent<NavigationComponent>()
                         ->navMeshDetailOverride() &&
                    sgn->usageContext() == SceneGraphNode::NODE_STATIC) {
                    level = DETAIL_BOUNDINGBOX;
                }
                if (dynamic_cast<Object3D*>(sn)->getObjectType() ==
                    Object3D::ObjectType::TERRAIN) {
                    areaType = SAMPLE_POLYAREA_GROUND;
                }
            } break;
            default: {
                assert(false);  // we should never reach this due to the bit
                                // checks above
            } break;
        };

        // I should remove this hack - Ionut
        if (nodeType == SceneNodeType::TYPE_WATER) {
            sgn = sgn->getChildren()["waterPlane"];
        }

        Console::d_printfn(Locale::get("NAV_MESH_CURRENT_NODE"),
                           sn->getName().c_str(), (U32)level);

        U32 currentTriangleIndexOffset = outData.getVertCount();

        if (level == DETAIL_ABSOLUTE) {
            if (nodeType == SceneNodeType::TYPE_OBJECT3D) {
                geometry = dynamic_cast<Object3D*>(sn)->getGeometryVB();
            } else /*nodeType == TYPE_WATER*/ {
                geometry =
                    dynamic_cast<WaterPlane*>(sn)->getQuad()->getGeometryVB();
            }
            assert(geometry != nullptr);

            const vectorImpl<vec3<F32> >& vertices = geometry->getPosition();
            if (vertices.empty()) {
                return false;
            }

            dynamic_cast<Object3D*>(sn)->computeTriangleList();
            const vectorImpl<vec3<U32> >& triangles =
                dynamic_cast<Object3D*>(sn)->getTriangles();
            if (nodeType != SceneNodeType::TYPE_OBJECT3D ||
                (nodeType == SceneNodeType::TYPE_OBJECT3D &&
                 dynamic_cast<Object3D*>(sn)->getObjectType() != Object3D::ObjectType::TERRAIN)) {
                mat4<F32> nodeTransform =
                    sgn->getComponent<PhysicsComponent>()->getWorldMatrix();
                for (U32 i = 0; i < vertices.size(); ++i) {
                    // Apply the node's transform and add the vertex to the
                    // NavMesh
                    addVertex(&outData, nodeTransform * (vertices[i]));
                }
            } else {
                for (U32 i = 0; i < vertices.size(); ++i) {
                    // Apply the node's transform and add the vertex to the
                    // NavMesh
                    addVertex(&outData, (vertices[i]));
                }
            }

            for (U32 i = 0; i < triangles.size(); ++i) {
                addTriangle(&outData, triangles[i], currentTriangleIndexOffset,
                            areaType);
            }
        } else if (level == DETAIL_BOUNDINGBOX) {
            const vec3<F32>* vertices = box.getPoints();

            for (U32 i = 0; i < 8; i++) {
                addVertex(&outData, (vertices[i]));
            }

            for (U32 f = 0; f < 6; f++) {
                for (U32 v = 2; v < 4; v++) {
                    // Note: We reverse the normal on the polygons to prevent
                    // things from going inside out
                    addTriangle(&outData,
                                vec3<U32>(cubeFaces[f][0], cubeFaces[f][v - 1],
                                          cubeFaces[f][v]),
                                currentTriangleIndexOffset, areaType);
                }
            }
        } else {
            Console::errorfn(Locale::get("ERROR_RECAST_DETAIL_LEVEL"), level);
        }

        Console::printfn(Locale::get("NAV_MESH_ADD_NODE"),
                         sn->getName().c_str());
    }
// although labels are bad, skipping here using them is the easiest solution to
// follow -Ionut
next:
    ;
    for (SceneGraphNode::NodeChildren::value_type& it : sgn->getChildren()) {
        if (!parse(it.second->getBoundingBoxConst(), outData, it.second)) {
            return false;
        }
    }

    return true;
}
};
};  // namespace Navigation
};  // namespace AI
};  // namespace Divide

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

Diff revisions: vs.
Revision Author Commited Message
365 Diff Diff IonutCava picture IonutCava Sun 08 Mar, 2015 21:26:10 +0000

[Ionut]
- More enum-related type safety changes

350 Diff Diff IonutCava picture IonutCava Tue 10 Feb, 2015 16:25:39 +0000

[Ionut]
- Simplified some Util-namespace level functions by using STL algorithms where possible
- Formatted the entire codebase using clang-format with the following style: "{BasedOnStyle: Google, IndentWidth: 4}"
- Attempted to make ProfileTimer thread-safe (temp fix until std::chrono works properly in Visual Studio)

343 Diff Diff IonutCava picture IonutCava Thu 15 Jan, 2015 17:30:12 +0000

[Ionut]
- Refactored 2 singletons into static classes (Console and TerrainLoader)
- Changed some C-casts to static_casts
- Updated copyright notices

337 Diff Diff IonutCava picture IonutCava Wed 17 Dec, 2014 17:25:16 +0000

[Ionut]
- Replaced all tabs with 4 spaces (some spacing may be off now. no way to check all the files.)
- Moved implementation details for ParamHandler, BoundingBox, BoundingSphere and ProfileTimer to proper .inl and .cpp files. (more to follow)
- Update all forward declared enums with the required storage type (as requested by the C++11 standard)

331 Diff Diff IonutCava picture IonutCava Sat 06 Dec, 2014 20:53:45 +0000

[Ionut]
- Limited line length to 132 characters to improve readability and diff-comparisons
- Refactored memory allocation/deallocation functions
- Fixed a few compatibility issues with HashMap.h
- Fixed a bug in GPU Skinning shaders (cast a float to int)

326 Diff Diff IonutCava picture IonutCava Tue 30 Sep, 2014 21:11:32 +0000

[Ionut]
- Fixed more memory leaks
- Simplified Task interface and timing System
- Improved compatibility between Boost, STL and EASTL with random combinations of vectors, strings and maps
- Simplified Light class by removing the “slot” member
- Random optimizations

325 Diff Diff IonutCava picture IonutCava Wed 17 Sep, 2014 20:06:13 +0000

[Ionut]
- Reworked transform system:
— Parent transform chain system moved from Transform class to the PhysicsComponent
— PhysicsComponent now returns all transform values needed both global and local (still needs heavy optimization and caching)

- Reworked SceneGraph node management:
— Proper ref counting of SceneNodes and proper removing of resource (ResourceCache is now empty on destruction, as it should be)
— Removed parent transform tracking as that’s the PhysicsComponent’s responsibility
— Only nodes loaded via the ResourceCache are allowed to be added to the SceneGraph (added proper loaders for Impostors, Sky, etc)

- Optimized some of the math classes (mat4, mat3)

324 Diff Diff IonutCava picture IonutCava Sun 14 Sep, 2014 14:01:39 +0000

[Ionut]
- New memory management system (no custom allocators in this commit)
— Memory tracer to detect memory leaks on shutdown (from: https://www.relisoft.com/book/tech/9new.html)
— SAFE_DELETE_XYZ are now inline template functions not macros
— ASSERTION system now supports logging and message boxes and continue on error configurable for each build type
— Fixed a lot of memory leaks detected by the new system (some still remain)

- Added SRGB support (part 1)
— Albedo textures are loaded as SRGB (make sure resources are SRGB)
— Shaders output gamma corrected colors
— Moved terrain textures back to 2 array system (albedo and normal maps, albedo maps using a SRGB sampler)

- Sky is now loaded via the ResourceCache system
- Added include safeguards in shader atoms

322 Diff Diff IonutCava picture IonutCava Sat 06 Sep, 2014 20:33:47 +0000

[Ionut]
- Refactored most of Boost related code to be C++11 based
— Boost is only used for ThreadPool, Mutex handling, XML parsing and networking (ASIO)
— Function binds, threads, regex, NonCopyable base, Hashing algorithms and more are now using C++11 libraries
- Replaced all FOR_EACH calls with standard, range, “for” calls

318 IonutCava picture IonutCava Sat 30 Aug, 2014 17:35:53 +0000

[Ionut]
- Wrapped the entire code in a “Divide” namespace
- VertexBuffers now call “shrink_to_fit” on all internal data storage
- Improved some vector performance by preferring “emplace_back” instead of “push_back” + proepr usage of reserve / resize
- Wrapped OIS specific types and classes in Divide::Input namespace
- Added the messageBox.layout file (forgot it in the previous few commits)