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

#include "Core/Headers/PlatformContext.h"
#include "Platform/Video/Headers/GFXDevice.h"
#include "Platform/Video/Headers/RenderStateBlock.h"

#include "Geometry/Material/Headers/Material.h"
#include "Managers/Headers/SceneManager.h"
#include "Geometry/Shapes/Headers/Predefined/Quad3D.h"
#include "Geometry/Shapes/Headers/Predefined/Patch3D.h"

namespace Divide {

namespace Test {

void init(VertexBuffer* vb) {
    vb->resizeVertexCount(4);
    vb->modifyPositionValue(0, -1.0f, 0.0f, -1.0f);
    vb->modifyPositionValue(1,  1.0f, 0.0f, -1.0f);
    vb->modifyPositionValue(2,  1.0f, 0.0f,  1.0f);
    vb->modifyPositionValue(3, -1.0f, 0.0f,  1.0f);

    vb->modifyColourValue(0, Util::ToByteColour(vec3<F32>(0.18f, 0.91f, 0.46f)));
    vb->modifyColourValue(1, Util::ToByteColour(vec3<F32>(0.18f, 0.91f, 0.46f)));
    vb->modifyColourValue(2, Util::ToByteColour(vec3<F32>(0.18f, 0.91f, 0.46f)));
    vb->modifyColourValue(3, Util::ToByteColour(vec3<F32>(0.18f, 0.91f, 0.46f)));

    vb->modifyNormalValue(0, 0.0f, 1.0f, 0.0f);
    vb->modifyNormalValue(1, 0.0f, 1.0f, 0.0f);
    vb->modifyNormalValue(2, 0.0f, 1.0f, 0.0f);
    vb->modifyNormalValue(3, 0.0f, 1.0f, 0.0f);
    
    vb->modifyTexCoordValue(0, 0.0f, 2.0f);
    vb->modifyTexCoordValue(1, 2.0f, 2.0f);
    vb->modifyTexCoordValue(2, 2.0f, 0.0f);
    vb->modifyTexCoordValue(3, 0.0f, 0.0f);

    vb->addIndex(0);
    vb->addIndex(1);
    vb->addIndex(2);
    vb->addIndex(3);
}
};


bool TerrainLoader::loadTerrain(std::shared_ptr<Terrain> terrain,
                                const std::shared_ptr<TerrainDescriptor>& terrainDescriptor,
                                PlatformContext& context,
                                bool threadedLoading,
                                const DELEGATE_CBK<void, CachedResource_wptr>& onLoadCallback ) {
    const stringImpl& name = terrainDescriptor->getVariable("terrainName");

    Attorney::TerrainLoader::setUnderwaterDiffuseScale(
        *terrain, terrainDescriptor->getVariablef("underwaterDiffuseScale"));

    SamplerDescriptor blendMapSampler;
    blendMapSampler.setWrapMode(TextureWrap::CLAMP);
    blendMapSampler.setAnisotropy(0);
    blendMapSampler.toggleMipMaps(false);

    SamplerDescriptor albedoSampler;
    albedoSampler.setWrapMode(TextureWrap::REPEAT);
    albedoSampler.setAnisotropy(8);
    albedoSampler.toggleMipMaps(true);
    albedoSampler.toggleSRGBColourSpace(true);

    SamplerDescriptor normalSampler;
    normalSampler.setWrapMode(TextureWrap::REPEAT);
    normalSampler.setAnisotropy(8);
    normalSampler.toggleMipMaps(true);
    normalSampler.toggleSRGBColourSpace(false);

    SamplerDescriptor heightMapSampler;
    heightMapSampler.setWrapMode(TextureWrap::CLAMP);
    heightMapSampler.setAnisotropy(0);
    heightMapSampler.toggleMipMaps(false);
    heightMapSampler.toggleSRGBColourSpace(false);

    TerrainTextureLayer* textureLayer = nullptr;
    stringImpl layerOffsetStr;
    stringImpl currentTexture;
    stringImpl arrayLocation;
    U32 textureCount = 0;
    U32 textureCountAlbedo = 0;
    U32 textureCountDetail = 0;
    const stringImpl& terrainMapLocation = terrainDescriptor->getVariable("textureLocation");

    for (U32 i = 0; i < terrainDescriptor->getTextureLayerCount(); ++i) {
        textureCountAlbedo = 0;
        textureCountDetail = 0;

        layerOffsetStr = to_stringImpl(i);
        textureLayer = MemoryManager_NEW TerrainTextureLayer();

        ResourceDescriptor textureBlendMap("Terrain Blend Map_" + name + "_layer_" + layerOffsetStr);
        textureBlendMap.setResourceLocation(terrainMapLocation);
        textureBlendMap.setResourceName(terrainDescriptor->getVariable("blendMap" + layerOffsetStr));
        textureBlendMap.setPropertyDescriptor(blendMapSampler);
        textureBlendMap.setEnumValue(to_base(TextureType::TEXTURE_2D));
        textureLayer->setBlendMap(CreateResource<Texture>(terrain->parentResourceCache(), textureBlendMap));

        arrayLocation.clear();
        currentTexture = terrainDescriptor->getVariable("redAlbedo" + layerOffsetStr);
        if (!currentTexture.empty()) {
            arrayLocation = currentTexture;
            textureCount++;
            textureCountAlbedo++;
            textureLayer->setDiffuseScale(
                TerrainTextureLayer::TerrainTextureChannel::TEXTURE_RED_CHANNEL,
                terrainDescriptor->getVariablef("diffuseScaleR" +
                                                layerOffsetStr));
        }
        currentTexture =
            terrainDescriptor->getVariable("greenAlbedo" + layerOffsetStr);
        if (!currentTexture.empty()) {
            arrayLocation += "," + currentTexture;
            textureCount++;
            textureCountAlbedo++;
            textureLayer->setDiffuseScale(
                TerrainTextureLayer::TerrainTextureChannel::TEXTURE_GREEN_CHANNEL,
                terrainDescriptor->getVariablef("diffuseScaleG" +
                                                layerOffsetStr));
        }
        currentTexture =
            terrainDescriptor->getVariable("blueAlbedo" + layerOffsetStr);
        if (!currentTexture.empty()) {
            arrayLocation += "," + currentTexture;
            textureCount++;
            textureCountAlbedo++;
            textureLayer->setDiffuseScale(
                TerrainTextureLayer::TerrainTextureChannel::TEXTURE_BLUE_CHANNEL,
                terrainDescriptor->getVariablef("diffuseScaleB" +
                                                layerOffsetStr));
        }
        currentTexture =
            terrainDescriptor->getVariable("alphaAlbedo" + layerOffsetStr);
        if (!currentTexture.empty()) {
            arrayLocation += "," + currentTexture;
            textureCount++;
            textureCountAlbedo++;
            textureLayer->setDiffuseScale(
                TerrainTextureLayer::TerrainTextureChannel::TEXTURE_ALPHA_CHANNEL,
                terrainDescriptor->getVariablef("diffuseScaleA" +
                                                layerOffsetStr));
        }

        ResourceDescriptor textureTileMaps("Terrain Tile Maps_" + name +
                                           "_layer_" + layerOffsetStr);
        textureTileMaps.setEnumValue(to_base(TextureType::TEXTURE_2D_ARRAY));
        textureTileMaps.setID(textureCountAlbedo);
        textureTileMaps.setResourceLocation(terrainMapLocation);
        textureTileMaps.setResourceName(arrayLocation);
        textureTileMaps.setPropertyDescriptor(albedoSampler);
        textureLayer->setTileMaps(CreateResource<Texture>(terrain->parentResourceCache(), textureTileMaps));

        arrayLocation.clear();
        currentTexture =
            terrainDescriptor->getVariable("redDetail" + layerOffsetStr);
        if (!currentTexture.empty()) {
            arrayLocation += "," + currentTexture;
            textureCountDetail++;
            textureLayer->setDetailScale(
                TerrainTextureLayer::TerrainTextureChannel::TEXTURE_RED_CHANNEL,
                terrainDescriptor->getVariablef("detailScaleR" +
                                                layerOffsetStr));
        }
        currentTexture =
            terrainDescriptor->getVariable("greenDetail" + layerOffsetStr);
        if (!currentTexture.empty()) {
            arrayLocation += "," + currentTexture;
            textureCountDetail++;
            textureLayer->setDetailScale(
                TerrainTextureLayer::TerrainTextureChannel::TEXTURE_GREEN_CHANNEL,
                terrainDescriptor->getVariablef("detailScaleG" +
                                                layerOffsetStr));
        }
        currentTexture =
            terrainDescriptor->getVariable("blueDetail" + layerOffsetStr);
        if (!currentTexture.empty()) {
            arrayLocation += "," + currentTexture;
            textureCountDetail++;
            textureLayer->setDetailScale(
                TerrainTextureLayer::TerrainTextureChannel::TEXTURE_BLUE_CHANNEL,
                terrainDescriptor->getVariablef("detailScaleB" +
                                                layerOffsetStr));
        }
        currentTexture =
            terrainDescriptor->getVariable("alphaDetail" + layerOffsetStr);
        if (!currentTexture.empty()) {
            arrayLocation += "," + currentTexture;
            textureCountDetail++;
            textureLayer->setDetailScale(
                TerrainTextureLayer::TerrainTextureChannel::TEXTURE_ALPHA_CHANNEL,
                terrainDescriptor->getVariablef("detailScaleA" +
                                                layerOffsetStr));
        }

        ResourceDescriptor textureNormalMaps("Terrain Normal Maps_" + name +
                                             "_layer_" + layerOffsetStr);
        textureNormalMaps.setEnumValue(to_base(TextureType::TEXTURE_2D_ARRAY));
        textureNormalMaps.setID(textureCountDetail);
        textureNormalMaps.setResourceLocation(terrainMapLocation);
        textureNormalMaps.setResourceName(arrayLocation);
        textureNormalMaps.setPropertyDescriptor(normalSampler);
        textureLayer->setNormalMaps(CreateResource<Texture>(terrain->parentResourceCache(), textureNormalMaps));

        Attorney::TerrainLoader::addTextureLayer(*terrain, textureLayer);
    }

    ResourceDescriptor terrainMaterialDescriptor("terrainMaterial_" + name);
    Material_ptr terrainMaterial =
        CreateResource<Material>(terrain->parentResourceCache(), terrainMaterialDescriptor);

    terrainMaterial->setDiffuse(
        vec4<F32>(DefaultColours::WHITE().rgb() / 2, 1.0f));
    terrainMaterial->setSpecular(vec4<F32>(0.1f, 0.1f, 0.1f, 1.0f));
    terrainMaterial->setShininess(20.0f);
    terrainMaterial->setShadingMode(Material::ShadingMode::BLINN_PHONG);
    terrainMaterial->setShaderDefines("COMPUTE_TBN");
    terrainMaterial->setShaderDefines("SKIP_TEXTURES");
    terrainMaterial->setShaderDefines("USE_SHADING_PHONG");
    terrainMaterial->setShaderDefines("MAX_TEXTURE_LAYERS " + to_stringImpl(Attorney::TerrainLoader::textureLayerCount(*terrain)));
    terrainMaterial->setShaderDefines("CURRENT_TEXTURE_COUNT " + to_stringImpl(textureCount));

    terrainMaterial->setShaderProgram("terrainTess", true);
    terrainMaterial->setShaderProgram("terrainTess.Shadow", RenderStage::SHADOW, true);
    terrainMaterial->setShaderProgram("terrainTess.PrePass", RenderPassType::DEPTH_PASS, true);

    ResourceDescriptor textureWaterCaustics("Terrain Water Caustics_" + name);
    textureWaterCaustics.setResourceLocation(terrainMapLocation);
    textureWaterCaustics.setResourceName(terrainDescriptor->getVariable("waterCaustics"));
    textureWaterCaustics.setPropertyDescriptor(albedoSampler);
    textureWaterCaustics.setEnumValue(to_base(TextureType::TEXTURE_2D));
    terrainMaterial->setTexture(ShaderProgram::TextureUsage::UNIT0, CreateResource<Texture>(terrain->parentResourceCache(), textureWaterCaustics));

    ResourceDescriptor underwaterAlbedoTexture("Terrain Underwater Albedo_" + name);
    underwaterAlbedoTexture.setResourceLocation(terrainMapLocation);
    underwaterAlbedoTexture.setResourceName(terrainDescriptor->getVariable("underwaterAlbedoTexture"));
    underwaterAlbedoTexture.setPropertyDescriptor(albedoSampler);
    underwaterAlbedoTexture.setEnumValue(to_base(TextureType::TEXTURE_2D));
    terrainMaterial->setTexture(ShaderProgram::TextureUsage::UNIT1, CreateResource<Texture>(terrain->parentResourceCache(), underwaterAlbedoTexture));

    ResourceDescriptor underwaterDetailTexture("Terrain Underwater Detail_" + name);
    underwaterDetailTexture.setResourceLocation(terrainMapLocation);
    underwaterDetailTexture.setResourceName(terrainDescriptor->getVariable("underwaterDetailTexture"));
    underwaterDetailTexture.setPropertyDescriptor(albedoSampler);
    underwaterDetailTexture.setEnumValue(to_base(TextureType::TEXTURE_2D));
    terrainMaterial->setTexture(ShaderProgram::TextureUsage::NORMALMAP, CreateResource<Texture>(terrain->parentResourceCache(), underwaterDetailTexture));

    ResourceDescriptor heightMapTexture("Terrain Underwater Detail_" + name);
    heightMapTexture.setResourceLocation(terrainDescriptor->getVariable("heightmapLocation"));
    heightMapTexture.setResourceName(terrainDescriptor->getVariable("heightmap"));
    heightMapTexture.setPropertyDescriptor(albedoSampler);
    heightMapTexture.setEnumValue(to_base(TextureType::TEXTURE_2D));

    terrainMaterial->setTexture(ShaderProgram::TextureUsage::OPACITY, CreateResource<Texture>(terrain->parentResourceCache(), heightMapTexture));
    terrainMaterial->setShaderLoadThreaded(false);

    terrainMaterial->dumpToFile(false);
    terrain->setMaterialTpl(terrainMaterial);

    // Generate a render state
    RenderStateBlock terrainRenderState;
    terrainRenderState.setCullMode(CullMode::CCW);
    // Generate a render state for drawing reflections
    RenderStateBlock terrainRenderStateReflection;
    terrainRenderStateReflection.setCullMode(CullMode::CW);
    // Generate a shadow render state
    RenderStateBlock terrainRenderStateDepth;
    terrainRenderStateDepth.setCullMode(CullMode::CW);
    // terrainDescDepth.setZBias(1.0f, 2.0f);
    terrainRenderStateDepth.setColourWrites(true, true, false, false);

    terrainMaterial->setRenderStateBlock(terrainRenderState.getHash());
    terrainMaterial->setRenderStateBlock(terrainRenderStateReflection.getHash(), RenderStage::REFLECTION);
    terrainMaterial->setRenderStateBlock(terrainRenderStateDepth.getHash(), RenderStage::SHADOW);

    return context.gfx().loadInContext(threadedLoading ? CurrentContext::GFX_LOADING_CTX : CurrentContext::GFX_RENDERING_CTX,
                                       [terrain, terrainDescriptor, onLoadCallback](const Task& parent) {
                                            loadThreadedResources(terrain, std::move(terrainDescriptor), std::move(onLoadCallback));
                                       });
}

bool TerrainLoader::loadThreadedResources(std::shared_ptr<Terrain> terrain,
                                          const std::shared_ptr<TerrainDescriptor> terrainDescriptor,
                                          DELEGATE_CBK<void, CachedResource_wptr> onLoadCallback) {

    ResourceDescriptor infinitePlane("infinitePlane");
    infinitePlane.setFlag(true);  // No default material

    vec2<F32>& terrainScaleFactor =
        Attorney::TerrainLoader::scaleFactor(*terrain);

    Attorney::TerrainLoader::chunkSize(*terrain) = terrainDescriptor->getChunkSize();
    terrainScaleFactor.set(terrainDescriptor->getScale());

    const vec2<U16>& terrainDimensions = terrainDescriptor->getDimensions();
    
    U16 heightmapWidth = terrainDimensions.width;
    U16 heightmapHeight = terrainDimensions.height;
    const stringImpl& terrainMapLocation = terrainDescriptor->getVariable("heightmapLocation");

    stringImpl terrainRawFile(terrainDescriptor->getVariable("heightmap"));

    vec2<U16>& dimensions = Attorney::TerrainLoader::dimensions(*terrain);
    Attorney::TerrainLoader::dimensions(*terrain).set(heightmapWidth, heightmapHeight);

    if (dimensions.x % 2 == 0) {
        dimensions.x++;
    }
    if (dimensions.y % 2 == 0) {
        dimensions.y++;
    }
    Console::d_printfn(Locale::get(_ID("TERRAIN_INFO")), dimensions.x, dimensions.y);

    I32 terrainWidth = (I32)dimensions.x;
    I32 terrainHeight = (I32)dimensions.y;
    F32 minAltitude = terrainDescriptor->getAltitudeRange().x;
    F32 maxAltitude = terrainDescriptor->getAltitudeRange().y;

    BoundingBox& terrainBB = Attorney::TerrainLoader::boundingBox(*terrain);
    terrainBB.set(vec3<F32>(-terrainWidth * 0.5f, minAltitude, -terrainHeight * 0.5f),
                  vec3<F32>(terrainWidth * 0.5f, maxAltitude, terrainHeight * 0.5f));

    terrainBB.translate(terrainDescriptor->getPosition());
    terrainBB.multiply(vec3<F32>(terrainScaleFactor.x, terrainScaleFactor.y,
                                 terrainScaleFactor.x));

    const vec3<F32>& bMin = terrainBB.getMin();
    const vec3<F32>& bMax = terrainBB.getMax();
    F32 yOffset = terrainDescriptor->getPosition().y;

    stringImpl cacheLocation(terrainMapLocation + terrainRawFile + ".cache");
    STUBBED("ToDo: Move image data into the ByteBuffer as well to avoid reading height data from images each time we load the terrain! -Ionut");

    ByteBuffer terrainCache;
    if (!terrainCache.loadFromFile(cacheLocation)) {
        F32 altitudeRange = maxAltitude - minAltitude;
        F32 yScaleFactor = terrainScaleFactor.y;

        vectorImpl<U16> heightValues;
        if (terrainDescriptor->is16Bit()) {
            assert(heightmapWidth != 0 && heightmapHeight != 0);
            // only raw files for 16 bit support
            assert(hasExtension(terrainRawFile, "raw"));
            // Read File Data

            vectorImpl<Byte> data;
            readFile(terrainMapLocation + terrainRawFile, data, FileType::BINARY);
            if (data.empty()) {
                return false;
            }

            U32 positionCount = to_U32(data.size());
            heightValues.reserve(positionCount / 2);
            for (U32 i = 0; i < positionCount + 1; i += 2) {
                heightValues.push_back((data[i + 1] << 8) | data[i]);
            }

        } else {
            ImageTools::ImageData img;
            ImageTools::ImageDataInterface::CreateImageData(terrainMapLocation + terrainRawFile, img);
            assert(terrainDimensions == img.dimensions());
            // data will be destroyed when img gets out of scope
            const U8* data = (const U8*)img.data();
            assert(data);
            heightValues.insert(std::end(heightValues), &data[0], &data[img.imageLayers().front()._data.size()]);
        }

        terrain->_physicsVerts.resize(terrainWidth * terrainHeight);

        // scale and translate all height by half to convert from 0-255 (0-65335) to -127 - 128 (-32767 - 32768)
        if (terrainDescriptor->is16Bit()) {
            const F32 fMax = to_F32(std::numeric_limits<U16>::max() + 1);
            
            #pragma omp parallel for
            for (I32 j = 0; j < terrainHeight; j++) {
                for (I32 i = 0; i < terrainWidth; i++) {
                    U32 idxHM = TER_COORD(i, j, terrainWidth);

                    U32 idxIMG = TER_COORD<U32>(i < to_I32(heightmapWidth) ? i : i - 1,
                                                j < to_I32(heightmapHeight) ? j : j - 1,
                                                heightmapWidth);

                    vec3<F32> vertexData(bMin.x + (to_F32(i)) * (bMax.x - bMin.x) / (terrainWidth - 1),                           // X
                                        ((minAltitude + altitudeRange * (heightValues[idxIMG] / fMax)) * yScaleFactor) + yOffset, // Y
                                        bMin.z + (to_F32(j)) * (bMax.z - bMin.z) / (terrainHeight - 1));                          // Z
                    #pragma omp critical
                    {
                        terrain->_physicsVerts[idxHM]._position.set(vertexData);
                    }
                }
            }
        } else {
            const F32 byteMax = to_F32(std::numeric_limits<U8>::max() + 1);

            #pragma omp parallel for
            for (I32 j = 0; j < terrainHeight; j++) {
                for (I32 i = 0; i < terrainWidth; i++) {
                    U32 idxHM = TER_COORD(i, j, terrainWidth);

                    U32 idxIMG = TER_COORD<U32>(i < to_I32(heightmapWidth) ? i : i - 1,
                                                j < to_I32(heightmapHeight) ? j : j - 1,
                                                heightmapWidth);

                    F32 h = ((heightValues[idxIMG * 3 + 0] +
                              heightValues[idxIMG * 3 + 1] +
                              heightValues[idxIMG * 3 + 2]) / 3.0f) / byteMax;

                    vec3<F32> vertexData(bMin.x + (to_F32(i)) * (bMax.x - bMin.x) / (terrainWidth - 1),   //X
                                         ((minAltitude + altitudeRange * h) * yScaleFactor) + yOffset,    //Y
                                         bMin.z + (to_F32(j)) * (bMax.z - bMin.z) / (terrainHeight - 1)); //Z

                    
                    #pragma omp critical
                    {
                        terrain->_physicsVerts[idxHM]._position.set(vertexData);
                    }
                }
            }
        }

        heightValues.clear();

        I32 offset = 2;
        U32 idx = 0, idx0 = 0, idx1 = 0;
    
       #pragma omp parallel for
        for (I32 j = offset; j < terrainHeight - offset; j++) {
            for (I32 i = offset; i < terrainWidth - offset; i++) {
                vec3<F32> vU, vV, vUV;

                idx = TER_COORD(i, j, terrainWidth);

                vU.set(terrain->_physicsVerts[TER_COORD(i + offset, j + 0, terrainWidth)]._position -
                       terrain->_physicsVerts[TER_COORD(i - offset, j + 0, terrainWidth)]._position);
                vV.set(terrain->_physicsVerts[TER_COORD(i + 0, j + offset, terrainWidth)]._position -
                       terrain->_physicsVerts[TER_COORD(i + 0, j - offset, terrainWidth)]._position);

                vUV.cross(vV, vU);
                vUV.normalize();
                vU = -vU;
                vU.normalize();
                #pragma omp critical
                {
                    terrain->_physicsVerts[idx]._normal = Util::PACK_VEC3(vUV);
                    terrain->_physicsVerts[idx]._tangent = Util::PACK_VEC3(vU);
                }
            }
        }
        
        vec3<F32> normal, tangent;
        for (I32 j = 0; j < offset; j++) {
            for (I32 i = 0; i < terrainWidth; i++) {
                idx0 = TER_COORD(i, j, terrainWidth);
                idx1 = TER_COORD(i, offset, terrainWidth);

                normal.set(Util::UNPACK_VEC3(terrain->_physicsVerts[idx1]._normal));
                tangent.set(Util::UNPACK_VEC3(terrain->_physicsVerts[idx1]._tangent));

                terrain->_physicsVerts[idx0]._normal = Util::PACK_VEC3(normal);
                terrain->_physicsVerts[idx0]._tangent = Util::PACK_VEC3(tangent);

                idx0 = TER_COORD(i, terrainHeight - 1 - j, terrainWidth);
                idx1 = TER_COORD(i, terrainHeight - 1 - offset, terrainWidth);

                normal.set(Util::UNPACK_VEC3(terrain->_physicsVerts[idx1]._normal));
                tangent.set(Util::UNPACK_VEC3(terrain->_physicsVerts[idx1]._tangent));

                terrain->_physicsVerts[idx0]._normal = Util::PACK_VEC3(normal);
                terrain->_physicsVerts[idx0]._tangent = Util::PACK_VEC3(tangent);
            }
        }

        for (I32 i = 0; i < offset; i++) {
            for (I32 j = 0; j < terrainHeight; j++) {
                idx0 = TER_COORD(i, j, terrainWidth);
                idx1 = TER_COORD(offset, j, terrainWidth);

                normal.set(Util::UNPACK_VEC3(terrain->_physicsVerts[idx1]._normal));
                tangent.set(Util::UNPACK_VEC3(terrain->_physicsVerts[idx1]._tangent));

                terrain->_physicsVerts[idx0]._normal = Util::PACK_VEC3(normal);
                terrain->_physicsVerts[idx0]._tangent = Util::PACK_VEC3(tangent);

                idx0 = TER_COORD(terrainWidth - 1 - i, j, terrainWidth);
                idx1 = TER_COORD(terrainWidth - 1 - offset, j, terrainWidth);

                normal.set(Util::UNPACK_VEC3(terrain->_physicsVerts[idx1]._normal));
                tangent.set(Util::UNPACK_VEC3(terrain->_physicsVerts[idx1]._tangent));

                terrain->_physicsVerts[idx0]._normal = Util::PACK_VEC3(normal);
                terrain->_physicsVerts[idx0]._tangent = Util::PACK_VEC3(tangent);
            }
        }
        terrainCache << terrain->_physicsVerts;
        terrainCache.dumpToFile(cacheLocation);
    } else {
        terrainCache >> terrain->_physicsVerts;
    }

    Test::init(terrain->getGeometryVB());

    initializeVegetation(terrain, terrainDescriptor);
    Attorney::TerrainLoader::buildQuadtree(*terrain);

    ResourceDescriptor planeShaderDesc("terrainPlane.Colour");
    ShaderProgram_ptr planeShader = CreateResource<ShaderProgram>(terrain->parentResourceCache(), planeShaderDesc);
    planeShaderDesc.setResourceName("terrainPlane.Depth");
    ShaderProgram_ptr planeDepthShader = CreateResource<ShaderProgram>(terrain->parentResourceCache(), planeShaderDesc);
    Quad3D_ptr plane = CreateResource<Quad3D>(terrain->parentResourceCache(), infinitePlane);
    // our bottom plane is placed at the bottom of our water entity
    F32 height = bMin.y + yOffset;
    F32 farPlane = 2.0f * terrainBB.getWidth();

    plane->setCorner(Quad3D::CornerLocation::TOP_LEFT, vec3<F32>(-farPlane * 1.5f, height, -farPlane * 1.5f));
    plane->setCorner(Quad3D::CornerLocation::TOP_RIGHT, vec3<F32>(farPlane * 1.5f, height, -farPlane * 1.5f));
    plane->setCorner(Quad3D::CornerLocation::BOTTOM_LEFT, vec3<F32>(-farPlane * 1.5f, height, farPlane * 1.5f));
    plane->setCorner(Quad3D::CornerLocation::BOTTOM_RIGHT, vec3<F32>(farPlane * 1.5f, height, farPlane * 1.5f));

    Attorney::TerrainLoader::plane(*terrain, plane, planeShader, planeDepthShader);

    ResourceDescriptor renderGeometry("TerrainRenderGeometry");
    renderGeometry.setFlag(true);  // No default material
    renderGeometry.setUserPtr((void*)(&dimensions));

    Console::printfn(Locale::get(_ID("TERRAIN_LOAD_END")), terrain->getName().c_str());
    return terrain->load(onLoadCallback);
}

void TerrainLoader::initializeVegetation(std::shared_ptr<Terrain> terrain,
                                         const std::shared_ptr<TerrainDescriptor> terrainDescriptor) {
    U8 textureCount = 0;
    stringImpl textureName;

    stringImpl currentImage = terrainDescriptor->getVariable("grassBillboard1");
    if (!currentImage.empty()) {
        textureName += currentImage;
        textureCount++;
    }

    currentImage = terrainDescriptor->getVariable("grassBillboard2");
    if (!currentImage.empty()) {
        textureName += "," + currentImage;
        textureCount++;
    }

    currentImage = terrainDescriptor->getVariable("grassBillboard3");
    if (!currentImage.empty()) {
        textureName += "," + currentImage;
        textureCount++;
    }

    currentImage = terrainDescriptor->getVariable("grassBillboard4");
    if (!currentImage.empty()) {
        textureName += "," + currentImage;
        textureCount++;
    }

    if (textureCount == 0){
        return;
    }

    SamplerDescriptor grassSampler;
    grassSampler.setAnisotropy(0);
    grassSampler.setWrapMode(TextureWrap::CLAMP);
    ResourceDescriptor textureDetailMaps("Vegetation Billboards");
    textureDetailMaps.setEnumValue(to_base(TextureType::TEXTURE_2D_ARRAY));
    textureDetailMaps.setID(textureCount);
    textureDetailMaps.setResourceLocation(terrainDescriptor->getVariable("grassMapLocation"));
    textureDetailMaps.setResourceName(textureName);
    textureDetailMaps.setPropertyDescriptor(grassSampler);
    Texture_ptr grassBillboardArray = CreateResource<Texture>(terrain->parentResourceCache(), textureDetailMaps);

    VegetationDetails& vegDetails = Attorney::TerrainLoader::vegetationDetails(*terrain);
    vegDetails.billboardCount = textureCount;
    vegDetails.name = terrain->getName() + "_grass";
    vegDetails.grassDensity = terrainDescriptor->getGrassDensity();
    vegDetails.grassScale = terrainDescriptor->getGrassScale();
    vegDetails.treeDensity = terrainDescriptor->getTreeDensity();
    vegDetails.treeScale = terrainDescriptor->getTreeScale();
    vegDetails.grassBillboards = grassBillboardArray;
    vegDetails.grassShaderName = "grass";
    vegDetails.parentTerrain = terrain;

    vegDetails.map.reset(new ImageTools::ImageData);
    ImageTools::ImageDataInterface::CreateImageData(
        terrainDescriptor->getVariable("grassMapLocation") + 
        terrainDescriptor->getVariable("grassMap"),
        *vegDetails.map);
}

bool TerrainLoader::Save(const char* fileName) { return true; }

bool TerrainLoader::Load(const char* filename) { return true; }
};

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

