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
#include "config.h"

#include "Headers/Material.h"
#include "Headers/ShaderComputeQueue.h"

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

#include "Core/Headers/Console.h"

namespace Divide {

namespace {
    const char* g_DepthPassMaterialShaderName = "depthPass";
    const char* g_ForwardMaterialShaderName = "material";
    const char* g_DeferredMaterialShaderName = "DeferredShadingPass1";
    const char* g_PassThroughMaterialShaderName = "passThrough";
};

Material::Material(GFXDevice& context, ResourceCache& parentCache, const stringImpl& name)
    : Resource(ResourceType::DEFAULT, name),
      _context(context),
      _parentCache(parentCache),
      _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),
      _translucencySource(TranslucencySource::COUNT)
{
    _textures.fill(nullptr);
    _textureExtenalFlag.fill(false);
    _textureExtenalFlag[to_const_uint(ShaderProgram::TextureUsage::REFLECTION)] = true;
    _textureExtenalFlag[to_const_uint(ShaderProgram::TextureUsage::REFRACTION)] = true;
    _textureExtenalFlag[to_const_uint(ShaderProgram::TextureUsage::DEPTH)] = true;
    _textureExtenalFlag[to_const_uint(ShaderProgram::TextureUsage::DEPTH_PREV)] = true;
    defaultReflectionTexture(nullptr, 0);
    defaultRefractionTexture(nullptr, 0);

    _operation = TextureOperation::NONE;

    /// 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()
{
}


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>(_parentCache, 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 = base._translucencySource;

    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 (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->_colourData = base._colourData;

    return cloneMat;
}

void Material::update(const U64 deltaTime) {
    for (ShaderProgramInfo& info : _shaderInfo) {
        if (info.computeStage() == ShaderProgramInfo::BuildStage::COMPUTED) {
            if (info._shaderRef->getState() == ResourceState::RES_LOADED) {
                info.computeStage(ShaderProgramInfo::BuildStage::READY);
                _dirty = true;
            }
        }
    }

    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);
    ShaderProgramInfo& 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>(_parentCache, 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);

    ShaderComputeQueue::ShaderQueueElement queueElement(shaderDescriptor);
    queueElement._shaderData = &_shaderInfo[stageIndex];
    
    ShaderComputeQueue& shaderQueue = _context.shaderComputeQueue();
    if (computeOnAdd) {
        shaderQueue.addToQueueFront(queueElement);
        shaderQueue.stepQueue();
    } else {
        shaderQueue.addToQueueBack(queueElement);
    }
}

void Material::clean() {
    if (_dirty && _dumpToFile) {
        updateTranslucency();
        if (!Config::Build::IS_DEBUG_BUILD) {
            //XML::dumpMaterial(_context, *this);
        }
        _dirty = false;
    }
}

void Material::recomputeShaders() {
    for (ShaderProgramInfo& info : _shaderInfo) {
        if (!info._customShader) {
            info.computeStage(ShaderProgramInfo::BuildStage::REQUESTED);
        }
    }
}

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

    return true;
}

void Material::updateReflectionIndex(I32 index) {
    _reflectionIndex = index;
    if (_reflectionIndex > -1) {
        RenderTarget& reflectionTarget = _context.renderTarget(RenderTargetID(RenderTargetUsage::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 = _context.renderTarget(RenderTargetID(RenderTargetUsage::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){
    ShaderProgramInfo& info = _shaderInfo[to_uint(renderStage)];
    // If shader's invalid, try to request a recompute as it might fix it
    if (info.computeStage() == ShaderProgramInfo::BuildStage::COUNT) {
        info.computeStage(ShaderProgramInfo::BuildStage::REQUESTED);
        return false;
    }

    // If the shader is valid and a recompute wasn't requested, just return true
    if (info.computeStage() != ShaderProgramInfo::BuildStage::REQUESTED) {
        return info.computeStage() == ShaderProgramInfo::BuildStage::READY;
    }

    // At this point, only computation requests are processed
    assert(info.computeStage() == ShaderProgramInfo::BuildStage::REQUESTED);

    const U32 slot0 = to_const_uint(ShaderProgram::TextureUsage::UNIT0);
    const U32 slot1 = to_const_uint(ShaderProgram::TextureUsage::UNIT1);
    const 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[slot1]) {
        if (!_textures[slot0]) {
            std::swap(_textures[slot0], _textures[slot1]);
            _translucencyCheck = true;
        }
    }

    bool deferredPassShader = _context.getRenderer().getType() !=
                              RendererType::RENDERER_TILED_FORWARD_SHADING;
    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 ? g_DeferredMaterialShaderName
                            : (depthPassShader ? g_DepthPassMaterialShaderName : g_ForwardMaterialShaderName));

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

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

    // 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 (updateTranslucency()) {
        switch (_translucencySource) {
            case TranslucencySource::OPACITY_MAP: {
                shader += ".OpacityMap";
                setShaderDefines(renderStage, "USE_OPACITY_MAP");
            } break;
            case TranslucencySource::DIFFUSE: {
                shader += ".DiffuseAlpha";
                setShaderDefines(renderStage, "USE_OPACITY_DIFFUSE");
            } break;
            case TranslucencySource::DIFFUSE_MAP: {
                shader += ".DiffuseMapAlpha";
                setShaderDefines(renderStage, "USE_OPACITY_DIFFUSE_MAP");
            } break;
        };
    }

    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;
}

/// 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);
        container.addTexture(data);
    }
}

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

    if (!_context.isDepthStage()) {
        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& data = tex.first->getData();
                data.setHandleLow(to_uint(tex.second));
                textureData.addTexture(data);
            }
        }
    } else {
        getTextureData(ShaderProgram::TextureUsage::NORMALMAP, textureData);
        switch(_translucencySource) {
            case TranslucencySource::OPACITY_MAP : {
                getTextureData(ShaderProgram::TextureUsage::OPACITY, textureData);
            } break;
            case TranslucencySource::DIFFUSE_MAP: {
                getTextureData(ShaderProgram::TextureUsage::UNIT0, textureData);
            } break;
        };
    }
}

