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
#include "Headers/CascadedShadowMaps.h"

#include "Core/Headers/ParamHandler.h"

#include "Scenes/Headers/SceneState.h"

#include "Rendering/Headers/Renderer.h"
#include "Rendering/Camera/Headers/Camera.h"
#include "Rendering/Lighting/Headers/Light.h"

#include "Managers/Headers/SceneManager.h"
#include "Managers/Headers/RenderPassManager.h"

#include "Graphs/Headers/SceneGraphNode.h"
#include "Geometry/Shapes/Headers/Predefined/Quad3D.h"

#include "Platform/Video/Headers/GFXDevice.h"
#include "Platform/Video/Shaders/Headers/ShaderProgram.h"
#include "Platform/Video/Buffers/ShaderBuffer/Headers/ShaderBuffer.h"

namespace Divide {

CascadedShadowMaps::CascadedShadowMaps(Light* light, Camera* shadowCamera, U8 numSplits)
    : ShadowMap(light, shadowCamera, ShadowType::LAYERED)
{
    _dirLight = dynamic_cast<DirectionalLight*>(_light);
    _splitLogFactor = 0.0f;
    _nearClipOffset = 0.0f;
    _numSplits = numSplits;
    _splitDepths.resize(_numSplits + 1);
    _frustumCornersWS.resize(8);
    _frustumCornersVS.resize(8);
    _frustumCornersLS.resize(8);
    _splitFrustumCornersVS.resize(8);
    _horizBlur = 0;
    _vertBlur = 0;

    ResourceDescriptor shadowPreviewShader("fbPreview.Layered.LinearDepth.ESM.ScenePlanes");
    shadowPreviewShader.setThreadedLoading(false);
    shadowPreviewShader.setPropertyList("USE_SCENE_ZPLANES");
    _previewDepthMapShader = CreateResource<ShaderProgram>(shadowPreviewShader);
    _previewDepthMapShader->Uniform("useScenePlanes", false);

    ResourceDescriptor blurDepthMapShader("blur.GaussBlur");
    blurDepthMapShader.setThreadedLoading(false);
    _blurDepthMapShader = CreateResource<ShaderProgram>(blurDepthMapShader);
    _blurDepthMapShader->Uniform("layerTotalCount", (I32)_numSplits);
    _blurDepthMapShader->Uniform("layerCount",  (I32)_numSplits);

    Console::printfn(Locale::get(_ID("LIGHT_CREATE_SHADOW_FB")), light->getGUID(), "EVCSM");

    SamplerDescriptor blurMapSampler;
    blurMapSampler.setFilters(TextureFilter::LINEAR);
    blurMapSampler.setWrapMode(TextureWrap::CLAMP_TO_EDGE);
    blurMapSampler.setAnisotropy(0);
    blurMapSampler.toggleMipMaps(false);
    TextureDescriptor blurMapDescriptor(TextureType::TEXTURE_2D_ARRAY,
                                        GFXImageFormat::RG32F,
                                        GFXDataFormat::FLOAT_32);
    blurMapDescriptor.setLayerCount(Config::Lighting::MAX_SPLITS_PER_LIGHT);
    blurMapDescriptor.setSampler(blurMapSampler);
    
    _blurBuffer = GFX_DEVICE.allocateRT();
    _blurBuffer._rt->addAttachment(blurMapDescriptor,
                               RTAttachment::Type::Colour, 0);
    _blurBuffer._rt->setClearColour(RTAttachment::Type::COUNT, 0, DefaultColours::WHITE());

    _shadowMatricesBuffer = GFX_DEVICE.newSB(1, false, false, BufferUpdateFrequency::OFTEN);
    _shadowMatricesBuffer->create(Config::Lighting::MAX_SPLITS_PER_LIGHT, sizeof(mat4<F32>));

    STUBBED("Migrate to this: http://www.ogldev.org/www/tutorial49/tutorial49.html");
}

CascadedShadowMaps::~CascadedShadowMaps()
{
    GFX_DEVICE.deallocateRT(_blurBuffer);
    MemoryManager::DELETE(_shadowMatricesBuffer);
}

void CascadedShadowMaps::init(ShadowMapInfo* const smi) {
    _numSplits = smi->numLayers();
    const RenderTarget& depthMap = getDepthMap();
    _blurBuffer._rt->create(depthMap.getWidth(), depthMap.getHeight());
    _horizBlur = _blurDepthMapShader->GetSubroutineIndex(ShaderType::GEOMETRY, "computeCoordsH");
    _vertBlur = _blurDepthMapShader->GetSubroutineIndex(ShaderType::GEOMETRY, "computeCoordsV");

    vectorImpl<vec2<F32>> blurSizes(_numSplits);
    blurSizes[0].set(1.0f / (depthMap.getWidth() * 1.0f), 1.0f / (depthMap.getHeight() * 1.0f));
    for (int i = 1; i < _numSplits; ++i) {
        blurSizes[i].set(blurSizes[i - 1] / 2.0f);
    }

    _blurDepthMapShader->Uniform("blurSizes", blurSizes);

    _init = true;
}

void CascadedShadowMaps::render(SceneRenderState& renderState, U32 passIdx) {
    _splitLogFactor = _dirLight->csmSplitLogFactor();
    _nearClipOffset = _dirLight->csmNearClipOffset();
    _lightPosition.set(_light->getPosition());

    Camera& camera = renderState.getCamera();
    _sceneZPlanes.set(camera.getZPlanes());
    camera.getWorldMatrix(_viewInvMatrixCache);
    camera.getFrustum().getCornersWorldSpace(_frustumCornersWS);
    camera.getFrustum().getCornersViewSpace(_frustumCornersVS);

    calculateSplitDepths(camera);
    applyFrustumSplits();

    /*const RenderPassCuller::VisibleNodeList& nodes = 
        SceneManager::instance().cullSceneGraph(RenderStage::SHADOW);

    _previousFrustumBB.reset();
    for (SceneGraphNode_wptr node_wptr : nodes) {
        SceneGraphNode_ptr node_ptr = node_wptr.lock();
        if (node_ptr) {
            _previousFrustumBB.add(node_ptr->getBoundingBoxConst());
        }
    }
    _previousFrustumBB.transformHomogeneous(_shadowCamera->getViewMatrix());*/

    _shadowMatricesBuffer->setData(_shadowMatrices.data());
    _shadowMatricesBuffer->bind(ShaderBufferLocation::LIGHT_SHADOW);
    _shadowMatricesBuffer->incQueue();

    RenderPassManager::PassParams params;
    params.doPrePass = false;
    params.camera = _shadowCamera;
    params.stage = RenderStage::SHADOW;
    params.target = RenderTargetID(RenderTargetUsage::SHADOW, to_uint(getShadowMapType()));
    params.pass = passIdx;

    renderState.getCameraMgr().pushActiveCamera(_shadowCamera);
    RenderPassManager::instance().doCustomPass(params);
    renderState.getCameraMgr().popActiveCamera();

    postRender();
}

void CascadedShadowMaps::calculateSplitDepths(const Camera& cam) {
    const mat4<F32>& projMatrixCache = cam.getProjectionMatrix();

    F32 fd = _sceneZPlanes.y;//std::min(_sceneZPlanes.y, _previousFrustumBB.getExtent().z);
    F32 nd = _sceneZPlanes.x;//std::max(_sceneZPlanes.x, std::fabs(_previousFrustumBB.nearestDistanceFromPoint(cam.getEye())));

    F32 i_f = 1.0f, cascadeCount = (F32)_numSplits;
    _splitDepths[0] = nd;
    for (U32 i = 1; i < to_uint(_numSplits); ++i, i_f += 1.0f)
    {
        _splitDepths[i] = Lerp(nd + (i_f / cascadeCount)*(fd - nd),  nd * std::powf(fd / nd, i_f / cascadeCount), _splitLogFactor);
    }
    _splitDepths[_numSplits] = fd;

    for (U8 i = 0; i < _numSplits; ++i) {
        F32 crtSplitDepth = 0.5f * (-_splitDepths[i + 1] * projMatrixCache.mat[10] + projMatrixCache.mat[14]) / _splitDepths[i + 1] + 0.5f;
       _light->setShadowFloatValue(i, crtSplitDepth);
    }
}

void CascadedShadowMaps::applyFrustumSplits() {
    for (U8 pass = 0 ; pass < _numSplits; ++pass) {
        F32 minZ = _splitDepths[pass];
        F32 maxZ = _splitDepths[pass + 1];

        for (U8 i = 0; i < 4; ++i) {
            _splitFrustumCornersVS[i] =
                _frustumCornersVS[i + 4] * (minZ / _sceneZPlanes.y);
        }

        for (U8 i = 4; i < 8; ++i) {
            _splitFrustumCornersVS[i] =
                _frustumCornersVS[i] * (maxZ / _sceneZPlanes.y);
        }

        for (U8 i = 0; i < 8; ++i) {
            _frustumCornersWS[i].set(
                _viewInvMatrixCache.transformHomogeneous(_splitFrustumCornersVS[i]));
        }

        vec3<F32> frustumCentroid(0.0f);

        for (U8 i = 0; i < 8; ++i) {
            frustumCentroid += _frustumCornersWS[i];
        }
        // Find the centroid
        frustumCentroid /= 8;

        // Position the shadow-caster camera so that it's looking at the centroid,
        // and backed up in the direction of the sunlight
        F32 distFromCentroid = std::max((maxZ - minZ),
                     _splitFrustumCornersVS[4].distance(_splitFrustumCornersVS[5])) + _nearClipOffset;
    
        vec3<F32> currentEye = frustumCentroid - (_lightPosition * distFromCentroid);

        const mat4<F32>& viewMatrix = _shadowCamera->lookAt(currentEye, frustumCentroid);
        // Determine the position of the frustum corners in light space
        for (U8 i = 0; i < 8; ++i) {
            _frustumCornersLS[i].set(viewMatrix.transformHomogeneous(_frustumCornersWS[i]));
        }

        F32 frustumSphereRadius = BoundingSphere(_frustumCornersLS).getRadius();
        vec2<F32> clipPlanes(std::max(1.0f, minZ - _nearClipOffset), frustumSphereRadius * 2 + _nearClipOffset * 2);
        _shadowCamera->setProjection(UNIT_RECT * frustumSphereRadius,
                                     clipPlanes,
                                     true);
        mat4<F32>::Multiply(viewMatrix, _shadowCamera->getProjectionMatrix(), _shadowMatrices[pass]);

        // http://www.gamedev.net/topic/591684-xna-40---shimmering-shadow-maps/
        F32 halfShadowMapSize = getDepthMap().getWidth() * 0.5f;
        vec3<F32> testPoint = _shadowMatrices[pass].transformHomogeneous(VECTOR3_ZERO) * halfShadowMapSize;
        vec3<F32> testPointRounded(testPoint);
        testPointRounded.round();
        _shadowMatrices[pass].translate(vec3<F32>(((testPointRounded - testPoint) / halfShadowMapSize).xy(), 0.0f));

        _light->setShadowVPMatrix(pass, _shadowMatrices[pass] * MAT4_BIAS);
        _light->setShadowLightPos(pass, currentEye);
    }
}

void CascadedShadowMaps::postRender() {
    if (GFX_DEVICE.shadowDetailLevel() == RenderDetailLevel::LOW) {
        return;
    }

    RenderTarget& depthMap = getDepthMap();

    _blurDepthMapShader->bind();

    GenericDrawCommand pointsCmd;
    pointsCmd.primitiveType(PrimitiveType::API_POINTS);
    pointsCmd.drawCount(1);
    pointsCmd.stateHash(GFX_DEVICE.getDefaultStateBlock(true));
    pointsCmd.shaderProgram(_blurDepthMapShader);

    // Blur horizontally
    _blurDepthMapShader->Uniform("layerOffsetRead", (I32)getArrayOffset());
    _blurDepthMapShader->Uniform("layerOffsetWrite", 0);

    _blurDepthMapShader->SetSubroutine(ShaderType::GEOMETRY, _horizBlur);
    _blurBuffer._rt->begin(RenderTarget::defaultPolicy());
    depthMap.bind(0, RTAttachment::Type::Colour, 0, false);
        GFX_DEVICE.draw(pointsCmd);
    depthMap.end();

    // Blur vertically
    _blurDepthMapShader->Uniform("layerOffsetRead", 0);
    _blurDepthMapShader->Uniform("layerOffsetWrite", (I32)getArrayOffset());

    _blurDepthMapShader->SetSubroutine(ShaderType::GEOMETRY, _vertBlur);
    depthMap.begin(RenderTarget::defaultPolicy());
    _blurBuffer._rt->bind(0, RTAttachment::Type::Colour, 0);
        GFX_DEVICE.draw(pointsCmd);
    depthMap.end();
}

void CascadedShadowMaps::previewShadowMaps(U32 rowIndex) {
    if (_previewDepthMapShader->getState() != ResourceState::RES_LOADED) {
        return;
    }

    getDepthMap().bind(to_const_ubyte(ShaderProgram::TextureUsage::UNIT0), RTAttachment::Type::Colour, 0);

    GenericDrawCommand triangleCmd;
    triangleCmd.primitiveType(PrimitiveType::TRIANGLES);
    triangleCmd.drawCount(1);
    triangleCmd.stateHash(GFX_DEVICE.getDefaultStateBlock(true));
    triangleCmd.shaderProgram(_previewDepthMapShader);

    const vec4<I32> viewport = getViewportForRow(rowIndex);
    for (U32 i = 0; i < _numSplits; ++i) {
        _previewDepthMapShader->Uniform("layer", i + _arrayOffset);
        GFX::ScopedViewport sViewport(viewport.x * i, viewport.y, viewport.z, viewport.w);
        GFX_DEVICE.draw(triangleCmd);
    }
}
};