Diff revisions: vs.
Revision Author Commited Message
881 Diff Diff IonutCava picture IonutCava Tue 21 Mar, 2017 22:07:37 +0000

[IonutCava]
- Multi draw command bug fix: drawCount > 1 should properly register all commands in the command buffer
- More tessellated terrain updates and fixes (still Work In Progress)

880 Diff Diff IonutCava picture IonutCava Mon 20 Mar, 2017 17:27:13 +0000

[IonutCava]
- New tessellated terrain system based on this: http://victorbush.com/2015/01/tessellated-terrain/
— Work in progress: hardcoded values, new code is in Test namespace
- Split terrain geometry in two:
— tessellated rendering data
— physics verts + indices (used for collisions, vegetation, etc)
- Old Chunk system is used only for culling objects and speeding up collision detection

872 Diff Diff IonutCava picture IonutCava Mon 06 Mar, 2017 23:23:20 +0000

[IonutCava]
- Optimise static casts

869 Diff Diff IonutCava picture IonutCava Sun 26 Feb, 2017 23:25:54 +0000

[IonutCava]
- Reduce loading time using profile guided optimizations
- Camera/Quaternion work in an attempt to fix a weird Yaw-rotation bug.

867 Diff Diff IonutCava picture IonutCava Mon 20 Feb, 2017 17:01:12 +0000

