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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
#include "stdafx.h"

#include "config.h"

#include "Headers/RenderingComponent.h"

#include "Core/Headers/Kernel.h"
#include "Core/Headers/StringHelper.h"
#include "Scenes/Headers/SceneState.h"
#include "Graphs/Headers/SceneGraphNode.h"
#include "Platform/Video/Headers/GFXDevice.h"
#include "Platform/Video/Headers/IMPrimitive.h"
#include "Platform/Video/Headers/RenderStateBlock.h"
#include "Geometry/Shapes/Headers/Mesh.h"
#include "Geometry/Material/Headers/Material.h"
#include "Dynamics/Entities/Headers/Impostor.h"
#include "Rendering/Camera/Headers/Camera.h"
#include "Rendering/Lighting/Headers/LightPool.h"

namespace Divide {

RenderingComponent::RenderingComponent(GFXDevice& context,
                                       Material_ptr materialInstance,
                                       SceneGraphNode& parentSGN)
    : SGNComponent(SGNComponent::ComponentType::RENDERING, parentSGN),
      _context(context),
      _lodLevel(0),
      _commandIndex(0),
      _commandOffset(0),
      _renderMask(0),
      _depthStateBlockHash(0),
      _shadowStateBlockHash(0),
      _renderPackagesDirty(true),
      _reflectorType(ReflectorType::PLANAR_REFLECTOR),
      _materialInstance(materialInstance),
      _skeletonPrimitive(nullptr)
{

    toggleRenderOption(RenderOptions::RENDER_GEOMETRY, true);
    toggleRenderOption(RenderOptions::CAST_SHADOWS, true);
    toggleRenderOption(RenderOptions::RECEIVE_SHADOWS, true);
    toggleRenderOption(RenderOptions::IS_VISIBLE, true);

    Object3D_ptr node = parentSGN.getNode<Object3D>();
    Object3D::ObjectType type = node->getObjectType();

    bool isSubMesh = type == Object3D::ObjectType::SUBMESH;
    bool nodeSkinned = parentSGN.getNode<Object3D>()->getObjectFlag(Object3D::ObjectFlag::OBJECT_FLAG_SKINNED);

    assert(!_materialInstance || (_materialInstance && !_materialInstance->getName().empty()));

    for (U8 pass = 0; pass < to_base(RenderPassType::COUNT); ++pass) {
        if (_materialInstance) {
            if (!isSubMesh) {
                _materialInstance->addShaderModifier(RenderStagePass(RenderStage::SHADOW, static_cast<RenderPassType>(pass)), "TriangleStrip");
                _materialInstance->setShaderDefines(RenderStagePass(RenderStage::SHADOW, static_cast<RenderPassType>(pass)), "USE_TRIANGLE_STRIP");
            }
        }
    }

    RenderStateBlock depthDesc;
    depthDesc.setColourWrites(false, false, false, false);
    depthDesc.setZFunc(ComparisonFunction::LESS);
    _depthStateBlockHash = depthDesc.getHash();

    RenderStateBlock shadowDesc;
    /// Cull back faces for shadow rendering
    shadowDesc.setCullMode(CullMode::CCW);
    // depthDesc.setZBias(1.0f, 2.0f);
    shadowDesc.setColourWrites(true, true, false, false);
    _shadowStateBlockHash = shadowDesc.getHash();

    // Prepare it for rendering lines
    RenderStateBlock primitiveStateBlock;

    PipelineDescriptor pipelineDescriptor;
    pipelineDescriptor._stateHash = primitiveStateBlock.getHash();
    Pipeline pipeline = _context.newPipeline(pipelineDescriptor);

    _boundingBoxPrimitive[0] = _context.newIMP();
    _boundingBoxPrimitive[0]->name("BoundingBox_" + parentSGN.getName());
    _boundingBoxPrimitive[0]->pipeline(pipeline);
    _boundingBoxPrimitive[0]->paused(true);

    _boundingBoxPrimitive[1] = _context.newIMP();
    _boundingBoxPrimitive[1]->name("BoundingBox_Parent_" + parentSGN.getName());
    _boundingBoxPrimitive[1]->pipeline(pipeline);
    _boundingBoxPrimitive[1]->paused(true);

    _boundingSpherePrimitive = _context.newIMP();
    _boundingSpherePrimitive->name("BoundingSphere_" + parentSGN.getName());
    _boundingSpherePrimitive->pipeline(pipeline);
    _boundingSpherePrimitive->paused(true);

    if (nodeSkinned) {
        primitiveStateBlock.setZRead(false);
        _skeletonPrimitive = _context.newIMP();
        _skeletonPrimitive->name("Skeleton_" + parentSGN.getName());
        _skeletonPrimitive->pipeline(pipeline);
        _skeletonPrimitive->paused(true);
    }
    
    if (Config::Build::IS_DEBUG_BUILD) {
        ResourceDescriptor previewReflectionRefractionColour("fbPreview");
        previewReflectionRefractionColour.setThreadedLoading(true);
        _previewRenderTargetColour = CreateResource<ShaderProgram>(context.parent().resourceCache(), previewReflectionRefractionColour);

        ResourceDescriptor previewReflectionRefractionDepth("fbPreview.LinearDepth.ScenePlanes");
        previewReflectionRefractionDepth.setPropertyList("USE_SCENE_ZPLANES");
        _previewRenderTargetDepth = CreateResource<ShaderProgram>(context.parent().resourceCache(), previewReflectionRefractionDepth);

        // Red X-axis
        _axisLines.push_back(Line(VECTOR3_ZERO, WORLD_X_AXIS * 2, vec4<U8>(255, 0, 0, 255), 5.0f));
        // Green Y-axis
        _axisLines.push_back(Line(VECTOR3_ZERO, WORLD_Y_AXIS * 2, vec4<U8>(0, 255, 0, 255), 5.0f));
        // Blue Z-axis
        _axisLines.push_back(Line(VECTOR3_ZERO, WORLD_Z_AXIS * 2, vec4<U8>(0, 0, 255, 255), 5.0f));
        _axisGizmo = _context.newIMP();
        // Prepare it for line rendering
        size_t noDepthStateBlock = _context.getDefaultStateBlock(true);
        RenderStateBlock stateBlock(RenderStateBlock::get(noDepthStateBlock));

        pipelineDescriptor._stateHash = stateBlock.getHash();
        _axisGizmo->name("AxisGizmo_" + parentSGN.getName());
        _axisGizmo->pipeline(_context.newPipeline(pipelineDescriptor));
        // Create the object containing all of the lines
        _axisGizmo->beginBatch(true, to_U32(_axisLines.size()) * 2, 1);
        _axisGizmo->attribute4f(to_base(AttribLocation::VERTEX_COLOR), Util::ToFloatColour(_axisLines[0]._colourStart));
        // Set the mode to line rendering
        _axisGizmo->begin(PrimitiveType::LINES);
        // Add every line in the list to the batch
        for (const Line& line : _axisLines) {
            _axisGizmo->attribute4f(to_base(AttribLocation::VERTEX_COLOR), Util::ToFloatColour(line._colourStart));
            _axisGizmo->vertex(line._startPoint);
            _axisGizmo->vertex(line._endPoint);
        }
        _axisGizmo->end();
        // Finish our object
        _axisGizmo->endBatch();

        _axisGizmo->paused(true);
    } else {
        _axisGizmo = nullptr;
    }
}

RenderingComponent::~RenderingComponent()
{
    _boundingBoxPrimitive[0]->clear();
    _boundingBoxPrimitive[1]->clear();
    _boundingSpherePrimitive->clear();

    if (_skeletonPrimitive != nullptr) {
        _skeletonPrimitive->clear();
    }

    if (Config::Build::IS_DEBUG_BUILD) {
        _axisGizmo->clear();
    }
}

std::unique_ptr<RenderPackage>& RenderingComponent::renderData(const RenderStagePass& stagePass) {
    std::unique_ptr<RenderPackage>& pkg = _renderData[to_U32(stagePass.pass())][to_U32(stagePass.stage())];
    if (!pkg) {
        pkg = std::make_unique<RenderPackage>(_context, true);

        Object3D_ptr node = _parentSGN.getNode<Object3D>();
        pkg->isOcclusionCullable(node->getType() != SceneNodeType::TYPE_SKY);
    }
    return pkg;
}

const std::unique_ptr<RenderPackage>& RenderingComponent::renderData(const RenderStagePass& stagePass) const {
    const std::unique_ptr<RenderPackage>& pkg = _renderData[to_U32(stagePass.pass())][to_U32(stagePass.stage())];
    DIVIDE_ASSERT(pkg != nullptr, "RenderingComponent::renderData error: Attempt to reference a render package that wasn't created yet!");

    return pkg;
}

void RenderingComponent::rebuildDrawCommands(const RenderStagePass& stagePass) {
    std::unique_ptr<RenderPackage>& pkg = renderData(stagePass);
    pkg->clear();

    // We also have a pipeline
    PipelineDescriptor pipelineDescriptor;
    pipelineDescriptor._stateHash = getMaterialStateHash(stagePass);
    pipelineDescriptor._shaderProgram = getDrawShader(stagePass);

    GFX::BindPipelineCommand pipelineCommand;
    pipelineCommand._pipeline = _context.newPipeline(pipelineDescriptor);
    pkg->addPipelineCommand(pipelineCommand);
    
    GFX::SendPushConstantsCommand pushConstantsCommand;
    pushConstantsCommand._constants = _globalPushConstants;
    pkg->addPushConstantsCommand(pushConstantsCommand);

    GFX::BindDescriptorSetsCommand bindDescriptorSetsCommand;
    pkg->addDescriptorSetsCommand(bindDescriptorSetsCommand);

    _parentSGN.getNode()->buildDrawCommands(_parentSGN, stagePass, *pkg);
}

void RenderingComponent::postLoad() {
}

void RenderingComponent::update(const U64 deltaTime) {
    const Material_ptr& mat = getMaterialInstance();
    if (mat) {
        mat->update(deltaTime);
    }

    Object3D::ObjectType type = _parentSGN.getNode<Object3D>()->getObjectType();
    if (type == Object3D::ObjectType::SUBMESH)
    {
        StateTracker<bool>& parentStates = _parentSGN.getParent().lock()->getTrackedBools();
        parentStates.setTrackedValue(StateTracker<bool>::State::BOUNDING_BOX_RENDERED, false);

        if (_parentSGN.getNode<Object3D>()->getObjectFlag(Object3D::ObjectFlag::OBJECT_FLAG_SKINNED)) {
            parentStates.setTrackedValue(StateTracker<bool>::State::SKELETON_RENDERED, false);
        }
    }
}

bool RenderingComponent::canDraw(const RenderStagePass& renderStagePass) {
    if (_parentSGN.getNode()->getDrawState(renderStagePass)) {
        const Material_ptr& mat = getMaterialInstance();
        if (mat) {
            if (!mat->canDraw(renderStagePass)) {
                return false;
            }
        }
        return renderOptionEnabled(RenderOptions::IS_VISIBLE);
    }

    return false;
}

void RenderingComponent::rebuildMaterial() {
    const Material_ptr& mat = getMaterialInstance();
    if (mat) {
        mat->rebuild();
    }

    _parentSGN.forEachChild([](const SceneGraphNode& child) {
        RenderingComponent* const renderable = child.get<RenderingComponent>();
        if (renderable) {
            renderable->rebuildMaterial();
        }
    });
}

void RenderingComponent::registerTextureDependency(const TextureData& additionalTexture, U8 binding) {
    _textureDependencies.addTexture(additionalTexture, binding);
}

void RenderingComponent::removeTextureDependency(U8 binding) {
    _textureDependencies.removeTexture(binding);
}

void RenderingComponent::removeTextureDependency(const TextureData& additionalTexture) {
    _textureDependencies.removeTexture(additionalTexture);
}

bool RenderingComponent::onRender(const SceneRenderState& sceneRenderState,
                                  const RenderStagePass& renderStagePass) {

    ACKNOWLEDGE_UNUSED(sceneRenderState);

    // Call any pre-draw operations on the SceneNode (refresh VB, update
    // materials, get list of textures, etc)
    std::unique_ptr<RenderPackage>& pkg = renderData(renderStagePass);
    DescriptorSet set = pkg->descriptorSet(0);
    
    set._textureData.clear(false);
    const Material_ptr& mat = getMaterialInstance();
    if (mat) {
        mat->getTextureData(set._textureData);
    }

    for (auto texture : _textureDependencies.textures()) {
        set._textureData.addTexture(texture);
    }

    set._shaderBuffers = _shaderBuffers;
    pkg->descriptorSet(0, set);

    return true;
}

void RenderingComponent::getMaterialColourMatrix(mat4<F32>& matOut) const {
    matOut.zero();

    const Material_ptr& mat = getMaterialInstance();
    if (mat) {
        mat->getMaterialMatrix(matOut);
    }
}

void RenderingComponent::getRenderingProperties(vec4<F32>& propertiesOut, F32& reflectionIndex, F32& refractionIndex) const {
    propertiesOut.set(_parentSGN.getSelectionFlag() == SceneGraphNode::SelectionFlag::SELECTION_SELECTED
                                                     ? -1.0f
                                                     : _parentSGN.getSelectionFlag() == SceneGraphNode::SelectionFlag::SELECTION_HOVER
                                                                                      ? 1.0f
                                                                                      : 0.0f,
                      renderOptionEnabled(RenderOptions::RECEIVE_SHADOWS) ? 1.0f : 0.0f,
                      _lodLevel,
                      0.0);
    const Material_ptr& mat = getMaterialInstance();
    if (mat) {
        reflectionIndex = to_F32(mat->defaultReflectionTextureIndex());
        refractionIndex = to_F32(mat->defaultRefractionTextureIndex());
    } else {
        reflectionIndex = refractionIndex = 0.0f;
    }
}

/// Called after the current node was rendered
void RenderingComponent::postRender(const SceneRenderState& sceneRenderState, const RenderStagePass& renderStagePass, GFX::CommandBuffer& bufferInOut) {
    
    if (renderStagePass.stage() != RenderStage::DISPLAY || renderStagePass.pass() == RenderPassType::DEPTH_PASS) {
        return;
    }

    const SceneNode_ptr& node = _parentSGN.getNode();

    if (Config::Build::IS_DEBUG_BUILD) {
        switch(sceneRenderState.gizmoState()){
            case SceneRenderState::GizmoState::ALL_GIZMO: {
                if (node->getType() == SceneNodeType::TYPE_OBJECT3D) {
                    if (_parentSGN.getNode<Object3D>()->getObjectType() == Object3D::ObjectType::SUBMESH) {
                        drawDebugAxis();
                    }
                }
            } break;
            case SceneRenderState::GizmoState::SELECTED_GIZMO: {
                switch (_parentSGN.getSelectionFlag()) {
                    case SceneGraphNode::SelectionFlag::SELECTION_SELECTED : {
                        drawDebugAxis();
                    } break;
                    default: {
                        _axisGizmo->paused(true);
                    } break;
                }
            } break;
            default: {
                _axisGizmo->paused(true);
            } break;
        }
    }

    SceneGraphNode_ptr grandParent = _parentSGN.getParent().lock();
    StateTracker<bool>& parentStates = grandParent->getTrackedBools();

    // Draw bounding box if needed and only in the final stage to prevent Shadow/PostFX artifacts
    bool renderBBox = renderOptionEnabled(RenderOptions::RENDER_BOUNDS_AABB);
    renderBBox = renderBBox || sceneRenderState.isEnabledOption(SceneRenderState::RenderOptions::RENDER_AABB);

    bool renderBSphere = renderOptionEnabled(RenderOptions::RENDER_BOUNDS_SPHERE);

    if (renderBBox) {
        const BoundingBox& bb = _parentSGN.get<BoundsComponent>()->getBoundingBox();
        _boundingBoxPrimitive[0]->fromBox(bb.getMin(), bb.getMax(), vec4<U8>(0, 0, 255, 255));

        renderBSphere = renderBSphere || _parentSGN.getSelectionFlag() == SceneGraphNode::SelectionFlag::SELECTION_SELECTED;
        toggleRenderOption(RenderOptions::RENDER_BOUNDS_SPHERE, renderBSphere);

        Object3D::ObjectType type = _parentSGN.getNode<Object3D>()->getObjectType();
        bool isSubMesh = type == Object3D::ObjectType::SUBMESH;
        if (isSubMesh) {
            bool renderParentBBFlagInitialized = false;
            bool renderParentBB = parentStates.getTrackedValue(StateTracker<bool>::State::BOUNDING_BOX_RENDERED,
                                   renderParentBBFlagInitialized);
            if (!renderParentBB || !renderParentBBFlagInitialized) {
                const BoundingBox& bbGrandParent = grandParent->get<BoundsComponent>()->getBoundingBox();
                _boundingBoxPrimitive[1]->fromBox(
                                     bbGrandParent.getMin() - vec3<F32>(0.0025f),
                                     bbGrandParent.getMax() + vec3<F32>(0.0025f),
                                     vec4<U8>(0, 128, 128, 255));
            }
        }
    }

    if (renderBSphere) {
        const BoundingSphere& bs = _parentSGN.get<BoundsComponent>()->getBoundingSphere();
        _boundingSpherePrimitive->fromSphere(bs.getCenter(), bs.getRadius(), vec4<U8>(0, 255, 0, 255));
    }

    bool renderSkeleton = renderOptionEnabled(RenderOptions::RENDER_SKELETON);
    renderSkeleton = renderSkeleton || sceneRenderState.isEnabledOption(SceneRenderState::RenderOptions::RENDER_SKELETONS);

    if (renderSkeleton) {
        // Continue only for skinned submeshes
        Object3D::ObjectType type = _parentSGN.getNode<Object3D>()->getObjectType();
        bool isSubMesh = type == Object3D::ObjectType::SUBMESH;
        if (isSubMesh && _parentSGN.getNode<Object3D>()->getObjectFlag(Object3D::ObjectFlag::OBJECT_FLAG_SKINNED))
        {
            bool renderSkeletonFlagInitialized = false;
            bool renderParentSkeleton = parentStates.getTrackedValue(StateTracker<bool>::State::SKELETON_RENDERED, renderSkeletonFlagInitialized);
            if (!renderParentSkeleton || !renderSkeletonFlagInitialized) {
                // Get the animation component of any submesh. They should be synced anyway.
                AnimationComponent* childAnimComp = _parentSGN.get<AnimationComponent>();
                // Get the skeleton lines from the submesh's animation component
                const vectorImpl<Line>& skeletonLines = childAnimComp->skeletonLines();
                _skeletonPrimitive->worldMatrix(_parentSGN.get<PhysicsComponent>()->getWorldMatrix());
                // Submit the skeleton lines to the GPU for rendering
                _skeletonPrimitive->fromLines(skeletonLines);
                parentStates.setTrackedValue(StateTracker<bool>::State::SKELETON_RENDERED, true);
            }
        }
    } else {
        if (_skeletonPrimitive) {
            _skeletonPrimitive->paused(true);
        }
    }

    bufferInOut.add(_boundingBoxPrimitive[0]->toCommandBuffer());
    bufferInOut.add(_boundingBoxPrimitive[1]->toCommandBuffer());
    bufferInOut.add(_boundingSpherePrimitive->toCommandBuffer());
    if (_skeletonPrimitive) {
        bufferInOut.add(_skeletonPrimitive->toCommandBuffer());
    }
    if (Config::Build::IS_DEBUG_BUILD) {
        bufferInOut.add(_axisGizmo->toCommandBuffer());
    }
}

void RenderingComponent::registerShaderBuffer(ShaderBufferLocation slot,
                                              vec2<U32> bindRange,
                                              ShaderBuffer& shaderBuffer) {
    ShaderBufferList::iterator it = std::find_if(std::begin(_shaderBuffers),
                                                 std::end(_shaderBuffers),
                                                 [slot](const ShaderBufferBinding& binding)
                                                 -> bool { return binding._binding == slot; });

    if (it == std::end(_shaderBuffers)) {
        vectorAlg::emplace_back(_shaderBuffers, slot, &shaderBuffer, bindRange);
    } else {
        it->set(slot, &shaderBuffer, bindRange);
    }
}

void RenderingComponent::unregisterShaderBuffer(ShaderBufferLocation slot) {
    _shaderBuffers.erase(std::remove_if(std::begin(_shaderBuffers),
                                        std::end(_shaderBuffers),
                                        [&slot](const ShaderBufferBinding& binding)
                                        -> bool { return binding._binding == slot; }),
                         std::end(_shaderBuffers));
}

ShaderProgram_ptr RenderingComponent::getDrawShader(const RenderStagePass& renderStagePass) {
    if (_materialInstance) {
        return _materialInstance->getShaderInfo(renderStagePass).getProgram();
    }

    return nullptr;
}

size_t RenderingComponent::getMaterialStateHash(const RenderStagePass& renderStagePass) {
    bool shadowStage = renderStagePass.stage() == RenderStage::SHADOW;
    bool depthPass   = renderStagePass.pass() == RenderPassType::DEPTH_PASS || shadowStage;

    if (!getMaterialInstance() && depthPass) {
        return shadowStage ? _shadowStateBlockHash : _depthStateBlockHash;
    }

    if (!_materialInstance) {
        return 0;
    }

    I32 variant = 0;
    if (shadowStage && LightPool::currentShadowCastingLight()) {
        LightType type = LightPool::currentShadowCastingLight()->getLightType();
        variant = (type == LightType::DIRECTIONAL
                         ? 0
                         : type == LightType::POINT 
                                 ? 1
                                 : 2);
    }

    return _materialInstance->getRenderStateBlock(renderStagePass, variant);
}

void RenderingComponent::updateLoDLevel(const Camera& camera, const RenderStagePass& renderStagePass) {
    static const U32 SCENE_NODE_LOD0_SQ = Config::SCENE_NODE_LOD0 * Config::SCENE_NODE_LOD0;
    static const U32 SCENE_NODE_LOD1_SQ = Config::SCENE_NODE_LOD1 * Config::SCENE_NODE_LOD1;

    _lodLevel = to_U8(_parentSGN.getNode()->getLODcount() - 1);

    // ToDo: Hack for lower LoD rendering in reflection and refraction passes
    if (renderStagePass.stage() != RenderStage::REFLECTION && renderStagePass.stage() != RenderStage::REFRACTION) {
        const vec3<F32>& eyePos = camera.getEye();
        const BoundingSphere& bSphere = _parentSGN.get<BoundsComponent>()->getBoundingSphere();
        F32 cameraDistanceSQ = bSphere.getCenter().distanceSquared(eyePos);

        U8 lodLevelTemp = cameraDistanceSQ > SCENE_NODE_LOD0_SQ
                                           ? cameraDistanceSQ > SCENE_NODE_LOD1_SQ ? 2 : 1
                                           : 0;

        _lodLevel = std::min(_lodLevel, std::max(lodLevelTemp, to_U8(0)));
    }
}

void RenderingComponent::setDrawIDs(const RenderStagePass& renderStagePass,
                                    U32 cmdOffset,
                                    U32 cmdIndex) {
    commandOffset(cmdOffset);
    commandIndex(cmdIndex);

    std::unique_ptr<RenderPackage>& pkg = renderData(renderStagePass);
    
    for (I32 cmdIdx = 0; cmdIdx < pkg->drawCommandCount(); ++cmdIdx) {
        GFX::DrawCommand& cmd = Attorney::RenderPackageRenderingComponent::drawCommand(*pkg, cmdIdx);
        for (GenericDrawCommand& drawCmd : cmd._drawCommands) {
            drawCmd.commandOffset(cmdOffset++);
            drawCmd.toggleOption(GenericDrawCommand::RenderOptions::RENDER_INDIRECT, true);
            drawCmd.cmd().baseInstance = cmdIndex;
        }
    }
}

void RenderingComponent::prepareDrawPackage(const SceneRenderState& sceneRenderState, const RenderStagePass& renderStagePass) {
    std::unique_ptr<RenderPackage>& pkg = renderData(renderStagePass);
    pkg->isRenderable(false);
    if (canDraw(renderStagePass)) {

        if (_renderPackagesDirty) {
            for (RenderStagePass::PassIndex i = 0; i < RenderStagePass::count(); ++i) {
                rebuildDrawCommands(RenderStagePass::stagePass(i));
            }
            _renderPackagesDirty = false;
        }

        if (_parentSGN.prepareRender(sceneRenderState, renderStagePass)) {
            updateLoDLevel(*Camera::activeCamera(), renderStagePass);

            bool renderGeometry = renderOptionEnabled(RenderOptions::RENDER_GEOMETRY);
            renderGeometry = renderGeometry || sceneRenderState.isEnabledOption(SceneRenderState::RenderOptions::RENDER_GEOMETRY);

            bool renderWireframe = renderOptionEnabled(RenderOptions::RENDER_WIREFRAME);
            renderWireframe = renderWireframe || sceneRenderState.isEnabledOption(SceneRenderState::RenderOptions::RENDER_WIREFRAME);

            for (I32 cmdIdx = 0; cmdIdx < pkg->drawCommandCount(); ++cmdIdx) {
                GFX::DrawCommand& cmd = Attorney::RenderPackageRenderingComponent::drawCommand(*pkg, cmdIdx);
                for (GenericDrawCommand& drawCmd : cmd._drawCommands) {
                    drawCmd.toggleOption(GenericDrawCommand::RenderOptions::RENDER_GEOMETRY,
                                         renderGeometry || drawCmd.isEnabledOption(GenericDrawCommand::RenderOptions::RENDER_GEOMETRY));

                    drawCmd.toggleOption(GenericDrawCommand::RenderOptions::RENDER_WIREFRAME,
                                         renderWireframe || drawCmd.isEnabledOption(GenericDrawCommand::RenderOptions::RENDER_WIREFRAME));

                    drawCmd.LoD(_lodLevel);
                }
            }

            if (pkg->drawCommandCount() > 0) {
                pkg->isRenderable(true);
                setDrawIDs(renderStagePass, commandOffset(), commandIndex());
            }
            if (Attorney::RenderPackageRenderingComponent::buildCommandBuffer(*pkg)) {
                //rebuild detected -Ionut
            }
            
        }
    }
}

RenderPackage& RenderingComponent::getDrawPackage(const RenderStagePass& renderStagePass) {
    RenderPackage& ret = *renderData(renderStagePass).get();
    //ToDo: Some validation? -Ionut
    return ret;
}

const RenderPackage& RenderingComponent::getDrawPackage(const RenderStagePass& renderStagePass) const {
    const RenderPackage& ret = *renderData(renderStagePass).get();
    //ToDo: Some validation? -Ionut
    return ret;
}


size_t RenderingComponent::getSortKeyHash(const RenderStagePass& renderStagePass) const {
    const std::unique_ptr<RenderPackage>& pkg = _renderData[to_U32(renderStagePass.pass())][to_U32(renderStagePass.stage())];
    if (pkg) {
        pkg->getSortKeyHash();
    }

    return 0;
}

bool RenderingComponent::clearReflection() {
    // If we lake a material, we don't use reflections
    const Material_ptr& mat = getMaterialInstance();
    if (mat == nullptr) {
        return false;
    }

    mat->updateReflectionIndex(_reflectorType, -1);
    return true;
}

bool RenderingComponent::updateReflection(U32 reflectionIndex,
                                          Camera* camera,
                                          const SceneRenderState& renderState,
                                          GFX::CommandBuffer& bufferInOut)
{
    // Low lod entities don't need up to date reflections
    if (_lodLevel > 1) {
        return false;
    }
    // If we lake a material, we don't use reflections
    const Material_ptr& mat = getMaterialInstance();
    if (mat == nullptr) {
        return false;
    }

    mat->updateReflectionIndex(_reflectorType, reflectionIndex);

    RenderTargetID reflectRTID(_reflectorType == ReflectorType::PLANAR_REFLECTOR ? RenderTargetUsage::REFLECTION_PLANAR
                                                                                 : RenderTargetUsage::REFRACTION_CUBE, 
                               reflectionIndex);

    if (Config::Build::IS_DEBUG_BUILD) {
        GFXDevice::DebugView_ptr& viewPtr = _debugViews[0][reflectionIndex];
        const RenderTarget& target = _context.renderTargetPool().renderTarget(reflectRTID);
        if (!viewPtr) {
            viewPtr = std::make_shared<GFXDevice::DebugView>();
            viewPtr->_texture = target.getAttachment(RTAttachmentType::Colour, 0).texture();
            viewPtr->_shader = _previewRenderTargetColour;
            viewPtr->_shaderData.set("lodLevel", PushConstantType::FLOAT, 0.0f);
            viewPtr->_shaderData.set("linearSpace", PushConstantType::BOOL, false);
            viewPtr->_shaderData.set("unpack2Channel", PushConstantType::BOOL, false);

            viewPtr->_name = Util::StringFormat("Reflection_", reflectRTID);
            _context.addDebugView(viewPtr);
        } else {
            if (_context.getFrameCount() % (Config::TARGET_FRAME_RATE * 15) == 0) {
                if (viewPtr->_shader->getGUID() == _previewRenderTargetColour->getGUID()) {
                    viewPtr->_texture = target.getAttachment(RTAttachmentType::Depth, 0).texture();
                    viewPtr->_shader = _previewRenderTargetDepth;
                } else {
                    viewPtr->_texture = target.getAttachment(RTAttachmentType::Colour, 0).texture();
                    viewPtr->_shader = _previewRenderTargetColour;
                }
                
            }

        }
    }

    if (_reflectionCallback) {
        RenderCbkParams params(_context, _parentSGN, renderState, reflectRTID, reflectionIndex, camera);
        _reflectionCallback(params, bufferInOut);
    } else {
        if (_reflectorType == ReflectorType::CUBE_REFLECTOR) {
            const vec2<F32>& zPlanes = camera->getZPlanes();
            _context.generateCubeMap(reflectRTID,
                                     0,
                                     camera->getEye(),
                                     vec2<F32>(zPlanes.x, zPlanes.y * 0.25f),
                                     RenderStagePass(RenderStage::REFLECTION, RenderPassType::COLOUR_PASS),
                                     reflectionIndex,
                                     bufferInOut);
        }
    }

    return true;
}

bool RenderingComponent::clearRefraction() {
    const Material_ptr& mat = getMaterialInstance();
    if (mat == nullptr) {
        return false;
    }
    if (!mat->hasTransparency()) {
        return false;
    }
    mat->updateRefractionIndex(_reflectorType, -1);
    return true;
}

bool RenderingComponent::updateRefraction(U32 refractionIndex,
                                          Camera* camera,
                                          const SceneRenderState& renderState,
                                          GFX::CommandBuffer& bufferInOut) {
    // no default refraction system!
    if (!_refractionCallback) {
        return false;
    }
    // Low lod entities don't need up to date reflections
    if (_lodLevel > 1) {
        return false;
    }
    const Material_ptr& mat = getMaterialInstance();
    if (mat == nullptr) {
        return false;
    }

    mat->updateRefractionIndex(_reflectorType, refractionIndex);

    RenderTargetID refractRTID(_reflectorType == ReflectorType::PLANAR_REFLECTOR ? RenderTargetUsage::REFRACTION_PLANAR
                                                                                 : RenderTargetUsage::REFRACTION_CUBE,
                               refractionIndex);

    if (Config::Build::IS_DEBUG_BUILD) {
        GFXDevice::DebugView_ptr& viewPtr = _debugViews[1][refractionIndex];
        const RenderTarget& target = _context.renderTargetPool().renderTarget(refractRTID);

        if (!viewPtr) {
            viewPtr = std::make_shared<GFXDevice::DebugView>();
            viewPtr->_texture = target.getAttachment(RTAttachmentType::Colour, 0).texture();
            viewPtr->_shader = _previewRenderTargetColour;
            viewPtr->_shaderData.set("lodLevel", PushConstantType::FLOAT, 0.0f);
            viewPtr->_shaderData.set("linearSpace", PushConstantType::BOOL, false);
            viewPtr->_shaderData.set("unpack2Channel", PushConstantType::BOOL, false);
            viewPtr->_name = Util::StringFormat("Refraction", refractRTID);
            _context.addDebugView(viewPtr);
        } else {
            if (_context.getFrameCount() % (Config::TARGET_FRAME_RATE * 15) == 0) {
                if (viewPtr->_shader->getGUID() == _previewRenderTargetColour->getGUID()) {
                    viewPtr->_texture = target.getAttachment(RTAttachmentType::Depth, 0).texture();
                    viewPtr->_shader = _previewRenderTargetDepth;
                } else {
                    viewPtr->_texture = target.getAttachment(RTAttachmentType::Colour, 0).texture();
                    viewPtr->_shader = _previewRenderTargetColour;
                }
            } 
        }
    }

    RenderCbkParams params(_context, _parentSGN, renderState, refractRTID, refractionIndex, camera);
    _refractionCallback(params, bufferInOut);

    return false;
}

void RenderingComponent::updateEnvProbeList(const EnvironmentProbeList& probes) {
    _envProbes.resize(0);
    if (probes.empty()) {
        return;
    }

    _envProbes.insert(std::cend(_envProbes), std::cbegin(probes), std::cend(probes));

    PhysicsComponent* const transform = _parentSGN.get<PhysicsComponent>();
    if (transform) {
        const vec3<F32>& nodePos = transform->getPosition();
        auto sortFunc = [&nodePos](const EnvironmentProbe_ptr& a, const EnvironmentProbe_ptr& b) -> bool {
            return a->distanceSqTo(nodePos) < b->distanceSqTo(nodePos);
        };

        std::sort(std::begin(_envProbes), std::end(_envProbes), sortFunc);
    }
    const Material_ptr& mat = getMaterialInstance();
    if (mat == nullptr) {
        return;
    }

    RenderTarget* rt = EnvironmentProbe::reflectionTarget()._rt;
    mat->defaultReflectionTexture(rt->getAttachment(RTAttachmentType::Colour, 0).texture(),
                                  _envProbes.front()->getRTIndex());
}

/// Draw the axis arrow gizmo
void RenderingComponent::drawDebugAxis() {
    if (!Config::Build::IS_DEBUG_BUILD) {
        return;
    }

    PhysicsComponent* const transform = _parentSGN.get<PhysicsComponent>();
    if (transform) {
        mat4<F32> tempOffset(GetMatrix(transform->getOrientation()), false);
        tempOffset.setTranslation(transform->getPosition());
        _axisGizmo->worldMatrix(tempOffset);
    } else {
        _axisGizmo->resetWorldMatrix();
    }
    _axisGizmo->paused(false);
}

};

