Subversion Repository Public Repository

Divide-Framework

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

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

#include "Headers/Material.h"

#include "Rendering/Headers/Renderer.h"
#include "Utility/Headers/Localization.h"
#include "Managers/Headers/SceneManager.h"
#include "Platform/Video/Headers/GFXDevice.h"

#include "Core/Headers/Console.h"
#include "Core/Resources/Headers/ResourceCache.h"

namespace Divide {

namespace {
#if defined(_DEBUG)
    const U32 g_MaxShadersComputedPerFrame = 2;
#else
    const U32 g_MaxShadersComputedPerFrame = 3;
#endif
};

bool Material::_shadersComputedThisFrame = false;
U32 Material::_totalShaderComputeCountThisFrame = 0;
U32 Material::_totalShaderComputeCount = 0;

Material::Material(const stringImpl& name)
    : Resource(name),
      FrameListener(),
      _parallaxFactor(1.0f),
      _dirty(false),
      _doubleSided(false),
      _shaderThreadedLoad(true),
      _hardwareSkinning(false),
      _useAlphaTest(false),
      _dumpToFile(true),
      _translucencyCheck(true),
      _highPriority(false),
      _reflectionIndex(-1),
      _refractionIndex(-1),
      _shadingMode(ShadingMode::COUNT),
      _bumpMethod(BumpMethod::NONE)
{
    _textures.fill(nullptr);
    _textureExtenalFlag.fill(false);
    _textureExtenalFlag[to_const_uint(ShaderProgram::TextureUsage::REFLECTION)] = true;
    _textureExtenalFlag[to_const_uint(ShaderProgram::TextureUsage::REFRACTION)] = true;
    defaultReflectionTexture(nullptr, 0);
    defaultRefractionTexture(nullptr, 0);

    REGISTER_FRAME_LISTENER(this, 9999);

    _operation = TextureOperation::REPLACE;

    /// Normal state for final rendering
    RenderStateBlock stateDescriptor;
    stateDescriptor.setZFunc(ComparisonFunction::LEQUAL);
    setRenderStateBlock(stateDescriptor.getHash(), RenderStage::DISPLAY);
    setRenderStateBlock(stateDescriptor.getHash(), RenderStage::REFRACTION);
    /// the reflection descriptor is the same as the normal descriptor
    RenderStateBlock reflectorDescriptor(stateDescriptor);
    setRenderStateBlock(reflectorDescriptor.getHash(), RenderStage::REFLECTION);
    /// the z-pre-pass descriptor does not process colours
    RenderStateBlock zPrePassDescriptor(stateDescriptor);
    zPrePassDescriptor.setColourWrites(true, true, true, false);
    zPrePassDescriptor.setZFunc(ComparisonFunction::LESS);
    setRenderStateBlock(zPrePassDescriptor.getHash(), RenderStage::Z_PRE_PASS);
    /// A descriptor used for rendering to depth map
    RenderStateBlock shadowDescriptor(stateDescriptor);
    shadowDescriptor.setCullMode(CullMode::CCW);
    /// set a polygon offset
    shadowDescriptor.setZBias(1.0f, 2.0f);
    /// ignore half of the colours 
    /// Some shadowing techniques require drawing to the a colour buffer
    shadowDescriptor.setColourWrites(true, true, false, false);
    setRenderStateBlock(shadowDescriptor.getHash(), RenderStage::SHADOW, 0);
    zPrePassDescriptor.setColourWrites(false, false, false, false);
    setRenderStateBlock(shadowDescriptor.getHash(), RenderStage::SHADOW, 1);
    setRenderStateBlock(shadowDescriptor.getHash(), RenderStage::SHADOW, 2);
}

Material::~Material()
{
    UNREGISTER_FRAME_LISTENER(this);
}

bool Material::frameStarted(const FrameEvent& evt) {
    return true;
}

bool Material::frameEnded(const FrameEvent& evt) {
    if (_shadersComputedThisFrame) {
        _totalShaderComputeCount += _totalShaderComputeCountThisFrame;
        _totalShaderComputeCountThisFrame = 0;
        _shadersComputedThisFrame = false;
    }

    return true;
}

Material_ptr Material::clone(const stringImpl& nameSuffix) {
    DIVIDE_ASSERT(!nameSuffix.empty(),
                  "Material error: clone called without a valid name suffix!");

    const Material& base = *this;
    Material_ptr cloneMat = CreateResource<Material>(ResourceDescriptor(getName() + nameSuffix));

    cloneMat->_shadingMode = base._shadingMode;
    cloneMat->_translucencyCheck = base._translucencyCheck;
    cloneMat->_dumpToFile = base._dumpToFile;
    cloneMat->_useAlphaTest = base._useAlphaTest;
    cloneMat->_doubleSided = base._doubleSided;
    cloneMat->_hardwareSkinning = base._hardwareSkinning;
    cloneMat->_shaderThreadedLoad = base._shaderThreadedLoad;
    cloneMat->_operation = base._operation;
    cloneMat->_bumpMethod = base._bumpMethod;
    cloneMat->_parallaxFactor = base._parallaxFactor;
    cloneMat->_reflectionIndex = base._reflectionIndex;
    cloneMat->_refractionIndex = base._refractionIndex;
    cloneMat->_defaultReflection = base._defaultReflection;
    cloneMat->_defaultRefraction = base._defaultRefraction;

    cloneMat->_translucencySource.clear();

    for (U8 i = 0; i < to_const_uint(RenderStage::COUNT); i++) {
        cloneMat->_shaderModifier[i] = base._shaderModifier[i];
        cloneMat->_shaderInfo[i] = _shaderInfo[i];
        for (U8 j = 0; j < _defaultRenderStates[i].size(); ++j) {
            cloneMat->_defaultRenderStates[i][j] = _defaultRenderStates[i][j];
        }
    }

    for (const TranslucencySource& trans : base._translucencySource) {
        cloneMat->_translucencySource.push_back(trans);
    }

    for (U8 i = 0; i < to_ubyte(base._textures.size()); ++i) {
        ShaderProgram::TextureUsage usage = static_cast<ShaderProgram::TextureUsage>(i);
        if (!isExternalTexture(usage)) {
            Texture_ptr tex = base._textures[i];
            if (tex) {
                cloneMat->setTexture(usage, tex);
            }
        }
    }
    for (const std::pair<Texture_ptr, U8>& tex : base._customTextures) {
        if (tex.first) {
            cloneMat->addCustomTexture(tex.first, tex.second);
        }
    }

    cloneMat->_shaderData = base._shaderData;

    return cloneMat;
}

void Material::update(const U64 deltaTime) {

    for (ShaderInfo& info : _shaderInfo) {
        if (info._shaderCompStage ==
            ShaderInfo::ShaderCompilationStage::PENDING) {
            if (info._shaderRef->getState() == ResourceState::RES_LOADED) {
                info._shaderCompStage =
                    ShaderInfo::ShaderCompilationStage::COMPUTED;
            }
        }
    }

    // build one shader per frame
    computeShaderInternal();

    for (ShaderInfo& info : _shaderInfo) {
        if (info._shaderCompStage ==
                ShaderInfo::ShaderCompilationStage::QUEUED ||
            info._shaderCompStage ==
                ShaderInfo::ShaderCompilationStage::REQUESTED ||
            info._shaderCompStage ==
                ShaderInfo::ShaderCompilationStage::PENDING) {
            return;
        }
    }

    clean();
}

size_t Material::getRenderStateBlock(RenderStage currentStage, I32 variant) {
    assert(variant >= 0 && variant < _defaultRenderStates[to_uint(currentStage)].size());
    return _defaultRenderStates[to_uint(currentStage)][variant];
}

// base = base texture
// second = second texture used for multitexturing
// bump = bump map
bool Material::setTexture(ShaderProgram::TextureUsage textureUsageSlot,
                          const Texture_ptr& texture,
                          const TextureOperation& op) {
    bool computeShaders = false;
    U32 slot = to_uint(textureUsageSlot);

    if (textureUsageSlot == ShaderProgram::TextureUsage::UNIT1) {
        _operation = op;
    }

    if (texture && textureUsageSlot == ShaderProgram::TextureUsage::OPACITY) {
        Texture_ptr& diffuseMap = _textures[to_const_uint(ShaderProgram::TextureUsage::UNIT0)];
        if (diffuseMap && texture->getGUID() == diffuseMap->getGUID()) {
            return false;
        }
    }

    if (!_translucencyCheck) {
         _translucencyCheck =
            (textureUsageSlot == ShaderProgram::TextureUsage::UNIT0 ||
             textureUsageSlot == ShaderProgram::TextureUsage::OPACITY);
    }

    if (!_textures[slot]) {
        if (textureUsageSlot != ShaderProgram::TextureUsage::REFLECTION &&
            textureUsageSlot != ShaderProgram::TextureUsage::REFRACTION) {
            // if we add a new type of texture recompute shaders
            computeShaders = true;
        }
    }

    _textures[slot] = texture;

    if (computeShaders) {
        recomputeShaders();
    }

    _dirty = textureUsageSlot != ShaderProgram::TextureUsage::REFLECTION &&
             textureUsageSlot != ShaderProgram::TextureUsage::REFRACTION;

    return true;
}

// Here we set the shader's name
void Material::setShaderProgram(const stringImpl& shader,
                                RenderStage renderStage,
                                const bool computeOnAdd) {
    _shaderInfo[to_uint(renderStage)]._customShader = true;
    setShaderProgramInternal(shader, renderStage, computeOnAdd);
}

void Material::setShaderProgramInternal(const stringImpl& shader,
                                        RenderStage renderStage,
                                        const bool computeOnAdd) {

    U32 stageIndex = to_uint(renderStage);
    ShaderInfo& info = _shaderInfo[stageIndex];
    // if we already had a shader assigned ...
    if (!info._shader.empty()) {
        // and we are trying to assign the same one again, return.
        info._shaderRef = FindResourceImpl<ShaderProgram>(info._shader);
        if (info._shader.compare(shader) != 0) {
            Console::printfn(Locale::get(_ID("REPLACE_SHADER")), info._shader.c_str(), shader.c_str());
        }
    }

    (!shader.empty()) ? info._shader = shader : info._shader = "NULL";

    ResourceDescriptor shaderDescriptor(info._shader);
    stringstreamImpl ss;
    if (!info._shaderDefines.empty()) {
        for (stringImpl& shaderDefine : info._shaderDefines) {
            ss << shaderDefine;
            ss << ",";
        }
    }
    ss << "DEFINE_PLACEHOLDER";
    shaderDescriptor.setPropertyList(ss.str());
    shaderDescriptor.setThreadedLoading(_shaderThreadedLoad);

    ShaderQueueElement queueElement(stageIndex, shaderDescriptor);

    if (computeOnAdd) {
        _shaderComputeQueue.push_front(queueElement);
    } else {
        _shaderComputeQueue.push_back(queueElement);
    }
    
    info._shaderCompStage = ShaderInfo::ShaderCompilationStage::QUEUED;

    if (computeOnAdd) {
        computeShaderInternal();
    }
}

void Material::clean() {
    if (_dirty && _dumpToFile) {
        isTranslucent();
#if !defined(DEBUG)
        XML::dumpMaterial(*this);
#endif
        _dirty = false;
    }
}

void Material::recomputeShaders() {
    for (ShaderInfo& info : _shaderInfo) {
        if (!info._customShader) {
            info._shaderCompStage = ShaderInfo::ShaderCompilationStage::REQUESTED;
        }
    }
}

bool Material::canDraw(RenderStage renderStage) {
    for (U32 i = 0; i < to_const_uint(RenderStage::COUNT); ++i) {
        ShaderInfo& info = _shaderInfo[i];
        if (info._shaderCompStage != ShaderInfo::ShaderCompilationStage::COMPUTED) {
            computeShader(static_cast<RenderStage>(i), _highPriority);
            return false;
        }
    }

    return true;
}

void Material::updateReflectionIndex(I32 index) {
    _reflectionIndex = index;
    if (_reflectionIndex > -1) {
        RenderTarget& reflectionTarget = GFX_DEVICE.renderTarget(RenderTargetID::REFLECTION, index);
        const Texture_ptr& refTex = reflectionTarget.getAttachment(RTAttachment::Type::Colour, 0).asTexture();
        setTexture(ShaderProgram::TextureUsage::REFLECTION, refTex);
    } else {
        setTexture(ShaderProgram::TextureUsage::REFLECTION, _defaultReflection.first);
    }
}

void Material::updateRefractionIndex(I32 index) {
    _refractionIndex = index;
    if (_refractionIndex > -1) {
        RenderTarget& refractionTarget = GFX_DEVICE.renderTarget(RenderTargetID::REFRACTION, index);
        const Texture_ptr& refTex = refractionTarget.getAttachment(RTAttachment::Type::Colour, 0).asTexture();
        setTexture(ShaderProgram::TextureUsage::REFRACTION, refTex);
    } else {
        setTexture(ShaderProgram::TextureUsage::REFRACTION, _defaultRefraction.first);
    }
}


void Material::defaultReflectionTexture(const Texture_ptr& reflectionPtr, U32 arrayIndex) {
    _defaultReflection.first = reflectionPtr;
    _defaultReflection.second = arrayIndex;
}

void Material::defaultRefractionTexture(const Texture_ptr& refractionPtr, U32 arrayIndex) {
    _defaultRefraction.first = refractionPtr;
    _defaultRefraction.second = arrayIndex;
}


/// If the current material doesn't have a shader associated with it, then add
/// the default ones.
bool Material::computeShader(RenderStage renderStage, const bool computeOnAdd){

    ShaderInfo& info = _shaderInfo[to_uint(renderStage)];
    if (info._shaderCompStage ==
        ShaderInfo::ShaderCompilationStage::UNHANDLED) {
        info._shaderCompStage = ShaderInfo::ShaderCompilationStage::REQUESTED;
        return false;
    }

    if (info._shaderCompStage != ShaderInfo::ShaderCompilationStage::REQUESTED) {
        return info._shaderCompStage == ShaderInfo::ShaderCompilationStage::COMPUTED;
    }

    U32 slot0 = to_const_uint(ShaderProgram::TextureUsage::UNIT0);
    U32 slot1 = to_const_uint(ShaderProgram::TextureUsage::UNIT1);
    U32 slotOpacity = to_const_uint(ShaderProgram::TextureUsage::OPACITY);

    if ((_textures[slot0] &&
         _textures[slot0]->getState() != ResourceState::RES_LOADED) ||
        (_textures[slotOpacity] &&
         _textures[slotOpacity]->getState() != ResourceState::RES_LOADED)) {
        return false;
    }

    DIVIDE_ASSERT(
        _shadingMode != ShadingMode::COUNT,
        "Material computeShader error: Invalid shading mode specified!");

    info._shaderDefines.clear();

    if (_textures[slot0]) {
        _shaderData._textureCount = 1;
    }

    if (_textures[slot1]) {
        if (!_textures[slot0]) {
            std::swap(_textures[slot0], _textures[slot1]);
            _shaderData._textureCount = 1;
            _translucencyCheck = true;
        } else {
            _shaderData._textureCount = 2;
        }
    }

    bool deferredPassShader = SceneManager::instance().getRenderer().getType() !=
                              RendererType::RENDERER_FORWARD_PLUS;
    bool depthPassShader = renderStage == RenderStage::SHADOW ||
                           renderStage == RenderStage::Z_PRE_PASS;

    // the base shader is either for a Deferred Renderer or a Forward  one ...
    stringImpl shader =
        (deferredPassShader ? "DeferredShadingPass1"
                            : (depthPassShader ? "depthPass" : "lighting"));

    if (Config::Profile::DISABLE_SHADING) {
        shader = "passThrough";
        setShaderProgramInternal(shader, renderStage, computeOnAdd);
        return false;;
    }

    if (depthPassShader && renderStage == RenderStage::SHADOW) {
        setShaderDefines(renderStage, "SHADOW_PASS");
        shader += ".Shadow";
    }

    // What kind of effects do we need?
    if (_textures[slot0]) {
        // Bump mapping?
        if (_textures[to_const_uint(ShaderProgram::TextureUsage::NORMALMAP)] &&
            _bumpMethod != BumpMethod::NONE) {
            setShaderDefines(renderStage, "COMPUTE_TBN");
            shader += ".Bump";  // Normal Mapping
            if (_bumpMethod == BumpMethod::PARALLAX) {
                shader += ".Parallax";
                setShaderDefines(renderStage, "USE_PARALLAX_MAPPING");
            } else if (_bumpMethod == BumpMethod::RELIEF) {
                shader += ".Relief";
                setShaderDefines(renderStage, "USE_RELIEF_MAPPING");
            }
        } else {
            // Or simple texture mapping?
            shader += ".Texture";
        }
    } else {
        setShaderDefines(renderStage, "SKIP_TEXTURES");
        shader += ".NoTexture";
    }

    if (_textures[to_const_uint(ShaderProgram::TextureUsage::SPECULAR)]) {
        shader += ".Specular";
        setShaderDefines(renderStage, "USE_SPECULAR_MAP");
    }

    if (isTranslucent()) {
        bool diffuseOpacityDefined = false;
        for (Material::TranslucencySource source : _translucencySource) {
            if (source == TranslucencySource::OPACITY_MAP) {
                shader += ".OpacityMap";
                setShaderDefines(renderStage, "USE_OPACITY_MAP");
            }
            if (source == TranslucencySource::DIFFUSE ||
                source == TranslucencySource::DIFFUSE_MAP) {
                if (!diffuseOpacityDefined) {
                    shader += ".DiffuseAlpha";
                    setShaderDefines(renderStage, "USE_OPACITY_DIFFUSE");
                    diffuseOpacityDefined = true;
                }
            }
        }
    }

    if (_doubleSided) {
        shader += ".DoubleSided";
        setShaderDefines(renderStage, "USE_DOUBLE_SIDED");
    }

    // Add the GPU skinning module to the vertex shader?
    if (_hardwareSkinning) {
        setShaderDefines(renderStage, "USE_GPU_SKINNING");
        shader += ",Skinned";  //<Use "," instead of "." will add a Vertex only property
    }

    switch (_shadingMode) {
        default:
        case ShadingMode::FLAT: {
            setShaderDefines(renderStage, "USE_SHADING_FLAT");
            shader += ".Flat";
        } break;
        case ShadingMode::PHONG: {
            setShaderDefines(renderStage, "USE_SHADING_PHONG");
            shader += ".Phong";
        } break;
        case ShadingMode::BLINN_PHONG: {
            setShaderDefines(renderStage, "USE_SHADING_BLINN_PHONG");
            shader += ".BlinnPhong";
        } break;
        case ShadingMode::TOON: {
            setShaderDefines(renderStage, "USE_SHADING_TOON");
            shader += ".Toon";
        } break;
        case ShadingMode::OREN_NAYAR: {
            setShaderDefines(renderStage, "USE_SHADING_OREN_NAYAR");
            shader += ".OrenNayar";
        } break;
        case ShadingMode::COOK_TORRANCE: {
            setShaderDefines(renderStage, "USE_SHADING_COOK_TORRANCE");
            shader += ".CookTorrance";
        } break;
    }
    // Add any modifiers you wish
    if (!_shaderModifier[to_uint(renderStage)].empty()) {
        shader += ".";
        shader += _shaderModifier[to_uint(renderStage)];
    }

    setShaderProgramInternal(shader, renderStage, computeOnAdd);

    return false;
}

void Material::computeShaderInternal() {
    if (_shaderComputeQueue.empty() || _shadersComputedThisFrame) {
        return;
    }
    
    if (g_MaxShadersComputedPerFrame == ++_totalShaderComputeCountThisFrame) {
        _shadersComputedThisFrame = true;
    }

    const ShaderQueueElement& currentItem = _shaderComputeQueue.front();
    _dirty = true;

    ShaderInfo& info = _shaderInfo[std::get<0>(currentItem)];
    info._shaderRef = CreateResource<ShaderProgram>(std::get<1>(currentItem));
    bool shaderAvailable = info._shaderRef->getState() == ResourceState::RES_LOADED;
    info._shaderCompStage = shaderAvailable
                                ? ShaderInfo::ShaderCompilationStage::COMPUTED
                                : ShaderInfo::ShaderCompilationStage::PENDING;

    _shaderComputeQueue.pop_front();
}

/// Add a texture <-> bind slot pair to be bound with the default textures
/// on each "bindTexture" call
void Material::addCustomTexture(const Texture_ptr& texture, U8 offset) {
    // custom textures are not material dependencies!
    _customTextures.push_back(std::make_pair(texture, offset));
}

/// Remove the custom texture assigned to the specified offset
bool Material::removeCustomTexture(U8 index) {
    vectorImpl<std::pair<Texture_ptr, U8>>::iterator it =
        std::find_if(std::begin(_customTextures), std::end(_customTextures),
            [&index](const std::pair<Texture_ptr, U8>& tex)
            -> bool { return tex.second == index; });
    if (it == std::end(_customTextures)) {
        return false;
    }

    _customTextures.erase(it);

    return true;
}

void Material::getTextureData(ShaderProgram::TextureUsage slot,
                              TextureDataContainer& container) {
    U32 slotValue = to_uint(slot);
    Texture_ptr& crtTexture = _textures[slotValue];
    if (crtTexture && crtTexture->flushTextureState()) {
        TextureData& data = crtTexture->getData();
        data.setHandleLow(slotValue);
        vectorAlg::emplace_back(container, data);
    }
}

void Material::getTextureData(TextureDataContainer& textureData) {
    const U32 textureCount = to_const_uint(ShaderProgram::TextureUsage::COUNT);

    if (!GFX_DEVICE.isDepthStage()) {
        textureData.reserve(textureCount + _customTextures.size());
        getTextureData(ShaderProgram::TextureUsage::UNIT0, textureData);
        getTextureData(ShaderProgram::TextureUsage::UNIT1, textureData);
        getTextureData(ShaderProgram::TextureUsage::OPACITY, textureData);
        getTextureData(ShaderProgram::TextureUsage::NORMALMAP, textureData);
        getTextureData(ShaderProgram::TextureUsage::SPECULAR, textureData);
        getTextureData(ShaderProgram::TextureUsage::REFLECTION, textureData);
        getTextureData(ShaderProgram::TextureUsage::REFRACTION, textureData);

        for (std::pair<Texture_ptr, U8>& tex : _customTextures) {
            if (tex.first->flushTextureState()) {
                textureData.push_back(tex.first->getData());
                textureData.back().setHandleLow(to_uint(tex.second));
            }
        }
    } else {
        textureData.reserve(2);
        getTextureData(ShaderProgram::TextureUsage::NORMALMAP, textureData);
        for (Material::TranslucencySource source : _translucencySource) {
            if (source == TranslucencySource::OPACITY_MAP) {
                getTextureData(ShaderProgram::TextureUsage::OPACITY, textureData);
            }
            if (source == TranslucencySource::DIFFUSE_MAP) {
                getTextureData(ShaderProgram::TextureUsage::UNIT0, textureData);
            }
        }
    }
}

const ShaderProgram_ptr& Material::ShaderInfo::getProgram() const {
    return _shaderRef == nullptr
               ? ShaderProgram::defaultShader()
               : _shaderRef;
}

Material::ShaderInfo& Material::getShaderInfo(RenderStage renderStage) {
    return _shaderInfo[to_uint(renderStage)];
}

void Material::setBumpMethod(const BumpMethod& newBumpMethod) {
    _bumpMethod = newBumpMethod;
    recomputeShaders();
}

void Material::setShadingMode(const ShadingMode& mode) { 
    _shadingMode = mode;
    recomputeShaders();
}

bool Material::unload() {

    _textures.fill(nullptr);
    _customTextures.clear();
    _shaderInfo.fill(ShaderInfo());

    return true;
}

void Material::setDoubleSided(const bool state, const bool useAlphaTest) {
    if (_doubleSided == state && _useAlphaTest == useAlphaTest) {
        return;
    }
    _doubleSided = state;
    _useAlphaTest = useAlphaTest;
    // Update all render states for this item
    if (_doubleSided) {
        for (U32 index = 0; index < to_const_uint(RenderStage::COUNT); ++index) {
            for (U8 variant = 0; variant < _defaultRenderStates[index].size(); ++variant) {
                size_t hash = _defaultRenderStates[index][variant];
                RenderStateBlock descriptor(GFX_DEVICE.getRenderStateBlock(hash));
                descriptor.setCullMode(CullMode::NONE);
                if (!_translucencySource.empty()) {
                    descriptor.setBlend(true);
                }
                setRenderStateBlock(descriptor.getHash(), static_cast<RenderStage>(index), variant);
            }
        }
    }

    _dirty = true;
    recomputeShaders();
}

bool Material::isTranslucent() {
    if (_translucencyCheck) {
        _translucencySource.clear();
        bool useAlphaTest = false;
        // In order of importance (less to more)!
        // diffuse channel alpha
        if (_shaderData._diffuse.a < 0.95f) {
            _translucencySource.push_back(TranslucencySource::DIFFUSE);
            useAlphaTest = (_shaderData._diffuse.a < 0.15f);
        }

        // base texture is translucent
        if (_textures[to_const_uint(ShaderProgram::TextureUsage::UNIT0)] &&
            _textures[to_const_uint(ShaderProgram::TextureUsage::UNIT0)]
                ->hasTransparency()) {
            _translucencySource.push_back(TranslucencySource::DIFFUSE_MAP);
            useAlphaTest = true;
        }

        // opacity map
        if (_textures[to_const_uint(ShaderProgram::TextureUsage::OPACITY)]) {
            _translucencySource.push_back(TranslucencySource::OPACITY_MAP);
            useAlphaTest = false;
        }

        _translucencyCheck = false;

        // Disable culling for translucent items
        if (!_translucencySource.empty()) {
            setDoubleSided(true, useAlphaTest);
        } else {
            recomputeShaders();
        }
    }

    return !_translucencySource.empty();
}

void Material::getSortKeys(I32& shaderKey, I32& textureKey) const {
    static const I16 invalidShaderKey = -std::numeric_limits<I16>::max();

    const ShaderInfo& info = _shaderInfo[to_const_uint(RenderStage::DISPLAY)];

    shaderKey = info._shaderRef ? info._shaderRef->getID()
                                : invalidShaderKey;

    std::weak_ptr<Texture> albedoTex = getTexture(ShaderProgram::TextureUsage::UNIT0);
    textureKey = albedoTex.expired() ? invalidShaderKey : albedoTex.lock()->getHandle();
}

void Material::getMaterialMatrix(mat4<F32>& retMatrix) const {
    retMatrix.setRow(0, _shaderData._diffuse);
    retMatrix.setRow(1, _shaderData._specular);
    retMatrix.setRow(2, vec4<F32>(_shaderData._emissive.rgb(), _shaderData._shininess));
    retMatrix.setRow(3, vec4<F32>(isTranslucent() ? 1.0f : 0.0f,  to_float(getTextureOperation()), to_float(getTextureCount()), getParallaxFactor()));
}

void Material::rebuild() {
    for (U32 i = 0; i < to_const_uint(RenderStage::COUNT); ++i) {
        ShaderInfo& info = _shaderInfo[i];
        computeShader(static_cast<RenderStage>(i), _highPriority);
        info._shaderRef->recompile();
    }
}

};