[IonutCava]
- Rename to_XNN and to_const_XNN functions to reflect the target data type they are converting to.
- Cleanup Angle namespace and remove all “inDegrees” parameters from rotation functions. Use aliases to differentiate between Degree and Radian parameters.
- Profile guided optimizations.

866 Diff Diff IonutCava picture IonutCava Mon 20 Feb, 2017 13:57:52 +0000

[IonutCava]
- Cleanup terrain chunk generation

863 Diff Diff IonutCava picture IonutCava Wed 15 Feb, 2017 16:27:26 +0000

[IonutCava]
- Split Resource class into Resource and CachedResource
— CachedResource is the only resource held in a ResourceCache and loaded from a ResourceDescriptor
— CachedResource is mapped by its creation descriptor’s hash value, instead of the resource name
-— Multiple cached resources can now exist with the same name if the have different properties, for example.

860 Diff Diff IonutCava picture IonutCava Mon 13 Feb, 2017 21:07:59 +0000

[IonutCava]
- Fix shared_ptr leak in resource loading callbacks

859 Diff Diff IonutCava picture IonutCava Mon 13 Feb, 2017 17:18:06 +0000

[IonutCava]
- Multi-threaded mesh load
- ByteBuffer fixes and unit test

858 IonutCava picture IonutCava Sun 12 Feb, 2017 20:55:05 +0000

[IonutCava]
- More resource loading updates