Commits for Divide-Framework/trunk/Source Code/Graphs/Components/RenderingComponent.cpp

Diff revisions: vs.
Revision Author Commited Message
949 Diff Diff IonutCava picture IonutCava Thu 19 Oct, 2017 21:48:37 +0000

[Ionut]
- More command buffer refactoring

948 Diff Diff IonutCava picture IonutCava Tue 17 Oct, 2017 22:41:09 +0000

[Ionut]
- Move rendering data caching outside of CommandBuffer and into RenderPackage for better control.

943 Diff Diff IonutCava picture IonutCava Tue 12 Sep, 2017 11:38:52 +0000

[IonutCava]
- Rework ThreadPool/Task system for clearer parent<->child relationship between tasks
— Disable Prio pool since it doesn’t work properly with the newest boost libraries
— Modify the C++11 threadpool to remove the boost dependency
- Reduce memory usage by allocating command buffers on use instead of on creation

940 Diff Diff IonutCava picture IonutCava Fri 18 Aug, 2017 16:18:44 +0000

[Ionut]
- Generate GFX::CommandBuffers only from GFX::CommandBufferPools.
— We shouldn’t be allocating any new GFX::CommandBuffers at runtime now.
— ToDo: Add a similar system for Pipelines
- Add 2 command buffer pools to GFXDevice: a primary one used for rendering and a large, secondary one used for command generation