Commits for Divide-Framework/trunk/Source Code/Geometry/Material/Material.cpp

Diff revisions: vs.
Revision Author Commited Message
750 Diff Diff IonutCava picture IonutCava Thu 07 Jul, 2016 16:02:03 +0000

[IonutCava]
- Static analysis based fixes and improvements

749 Diff Diff IonutCava picture IonutCava Mon 04 Jul, 2016 16:01:34 +0000

[IonutCava]
- Added initial environment mapping code:
— Allow adding, per scene, of multiple environment probes that generate cube map reflections
— Support 2 types of probes: infinite (such as sky only probes) and local. Local probes use an AABB that will later be used for parallax correction
— Probes are held in a scene specific pool, can be updated at different rates and their results can be passed on to materials (if materials don’t need specific reflection systems such as for water or mirrors)
- ToDo:
— Blend between probes (currently, only the closes one is selected)
— Reduce VRAM usage
— Set as fallback for screen space reflections

747 Diff Diff IonutCava picture IonutCava Thu 30 Jun, 2016 15:32:46 +0000

[IonutCava]
- Rework shader recompilation system
— Added a recompile all system for shaders
— Added a recompile selected for materials
— Still buggy

734 Diff Diff IonutCava picture IonutCava Tue 21 Jun, 2016 16:28:11 +0000

