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

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;
        }
    }
    ACKNOWLEDGE_UNUSED(cont);
    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) {
    STUBBED("ToDo: Rework load/save to properly use a ByteBuffer instead of this const char* hackery. -Ionut");
    char* buf = nullptr;
    char* srcEnd = nullptr;

    {
        ByteBuffer tempBuffer;
        if (!tempBuffer.loadFromFile(filename)) {
            return false;
        }

        MemoryManager_NEW char[tempBuffer.size()];
        std::memcpy(buf, reinterpret_cast<const char*>(tempBuffer.contents()), tempBuffer.size());
        srcEnd = buf + tempBuffer.size();
    }

    char* src = buf;

    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;

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

    return tempBuffer.dumpToFile(filename);
}

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 < to_uint(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) {
    assert(modelData != nullptr);

    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++ = to_int(triangleIndices.x + triangleIndexOffset);
    *dst++ = to_int(triangleIndices.y + triangleIndexOffset);
    *dst++ = to_int(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) {
    NavigationComponent* navComp = sgn.get<NavigationComponent>();
    if (navComp && 
        navComp->navigationContext() != NavigationComponent::NavigationContext::NODE_IGNORE &&  // Ignore if specified
        box.getHeight() > 0.05f)  // Skip small objects
    {
        const SceneNode_ptr& sn = sgn.getNode();

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

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

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

        if (nodeType == SceneNodeType::TYPE_OBJECT3D) {
            Object3D::ObjectType crtType =
                static_cast<Object3D*>(sn.get())->getObjectType();
            if (crtType == Object3D::ObjectType::TEXT_3D ||
                crtType == Object3D::ObjectType::MESH ||
                crtType == Object3D::ObjectType::FLYWEIGHT) {
                goto next;
            }
        }

        MeshDetailLevel level = MeshDetailLevel::MAXIMUM;
        VertexBuffer* geometry = nullptr;
        SamplePolyAreas areaType = SamplePolyAreas::SAMPLE_AREA_OBSTACLE;
        switch (nodeType) {
            case SceneNodeType::TYPE_WATER: {
                if (navComp && !navComp->navMeshDetailOverride())
                    level = MeshDetailLevel::BOUNDINGBOX;
                areaType = SamplePolyAreas::SAMPLE_POLYAREA_WATER;
            } break;
            case SceneNodeType::TYPE_OBJECT3D: {
                // Check if we need to override detail level
                if (navComp && !navComp->navMeshDetailOverride() &&
                     sgn.usageContext() == SceneGraphNode::UsageContext::NODE_STATIC) {
                    level = MeshDetailLevel::BOUNDINGBOX;
                }
                if (static_cast<Object3D*>(sn.get())->getObjectType() ==
                    Object3D::ObjectType::TERRAIN) {
                    areaType = SamplePolyAreas::SAMPLE_POLYAREA_GROUND;
                }
            } break;
            default: {
                // we should never reach this due to the bit checks above
                DIVIDE_UNEXPECTED_CALL();
            } break;
        };

        // I should remove this hack - Ionut
        SceneGraphNode_ptr nodeSGN = sgn.shared_from_this();
        if (nodeType == SceneNodeType::TYPE_WATER) {
            nodeSGN = sgn.findChild("waterPlane").lock();
        }

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

        U32 currentTriangleIndexOffset = outData.getVertCount();

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

            const vectorImpl<VertexBuffer::Vertex >& vertices = geometry->getVertices();
            if (vertices.empty()) {
                return false;
            }

            static_cast<Object3D*>(sn.get())->computeTriangleList();
            const vectorImpl<vec3<U32> >& triangles =
                static_cast<Object3D*>(sn.get())->getTriangles();
            if (nodeType != SceneNodeType::TYPE_OBJECT3D ||
               (nodeType == SceneNodeType::TYPE_OBJECT3D &&
                static_cast<Object3D*>(sn.get())->getObjectType() != Object3D::ObjectType::TERRAIN))
            {
                mat4<F32> nodeTransform = nodeSGN->get<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]._position));
                }
            } 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]._position));
                }
            }

            for (U32 i = 0; i < triangles.size(); ++i) {
                addTriangle(&outData, triangles[i], currentTriangleIndexOffset,
                            areaType);
            }
        } else if (level == MeshDetailLevel::BOUNDINGBOX) {
            std::array<vec3<F32>, 8> 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(_ID("ERROR_RECAST_LEVEL")), level);
        }

        Console::printfn(Locale::get(_ID("NAV_MESH_ADD_NODE")),
                         sn->getName().c_str());
    }
