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
#include "Headers/Terrain.h"
#include "Headers/TerrainChunk.h"
#include "Headers/TerrainDescriptor.h"

#include "Quadtree/Headers/QuadtreeNode.h"

#include "Core/Headers/PlatformContext.h"
#include "Core/Math/Headers/Transform.h"
#include "Graphs/Headers/SceneGraphNode.h"
#include "Managers/Headers/SceneManager.h"

#include "Geometry/Material/Headers/Material.h"
#include "Platform/Video/Headers/GFXDevice.h"
#include "Platform/Video/Buffers/VertexBuffer/Headers/VertexBuffer.h"

namespace Divide {


namespace {
    size_t g_PlaneCommandIndex = 0;
};

Terrain::Terrain(GFXDevice& context, ResourceCache& parentCache, const stringImpl& name)
    : Object3D(context, parentCache, name, ObjectType::TERRAIN, ObjectFlag::OBJECT_FLAG_NONE),
      _alphaTexturePresent(false),
      _plane(nullptr),
      _drawBBoxes(false),
      _underwaterDiffuseScale(100.0f),
      _chunkSize(1),
      _waterHeight(0.0f)
{
    getGeometryVB()->useLargeIndices(true);  //<32bit indices

    _albedoSampler = MemoryManager_NEW SamplerDescriptor();
    _albedoSampler->setWrapMode(TextureWrap::REPEAT);
    _albedoSampler->setAnisotropy(8);
    _albedoSampler->toggleMipMaps(true);
    _albedoSampler->toggleSRGBColourSpace(true);

    _normalSampler = MemoryManager_NEW SamplerDescriptor();
    _normalSampler->setWrapMode(TextureWrap::REPEAT);
    _normalSampler->setAnisotropy(8);
    _normalSampler->toggleMipMaps(true);
    _albedoSampler->toggleSRGBColourSpace(false);
}

Terrain::~Terrain() {
    MemoryManager::DELETE(_albedoSampler);
    MemoryManager::DELETE(_normalSampler);
}

bool Terrain::load() {
    return Object3D::load();
}

bool Terrain::unload() {
    MemoryManager::DELETE_VECTOR(_terrainTextures);
    return Object3D::unload();
}

void Terrain::postLoad(SceneGraphNode& sgn) {
    static const U32 normalMask = to_const_uint(SGNComponent::ComponentType::NAVIGATION) |
                                  to_const_uint(SGNComponent::ComponentType::PHYSICS) |
                                  to_const_uint(SGNComponent::ComponentType::BOUNDS) |
                                  to_const_uint(SGNComponent::ComponentType::RENDERING) |
                                  to_const_uint(SGNComponent::ComponentType::NETWORKING);

    SceneGraphNode_ptr planeSGN(sgn.addNode(_plane, normalMask, PhysicsGroup::GROUP_STATIC));
    planeSGN->setActive(false);
    /*for (TerrainChunk* chunk : _terrainChunks) {
        SceneGraphNode_ptr vegetation = sgn.addNode(Attorney::TerrainChunkTerrain::getVegetation(*chunk), normalMask);
        vegetation->lockVisibility(true);
    }*/
    // Skip Object3D::load() to avoid triangle list computation (extremely expensive)!!!

    SceneNode::postLoad(sgn);
}

void Terrain::buildQuadtree() {
    reserveTriangleCount((_terrainDimensions.x - 1) *
                         (_terrainDimensions.y - 1) * 2);
    _terrainQuadtree.Build(
        _context,
        _boundingBox,
        vec2<U32>(_terrainDimensions.x, _terrainDimensions.y),
        _chunkSize, this);

    // The terrain's final bounding box is the QuadTree's root bounding box
    _boundingBox.set(_terrainQuadtree.computeBoundingBox());


    const Material_ptr& mat = getMaterialTpl();

    const vec3<F32>& bbMin = _boundingBox.getMin();
    const vec3<F32>& bbExtent = _boundingBox.getExtent();

    for (U8 pass = 0; pass < to_const_ubyte(RenderPassType::COUNT); ++pass) {
        for (U32 i = 0; i < to_const_uint(RenderStage::COUNT); ++i) {
            RenderStage stage = static_cast<RenderStage>(i);

            const ShaderProgram_ptr& drawShader = mat->getShaderInfo(RenderStagePass(stage, static_cast<RenderPassType>(pass))).getProgram();

            drawShader->Uniform("bbox_min", bbMin);
            drawShader->Uniform("bbox_extent", bbExtent);
            drawShader->Uniform("underwaterDiffuseScale", _underwaterDiffuseScale);

            U8 textureOffset = to_const_ubyte(ShaderProgram::TextureUsage::COUNT);
            U8 layerOffset = 0;
            stringImpl layerIndex;
            for (U8 k = 0; k < _terrainTextures.size(); ++k) {
                layerOffset = k * 3 + textureOffset;
                layerIndex = to_stringImpl(k);
                TerrainTextureLayer* textureLayer = _terrainTextures[k];

                drawShader->Uniform(("texBlend[" + layerIndex + "]").c_str(), layerOffset);
                drawShader->Uniform(("texTileMaps[" + layerIndex + "]").c_str(), layerOffset + 1);
                drawShader->Uniform(("texNormalMaps[" + layerIndex + "]").c_str(), layerOffset + 2);
                drawShader->Uniform(("diffuseScale[" + layerIndex + "]").c_str(), textureLayer->getDiffuseScales());
                drawShader->Uniform(("detailScale[" + layerIndex + "]").c_str(), textureLayer->getDetailScales());

                if (i == 0) {
                    getMaterialTpl()->addCustomTexture(textureLayer->blendMap(), layerOffset);
                    getMaterialTpl()->addCustomTexture(textureLayer->tileMaps(), layerOffset + 1);
                    getMaterialTpl()->addCustomTexture(textureLayer->normalMaps(), layerOffset + 2);
                }
            }
        }
    }
}

void Terrain::sceneUpdate(const U64 deltaTime,
                          SceneGraphNode& sgn,
                          SceneState& sceneState) {
    _waterHeight = sceneState.waterLevel();
    _terrainQuadtree.sceneUpdate(deltaTime, sgn, sceneState);
    Object3D::sceneUpdate(deltaTime, sgn, sceneState);
}

void Terrain::initialiseDrawCommands(SceneGraphNode& sgn,
                                     const RenderStagePass& renderStagePass,
                                     GenericDrawCommands& drawCommandsInOut) {

    GenericDrawCommand cmd;
    cmd.sourceBuffer(getGeometryVB());
    cmd.primitiveType(PrimitiveType::TRIANGLE_STRIP);
    drawCommandsInOut.push_back(cmd);

    size_t chunkCount = static_cast<size_t>(_terrainQuadtree.getChunkCount());
    for (U32 i = 0; i < chunkCount; ++i) {
        drawCommandsInOut.push_back(cmd);
    }

    g_PlaneCommandIndex = drawCommandsInOut.size();
    if (renderStagePass._stage == RenderStage::DISPLAY) {
        //infinite plane
        VertexBuffer* const vb = _plane->getGeometryVB();
        cmd.cmd().firstIndex = 0;
        cmd.cmd().indexCount = vb->getIndexCount();
        cmd.LoD(0);
        cmd.sourceBuffer(vb);
        drawCommandsInOut.push_back(cmd);

        //BoundingBoxes
        GenericDrawCommand bbCommand;
        bbCommand.drawCount(0);
        for (U32 i = 0; i < chunkCount + 2; ++i) {
            drawCommandsInOut.push_back(bbCommand);
        }
    }
    Object3D::initialiseDrawCommands(sgn, renderStagePass, drawCommandsInOut);
}

void Terrain::updateDrawCommands(SceneGraphNode& sgn,
                                 const RenderStagePass& renderStagePass,
                                 const SceneRenderState& sceneRenderState,
                                 GenericDrawCommands& drawCommandsInOut) {

    _context.setClipPlane(ClipPlaneIndex::CLIP_PLANE_0, Plane<F32>(WORLD_Y_AXIS, _waterHeight));

    drawCommandsInOut.front().shaderProgram()->Uniform("dvd_waterHeight", _waterHeight);
    vectorImpl<vec3<U32>> chunkData;
    size_t chunkCount = static_cast<size_t>(_terrainQuadtree.getChunkCount());
    chunkData.reserve(chunkCount);
    _terrainQuadtree.getChunkBufferData(renderStagePass._stage, sceneRenderState, chunkData);

    std::sort(std::begin(chunkData), std::end(chunkData),
                [](const vec3<U32>& a, const vec3<U32>& b) {
                    // LoD comparison
                    return a.z < b.z; 
                });

    size_t i = 0; size_t dataCount = chunkData.size();
    for (;i < chunkCount; ++i) {
        if (i < dataCount) {
            vec3<U32>& cmdData = chunkData[i];
            GenericDrawCommand& cmd = drawCommandsInOut[i + 1];
            cmd.cmd().firstIndex = cmdData.x;
            cmd.cmd().indexCount = cmdData.y;
            cmd.LoD(to_byte(cmdData.z));
        }
    }

    if (renderStagePass._stage == RenderStage::DISPLAY) {
        // draw infinite plane
        GenericDrawCommand& planeCmd = drawCommandsInOut[g_PlaneCommandIndex];
        planeCmd.drawCount((renderStagePass._stage == RenderStage::DISPLAY ? 1 : 0));

        i = g_PlaneCommandIndex + 1;

        if (_drawBBoxes) {
            GenericDrawCommands commands;
            commands.reserve(chunkCount);
            _terrainQuadtree.drawBBox(_context, commands);

            for (const GenericDrawCommand& cmd : commands) {
                drawCommandsInOut[i++] = cmd;
            }

        } else {
            for (; i < chunkCount; ++i) {
                drawCommandsInOut[i].drawCount(0);
            }
        }
    }

    Object3D::updateDrawCommands(sgn, renderStagePass, sceneRenderState, drawCommandsInOut);
}

vec3<F32> Terrain::getPositionFromGlobal(F32 x, F32 z) const {
    x -= _boundingBox.getCenter().x;
    z -= _boundingBox.getCenter().z;
    F32 xClamp = (0.5f * _terrainDimensions.x) + x;
    F32 zClamp = (0.5f * _terrainDimensions.y) - z;
    xClamp /= _terrainDimensions.x;
    zClamp /= _terrainDimensions.y;
    zClamp = 1 - zClamp;
    vec3<F32> temp = getPosition(xClamp, zClamp);

    return temp;
}

vec3<F32> Terrain::getPosition(F32 x_clampf, F32 z_clampf) const {
    assert(!(x_clampf < .0f || z_clampf < .0f || x_clampf > 1.0f ||
             z_clampf > 1.0f));

    vec2<F32> posF(x_clampf * _terrainDimensions.x,
                   z_clampf * _terrainDimensions.y);
    vec2<I32> posI(to_int(posF.x), to_int(posF.y));
    vec2<F32> posD(posF.x - posI.x, posF.y - posI.y);

    if (posI.x >= (I32)_terrainDimensions.x - 1)
        posI.x = _terrainDimensions.x - 2;
    if (posI.y >= (I32)_terrainDimensions.y - 1)
        posI.y = _terrainDimensions.y - 2;

    assert(posI.x >= 0 && posI.x < to_int(_terrainDimensions.x) - 1 &&
           posI.y >= 0 && posI.y < to_int(_terrainDimensions.y) - 1);

    vec3<F32> pos(
        _boundingBox.getMin().x +
            x_clampf * (_boundingBox.getMax().x - _boundingBox.getMin().x),
        0.0f,
        _boundingBox.getMin().z +
            z_clampf * (_boundingBox.getMax().z - _boundingBox.getMin().z));


    const VertexBuffer* const vb = getGeometryVB();

    pos.y = (vb->getPosition(TER_COORD(posI.x, posI.y, to_int(_terrainDimensions.x))).y) *
            (1.0f - posD.x) * (1.0f - posD.y) + 
            (vb->getPosition(TER_COORD(posI.x + 1, posI.y, to_int(_terrainDimensions.x))).y) *
            posD.x * (1.0f - posD.y) +
            (vb->getPosition(TER_COORD(posI.x, posI.y + 1, to_int(_terrainDimensions.x))).y) *
            (1.0f - posD.x) * posD.y +
            (vb->getPosition(TER_COORD(posI.x + 1, posI.y + 1,to_int(_terrainDimensions.x))).y) *
            posD.x * posD.y;

    return pos;
}

vec3<F32> Terrain::getNormal(F32 x_clampf, F32 z_clampf) const {
    assert(!(x_clampf < .0f || z_clampf < .0f || x_clampf > 1.0f ||
             z_clampf > 1.0f));

    vec2<F32> posF(x_clampf * _terrainDimensions.x,
                   z_clampf * _terrainDimensions.y);
    vec2<I32> posI(to_int(x_clampf * _terrainDimensions.x),
                   to_int(z_clampf * _terrainDimensions.y));
    vec2<F32> posD(posF.x - posI.x, posF.y - posI.y);

    if (posI.x >= to_int(_terrainDimensions.x) - 1) {
        posI.x = to_int(_terrainDimensions.x) - 2;
    }
    if (posI.y >= to_int(_terrainDimensions.y) - 1) {
        posI.y = to_int(_terrainDimensions.y) - 2;
    }
    assert(posI.x >= 0 && posI.x < to_int(_terrainDimensions.x) - 1 &&
           posI.y >= 0 && posI.y < to_int(_terrainDimensions.y) - 1);

    const VertexBuffer* const vb = getGeometryVB();
    vec3<F32> normals[4];

    vb->getNormal(TER_COORD(posI.x, posI.y, to_int(_terrainDimensions.x)), normals[0]);
    vb->getNormal(TER_COORD(posI.x + 1, posI.y, to_int(_terrainDimensions.x)), normals[1]);
    vb->getNormal(TER_COORD(posI.x, posI.y + 1, to_int(_terrainDimensions.x)), normals[2]);
    vb->getNormal(TER_COORD(posI.x + 1, posI.y + 1, to_int(_terrainDimensions.x)), normals[3]);

    return normals[0] * (1.0f - posD.x) * (1.0f - posD.y) +
           normals[1] * posD.x * (1.0f - posD.y) +
           normals[2] * (1.0f - posD.x) * posD.y + 
           normals[3] * posD.x * posD.y;
}

vec3<F32> Terrain::getTangent(F32 x_clampf, F32 z_clampf) const {
    assert(!(x_clampf < .0f || z_clampf < .0f || x_clampf > 1.0f ||
             z_clampf > 1.0f));

    vec2<F32> posF(x_clampf * _terrainDimensions.x,
                   z_clampf * _terrainDimensions.y);
    vec2<I32> posI(to_int(x_clampf * _terrainDimensions.x),
                   to_int(z_clampf * _terrainDimensions.y));
    vec2<F32> posD(posF.x - posI.x, posF.y - posI.y);

    if (posI.x >= to_int(_terrainDimensions.x) - 1) {
        posI.x = to_int(_terrainDimensions.x) - 2;
    }
    if (posI.y >= to_int(_terrainDimensions.y) - 1) {
        posI.y = to_int(_terrainDimensions.y) - 2;
    }
    assert(posI.x >= 0 && posI.x < to_int(_terrainDimensions.x) - 1 &&
           posI.y >= 0 && posI.y < to_int(_terrainDimensions.y) - 1);

    const VertexBuffer* const vb = getGeometryVB();
    vec3<F32> tangents[4];


    vb->getTangent(TER_COORD(posI.x, posI.y, to_int(_terrainDimensions.x)), tangents[0]);
    vb->getTangent(TER_COORD(posI.x + 1, posI.y, to_int(_terrainDimensions.x)), tangents[1]);
    vb->getTangent(TER_COORD(posI.x, posI.y + 1, to_int(_terrainDimensions.x)), tangents[2]);
    vb->getTangent(TER_COORD(posI.x + 1, posI.y + 1, to_int(_terrainDimensions.x)), tangents[3]);

    return tangents[0] * (1.0f - posD.x) * (1.0f - posD.y) +
           tangents[1] * posD.x * (1.0f - posD.y) +
           tangents[2] * (1.0f - posD.x) * posD.y +
           tangents[3] * posD.x * posD.y;
}

TerrainTextureLayer::~TerrainTextureLayer()
{
}
};