[IonutCava]
- Added a render target pool:
— All render targets are now allocated (and tracked) by the GFXDevice.
— Allocation routines return a slim RenderTargetHandle object that will be used later on in draw commands.

- Added a refraction render pass that will handle translucent objects that need refracted textures instead of clear transparency
— Both reflective nodes and refractive nodes are not gathered properly at this point

- All API specific objects (buffers, textures, etc) are now initialized in the GFXDevice class (see GFXDeviceObjects.cpp)
— This allowed for the slimming of the RenderAPIWrapper interface

- Improved ENABLE_GPU_VALIDATION macro utilization:
— It enabled shadow map split plane debugging
— It bypasses loading shaders from text cache

722 Diff Diff IonutCava picture IonutCava Thu 09 Jun, 2016 16:15:33 +0000

[IonutCava]
- Restructure RenderTarget system:
— Separate attachments, use an attachment pool, use draw descriptors, require explicit information for RT calls, etc

721 Diff Diff IonutCava picture IonutCava Wed 08 Jun, 2016 15:47:49 +0000

[IonutCava]
- Spelling: change all references from our code of “color” to the PROPER British version of “colour” because it sounds 100x better

718 Diff Diff IonutCava picture IonutCava Thu 02 Jun, 2016 16:02:48 +0000

[IonutCava]
- Code cleanup:
— Rename Framebuffer to RenderTarget. Only OpenGL uses the Framebuffer nomenclature.
— Remove base Shader class as only OpenGL will have separate shaders (and eventually move to pipeline objects) as Direct3D uses FX files and may end up with different structure
— Remove drawBox3D, drawSphere3D and drawLines from GFXDevice class and add them as member functions to the IMPrimitive class (renamed to fromXYZ)
— Pull some elements from SceneManager and move them to standalone classes (W.I.P.)

712 Diff Diff IonutCava picture IonutCava Tue 24 May, 2016 16:18:37 +0000

[IonutCava]
- Added the concept of “buffer” to be used by GenericVertexData and ShaderBuffer without caring if it’s persistent or not.
— Persistent buffers handle their own locking instead of relying on the parent class
- HiZ occlusion culling fixes and optimizations

710 Diff Diff IonutCava picture IonutCava Fri 20 May, 2016 16:24:40 +0000

[IonutCava]
- Code cleanup
- Initial work on Scene loading and unloading with and without unloading assets:
— Need to change AIManager from a Singleton to a per-scene component

709 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)