Commits for Divide-Framework/trunk/Source Code/Rendering/Lighting/ShadowMapping/CascadedShadowMaps.cpp

Diff revisions: vs.
Revision Author Commited Message
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

778 Diff Diff IonutCava picture IonutCava Mon 10 Oct, 2016 15:18:32 +0000

[IonutCava]
- Rendering abstraction cleanup

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)

775 Diff Diff IonutCava picture IonutCava Wed 05 Oct, 2016 15:54:54 +0000

[IonutCava]
- Cleanup RenderTarget <-> RTAttachment relation
- Multisampled render target state is now deduced based on attachments used

764 Diff Diff IonutCava picture IonutCava Mon 22 Aug, 2016 15:38:11 +0000

[IonutCava]
- Add some explicit include for RenderStateBlock as it will be removed from the RenderAPIWrapper.h file

760 Diff Diff IonutCava picture IonutCava Tue 09 Aug, 2016 16:30:12 +0000

[IonutCava]
- Complete rewrite of RenderPass system:
— Allow every rendering pass (reflection, environment, etc) to use the same rendering system: occlusion culling, light culling, etc
— Define render passes by a param based token similar to modern API systems (DX12/Vulkan)
— W.I.P.: Depth rendering slightly wrong; Environment Mapping ,reflection and refraction rendering currently disabled
- Add compile time variables for DEBUG/PROFILE/RELEASE builds to validate all code for every build

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

730 Diff Diff IonutCava picture IonutCava Thu 16 Jun, 2016 15:35:07 +0000

[IonutCava]
- More shadow mapping fixes
- Small performance improvements
- Proper per scene XML data loading (e.g. fog)

729 Diff Diff IonutCava picture IonutCava Wed 15 Jun, 2016 21:24:38 +0000

[IonutCava]
- AMD compatibility fixes
- More race condition fixes

728 IonutCava picture IonutCava Wed 15 Jun, 2016 16:04:33 +0000

[IonutCava]
- Updates and fixes to shadow mapping.
- Fixed a race condition in console::output regarding redirection of events to the GUI
- Attempting to fix particle emitter:
— Rewrite GenericVertexData for easier debugging/processing
— Split attributes and buffers into separate classes
— Not finished / buggy / crashes
- Fixed an issue with scene switching regarding PhysicsSceneInterface. Caused race conditions related crashes
- Fixed an issue with scene save data loading. Moved Load system to main thread after loading finishes