Commits for Divide-Framework/trunk/Source Code/Environment/Terrain/Terrain.cpp

Diff revisions: vs.
Revision Author Commited Message
853 Diff Diff IonutCava picture IonutCava Tue 07 Feb, 2017 21:43:58 +0000

[IonutCava]
- More work on water rendering.

852 Diff Diff IonutCava picture IonutCava Tue 07 Feb, 2017 17:17:27 +0000

[IonutCava]
- Separate Pass Type from Render Stage:
— Render Stage: Display, Shadow, Reflection, Refraction, etc
— Pass Type: Depth pass, Colour Pass, etc
- ToDo: Bug fixes for issues introduced with this change

851 Diff Diff IonutCava picture IonutCava Mon 06 Feb, 2017 23:38:14 +0000

[IonutCava]
- Replaced most RenderStage params with RenderStagePass types
- More work on water rendering

850 Diff Diff IonutCava picture IonutCava Mon 06 Feb, 2017 17:04:39 +0000

[IonutCava]
- More code rot fixes
- Separate Planar reflectors/refractors from Cube R/R
- Now passing detail levels to shaders

847 Diff Diff IonutCava picture IonutCava Sun 05 Feb, 2017 21:16:24 +0000

[IonutCava]
- Code rot fixes:
— Terrain loading (8 bit heightmap only for now)
— Terrain rendering
— Water Plane loading and rendering
— Reflection and Refraction rendering passes (hack for now: need environment cubemaps as separate from reflect/refract maps for planar rendering)
-— ToDo: Separate Reflection / Refraction render targets to Planar R/R and Cube R/R. Environment probes should use Cube Reflections, Water should use planar reflection targets.
- Added a way to register debug views: texture, shader and params. Viewports get automatically scaled and positioned
— ToDo: Add a hover-preview feature
— ToDo: Add a click-lock preview feature