938 Diff Diff IonutCava picture IonutCava Wed 16 Aug, 2017 21:35:55 +0000

[Ionut]
- Separate texture binding slot from TextureData
- Binding slot is now a property of the descriptor set
- Remove bind() calls from texture’s public interface
ToDo
- Add image layer binding options (addTextureLayer(data, binding, layer, ...)

933 Diff Diff IonutCava picture IonutCava Tue 15 Aug, 2017 00:02:05 +0000

[Ionut]
- CommandBuffer Part 2/3: code compiles and splash screen renders and application doesn’t crash (still has drawing issues)

932 Diff Diff IonutCava picture IonutCava Mon 14 Aug, 2017 16:17:59 +0000

[Ionut]
- Transition every GPU call to the new GFX::CommandBuffer system.
- Part 1/3: Infrastructure. Does not compile yet; (ToDo: part 2/3: transition commands to new infrastructure. part 3/3: debug and optimize)

Currently supported commands:
BEGIN_RENDER_PASS
END_RENDER_PASS
BEGIN_RENDER_SUB_PASS
END_RENDER_SUB_PASS
SET_VIEWPORT
SET_SCISSOR
BIND_PIPELINE
BIND_DESCRIPTOR_SETS
SEND_PUSH_CONSTANTS
DRAW_COMMANDS
DRAW_TEXT
DISPATCH_COMPUTE

930 Diff Diff IonutCava picture IonutCava Sun 13 Aug, 2017 20:33:31 +0000

[Ionut]
- Fix a bug with Push Constant to Uniform conversion
- Add more push constant types
- Fix RENDER_INDIRECT param for draw commands
- Cleanup Sky, Terrain and Vegetation a bit

929 Diff Diff IonutCava picture IonutCava Sat 12 Aug, 2017 17:34:44 +0000

[Ionut]
- More work on finishing up new PushConstant / Command buffer rendering system:
— Everything compiles and runs but with graphical and performance issues

927 IonutCava picture IonutCava Thu 10 Aug, 2017 21:55:10 +0000

[Ionut]
- Cleanup Text rendering and text related structs
- Add labels to DebugViews