// although labels are bad, skipping here using them is the easiest solution to
// follow -Ionut
next:
    ;

    return !sgn.forEachChildInterruptible([&outData](SceneGraphNode& child) {
                if (!parse(child.get<BoundsComponent>()->getBoundingBox(), outData, child)) {
                    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
832 Diff Diff IonutCava picture IonutCava Thu 26 Jan, 2017 17:23:11 +0000

[IonutCava]
- More path related work
- Initial code to centralize file I/O (does not compile yet)

830 Diff Diff IonutCava picture IonutCava Wed 25 Jan, 2017 17:29:44 +0000

[IonutCava]
- Add a new Platform element: File
— Move all predefined paths to FileManagement System
- Split MathHelper into MathHelper and StringHelper

825 Diff Diff IonutCava picture IonutCava Fri 20 Jan, 2017 14:35:31 +0000

[IonutCava]
- Small corrections and optimizations to the TaskPool
- Fix buffer update bug in LightPool

794 Diff Diff IonutCava picture IonutCava Tue 22 Nov, 2016 16:44:26 +0000

[IonutCava]
- Change SDL_GL_Context management from a pool-based system to a thread_local variable type System
- Reworked SceneGraphNode child access for safer and faster iteration.
— Added a forEachChild with multiple overloads to apply a lambda expression over every child of the target SGN
- Slight optimization to Text rendering by batching all labels due for rendering and submitting them at all at once

727 Diff Diff IonutCava picture IonutCava Tue 14 Jun, 2016 16:01:38 +0000

[IonutCava]
- Remove node and cmd buffers from GFXDevice and add them as a new BufferData struct to RenderPass class.
— Each render pass holds its own buffers
- Improvements / fixes to the CSM code
- Added a global toggle to enable/disable custom memory allocators

720 Diff Diff IonutCava picture IonutCava Mon 06 Jun, 2016 15:51:06 +0000

[IonutCava]
- PVS-Studio guided static analysis fixes and optimizations
- Added a flag to SceneState to bypass the Save/Load system not needed for certain types of scenes (menus, cinematics, etc)

709 Diff Diff IonutCava picture IonutCava Thu 19 May, 2016 16:21:46 +0000

[IonutCava]
- Massive rewrite of the resource system:
— ResourceCache now uses a map of weak pointers and passes shared pointers to the call point of CreateResource
— RemoveResource is no longer needed, but resource based smart pointers use a custom deleter that calls unload()
— Keep a shared_ptr of the resource in the entity that needs it and pass shared_ptr references from getter methods
-— All of this removed the need for calls to RemoveResource, REGISTER_TRACKED_DEPENDENCY and UNREGISTER_TRACKED_DEPENDENCY reducing the number of mutex locks and atomic exchanges
- Singleton cleanup:
— Removed ShaderManager singleton and merged it’s data and responsibilities in static methods in both ShaderProgram and Shader classes.
Explanation: Due to the complex interdependency chains in the system, copying, updating, tracking the cache in a thread safe way became a lot more slower than a straight forward smart pointer based implementation. (e.g. scene graph nodes have 3d objects and material instances, 3d objects have materials, materials have textures and shaders, etc)

650 Diff Diff IonutCava picture IonutCava Tue 23 Feb, 2016 16:54:54 +0000

[IonutCava]
- Fix decoupling between PhysicsComponent and BoundsComponent
— SceneNodes now keep references to all owning SGNs and informs them when the bounds change
- AnimationComponent does not need a SceneAnimator on creation but most functionality will assert if one is not specified
— This was needed for the new component configuration system
- Added placeholder classes for an Inverse Kinematic component and a Ragdoll component
- SNG component configuration is now an upfront requirement: pass a component type mask when adding a node the the scenegraph
- SGN SpatialPartitionFlag is now an update flag that is set and cleared. More flags can be added in a similar fashion to nodes

649 Diff Diff IonutCava picture IonutCava Mon 22 Feb, 2016 17:16:17 +0000

[IonutCava]
- Attempt to uncouple PhysicsComponent from BoundsComponent

648 IonutCava picture IonutCava Sun 21 Feb, 2016 16:32:52 +0000

[IonutCava]
- Update copyright notice
- Move BoundingBox and BoundingSphere to a new BoundsComponent
— Add a temp hack in SceneGraphNode to update these