838 Diff Diff IonutCava picture IonutCava Mon 30 Jan, 2017 17:28:35 +0000

[IonutCava]
- Added a NetworkingComponent to SGNs
- Started cleaning up Client / Server architecture

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

811 Diff Diff IonutCava picture IonutCava Wed 11 Jan, 2017 17:26:49 +0000

[IonutCava]
- Fix some threadpool cleanup bugs
- Fix terrain rendering (except underwater caustics)
- Fix terrain loading
- Fix terrain unloading

804 Diff Diff IonutCava picture IonutCava Thu 01 Dec, 2016 17:20:59 +0000

[IonutCava]
- Singleton elimination update Part I: get it to compile
— The following classes are no longer Singletons: GFXDevice, GL_API, DX_API, SFXWrapper, FmodWrapper, SDLWrapper, ALWrapper, PXDevice, InputInterface, RenderPassManager, SceneManager and ResourceManager;
— Refactor system to a Context / Component based implementation (Pass relevant context to objects: e.g. GFXDevice object to Textures, GUI to GUIElements, etc)
— Make devices and managers components of the kernel
— Allow multiple Resource caches to co-exist. This may prove useful for later when a more fragmented memory model is need (per frame / per scene / global caches / etc)

  • next steps: part II – cleanup/refactor new code, part III – optimise code, part IV – remove remaining Singletons (e.g. Application, ParamHandler, FrameListenerManager, Recast, PostFX and DebugInterface)
788 IonutCava picture IonutCava Fri 21 Oct, 2016 16:11:37 +0000

[IonutCava]
- Added support for the Arena Allocator by Mamasha Knows (http://www.codeproject.com/Articles/44850/Arena-Allocator-DTOR-and-Embedded-Preallocated-Buf)
— Used for GFX Related objects: Textures, shaders, etc