ShaderProgramInfo& 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(ShaderProgramInfo());

    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(RenderStateBlock::get(hash));
                descriptor.setCullMode(CullMode::NONE);
                if (_translucencySource != TranslucencySource::COUNT) {
                    descriptor.setBlend(true);
                }
                setRenderStateBlock(descriptor.getHash(), static_cast<RenderStage>(index), variant);
            }
        }
    }

    _dirty = true;
    recomputeShaders();
}

bool Material::updateTranslucency() {
    if (_translucencyCheck) {
        bool useAlphaTest = false;
        _translucencySource = TranslucencySource::COUNT;
        // In order of importance (less to more)!
        // diffuse channel alpha
        if (_colourData._diffuse.a < 0.95f) {
            _translucencySource = TranslucencySource::DIFFUSE;
            useAlphaTest = (_colourData._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 = TranslucencySource::DIFFUSE_MAP;
            useAlphaTest = true;
        }

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

        _translucencyCheck = false;

        // Disable culling for translucent items
        if (_translucencySource != TranslucencySource::COUNT) {
            setDoubleSided(true, useAlphaTest);
        } else {
            recomputeShaders();
        }
    }

    return isTranslucent();
}

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

    const ShaderProgramInfo& 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, _colourData._diffuse);
    retMatrix.setRow(1, _colourData._specular);
    retMatrix.setRow(2, vec4<F32>(_colourData._emissive.rgb(), _colourData._shininess));
    retMatrix.setRow(3, vec4<F32>(isTranslucent() ? 1.0f : 0.0f,  to_float(getTextureOperation()), getParallaxFactor(), 0.0));
}

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

};

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

Diff revisions: vs.
Revision Author Commited Message
829 Diff Diff IonutCava picture IonutCava Tue 24 Jan, 2017 17:28:39 +0000

[IonutCava]
- Separate resourceLocation for resources into resourceLocation and resourceName.
- More XML config loading refactoring

810 Diff Diff IonutCava picture IonutCava Tue 10 Jan, 2017 23:05:48 +0000

[IonutCava]
- Further improve velocity buffer computation
- Fix depth pass texture-transparency issue

806 Diff Diff IonutCava picture IonutCava Sun 08 Jan, 2017 22:00:48 +0000

[IonutCava]
- Finish implementing per-fragment velocity computation using a compute shader
— Further tuning still needed
- Add VS2017 build targets

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)
801 Diff Diff IonutCava picture IonutCava Sun 27 Nov, 2016 21:28:01 +0000

[IonutCava]
- More performance analysis guided optimizations.
- Some refactoring to allow later removal of Singletons status for: GFXDevice, SFXDevice, PXDevice, GUI and Input.
— Pass a PlatformContext around objects to access these classes.

788 Diff Diff 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

781 Diff Diff IonutCava picture IonutCava Wed 12 Oct, 2016 16:03:46 +0000

[IonutCava]
- ShaderComputeQueue <-> Material shader request bug fix (element stuck in QUEUED state)
- More Camera class cleanups
- Add a method of removing EnvironmentProbes from their Pool

777 Diff Diff IonutCava picture IonutCava Fri 07 Oct, 2016 16:14:48 +0000

[IonutCava]
- Continue to implement CommandBuffer / RenderPass / RenderSubPass system.
— Rendering artefacts are still present.

776 Diff Diff IonutCava picture IonutCava Thu 06 Oct, 2016 15:57:56 +0000

[IonutCava]
- Improve the CommandBuffer system to include the notion of a RenderPass /RenderSubPass with output render target info stored in them (not used yet)

771 IonutCava picture IonutCava Tue 27 Sep, 2016 15:39:49 +0000

[IonutCava]
- Modify GFXDevice::flushRenderQueues so that it creates command buffers instead of directly calling rendering calls:
— Command buffers contain buffer, shader, texture and geometry info
— Command buffer state is now parsed and set at the API level instead of GFXDevice level
— This will allow easier porting to low level APIs later on
- Indirect draw is now a GenericDrawCommand render option instead of an explicit buffer draw parameter