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

#include "Hardware/Video/Headers/GFXDevice.h"
#include "Managers/Headers/LightManager.h"
#include "Managers/Headers/ShaderManager.h"
#include "Managers/Headers/SceneManager.h"
#include "core/Headers/Kernel.h"
#include "Core/Headers/ParamHandler.h"
#include "Core/Headers/Application.h"
#include "Geometry/Material/Headers/Material.h"
#include "Rendering/Lighting/ShadowMapping/Headers/ShadowMap.h"

ShaderProgram::ShaderProgram(const bool optimise) : HardwareResource("temp_shader_program"),
                                                    _activeCamera(nullptr),
                                                    _optimise(optimise),
                                                    _linked(false),
                                                    _bound(false),
                                                    _dirty(true),
                                                    _wasBound(false),
                                                    _elapsedTime(0ULL),
                                                    _outputCount(0),
                                                    _elapsedTimeMS(0.0f)
{
    _shaderProgramId = 0;//<Override in concrete implementations with appropriate invalid values
    
    memset(_refreshStage, false, ShaderType_PLACEHOLDER * sizeof(bool));

    _maxCombinedTextureUnits = ParamHandler::getInstance().getParam<I32>("GFX_DEVICE.maxTextureCombinedUnits",16);

    _sceneDataDirty = true;
    _timeLoc             = -1;
    _enableFogLoc        = -1;
    _lightAmbientLoc     = -1;
    _invScreenDimension  = -1;
    _fogColorLoc       = -1;
    _fogDensityLoc     = -1;
    _prevLOD           = 250;
    _lodVertLight.resize(2);
    _lodFragLight.resize(2);
}

ShaderProgram::~ShaderProgram()
{
    D_PRINT_FN(Locale::get("SHADER_PROGRAM_REMOVE"), getName().c_str());
    FOR_EACH(ShaderIdMap::value_type& it, _shaderIdMap){
        ShaderManager::getInstance().removeShader(it.second);
    }
    ShaderManager::getInstance().unregisterShaderProgram(getName());
    _shaderIdMap.clear();
}

U8 ShaderProgram::update(const U64 deltaTime){
    _elapsedTime += deltaTime;
    _elapsedTimeMS = static_cast<F32>(getUsToMs(_elapsedTime));
    if (!isHWInitComplete())
        return 0;

    _activeCamera = Application::getInstance().getKernel()->getCameraMgr().getActiveCamera();
    
    ParamHandler& par = ParamHandler::getInstance();
    LightManager& lightMgr = LightManager::getInstance();
    bool enableFog = par.getParam<bool>("rendering.enableFog");
#ifdef _DEBUG
    this->Uniform("dvd_showShadowSplits", par.getParam<bool>("rendering.debug.showSplits"));
#endif
    this->Uniform(_timeLoc, _elapsedTimeMS);
    this->Uniform(_enableFogLoc, enableFog);
    this->Uniform(_lightAmbientLoc, lightMgr.getAmbientLight());
    if(_sceneDataDirty){
        if(enableFog){
            this->Uniform(_fogColorLoc, vec3<F32>(par.getParam<F32>("rendering.sceneState.fogColor.r"),
                                                  par.getParam<F32>("rendering.sceneState.fogColor.g"),
                                                  par.getParam<F32>("rendering.sceneState.fogColor.b")));
            this->Uniform(_fogDensityLoc, par.getParam<F32>("rendering.sceneState.fogDensity"));
        }
        Scene* activeScene = GET_ACTIVE_SCENE();
        this->Uniform("windDirection", vec2<F32>(activeScene->state().getWindDirX(), activeScene->state().getWindDirZ()));
        this->Uniform("windSpeed", activeScene->state().getWindSpeed());
        _sceneDataDirty = false;
    }
    if(_dirty){
        const vec2<U16>& screenRes = GFX_DEVICE.getRenderTarget(GFXDevice::RENDER_TARGET_SCREEN)->getResolution();
        this->Uniform(_invScreenDimension, vec2<F32>(1.0f / screenRes.width, 1.0f / screenRes.height));
        //Apply global shader values valid throughout application runtime:
        char depthMapSampler1[32], depthMapSampler2[32], depthMapSampler3[32];
        for (I32 i = 0; i < Config::Lighting::MAX_SHADOW_CASTING_LIGHTS_PER_NODE; ++i){
            sprintf_s(depthMapSampler1, "texDepthMapFromLight[%d]",      i);
            sprintf_s(depthMapSampler2, "texDepthMapFromLightArray[%d]", i);
            sprintf_s(depthMapSampler3, "texDepthMapFromLightCube[%d]",  i);
             //Shadow Maps always bound from the last texture slot upwards
            this->UniformTexture(depthMapSampler1, lightMgr.getShadowBindSlot(LightManager::SHADOW_SLOT_TYPE_NORMAL, i));
            this->UniformTexture(depthMapSampler2, lightMgr.getShadowBindSlot(LightManager::SHADOW_SLOT_TYPE_ARRAY,  i));
            this->UniformTexture(depthMapSampler3, lightMgr.getShadowBindSlot(LightManager::SHADOW_SLOT_TYPE_CUBE,   i));
        }

        this->UniformTexture("texDiffuse0", Material::TEXTURE_UNIT0);
        this->UniformTexture("texDiffuse1", Material::TEXTURE_UNIT1);

        this->Uniform("dvd_lightBleedBias", 0.0000002f);
        this->Uniform("dvd_minShadowVariance", 0.0002f);
        this->Uniform("dvd_shadowMaxDist", 250.0f);
        this->Uniform("dvd_shadowFadeDist",150.0f);
        _dirty = false;
    }

    return 1;
}

bool ShaderProgram::generateHWResource(const std::string& name){
    _name = name;

    if (!HardwareResource::generateHWResource(name))
        return false;

    HardwareResource::threadedLoad(name);

    DIVIDE_ASSERT(isHWInitComplete(), "ShaderProgram error: hardware initialization failed!");

    _timeLoc             = this->cachedLoc("dvd_time");
    _enableFogLoc        = this->cachedLoc("dvd_enableFog");
    _lightAmbientLoc     = this->cachedLoc("dvd_lightAmbient");
    _invScreenDimension  = this->cachedLoc("dvd_invScreenDimension");
    _fogColorLoc         = this->cachedLoc("fogColor");
    _fogDensityLoc       = this->cachedLoc("fogDensity");

    _lodVertLight[0] = GetSubroutineIndex(VERTEX_SHADER, "computeLightInfoLOD0");
    _lodVertLight[1] = GetSubroutineIndex(VERTEX_SHADER, "computeLightInfoLOD1");

    _lodFragLight[0] = GetSubroutineIndex(FRAGMENT_SHADER, "computeLightInfoLOD0Frag");
    _lodFragLight[1] = GetSubroutineIndex(FRAGMENT_SHADER, "computeLightInfoLOD1Frag");
    _dirty = true;

    return true;
}

bool ShaderProgram::bind(){
    _bound = _wasBound = true;
    return _shaderProgramId != 0;
}

void ShaderProgram::UpdateDrawCommand(U8 LoD) {
    SetSubroutine(VERTEX_SHADER,   LoD == 0 ? _lodVertLight[0] : _lodVertLight[1]);
    SetSubroutine(FRAGMENT_SHADER, LoD == 0 ? _lodFragLight[0] : _lodFragLight[1]);

    if (LoD != _prevLOD){
        Uniform("lodLevel", (I32)LoD);
        _prevLOD = LoD;
    }
}

void ShaderProgram::unbind(bool resetActiveProgram){
    _bound = false;
}

vectorImpl<Shader* > ShaderProgram::getShaders(const ShaderType& type) const{
    static vectorImpl<Shader* > returnShaders;

    returnShaders.clear();
    FOR_EACH(ShaderIdMap::value_type it, _shaderIdMap){
        if(it.second->getType() == type){
            returnShaders.push_back(it.second);
        }
    }
    return returnShaders;
}

void ShaderProgram::removeShaderDefine(const std::string& define){
    vectorImpl<std::string >::iterator it = find(_definesList.begin(), _definesList.end(), define);
    if (it != _definesList.end()) _definesList.erase(it);
    else D_ERROR_FN(Locale::get("ERROR_INVALID_SHADER_DEFINE_DELETE"),define.c_str(),getName().c_str());
}

void ShaderProgram::addShaderUniform(const std::string& uniform, const ShaderType& type) {
    _customUniforms[type].push_back(uniform);
}

void ShaderProgram::removeUniform(const std::string& uniform, const ShaderType& type) {
    vectorImpl<std::string >::const_iterator it = find(_customUniforms[type].begin(), _customUniforms[type].end(), uniform);
    if (it != _customUniforms[type].end()) _customUniforms[type].erase(it);
    else D_ERROR_FN(Locale::get("ERROR_INVALID_SHADER_UNIFORM_DELETE"), uniform.c_str(), (U32)type , getName().c_str());
}

void ShaderProgram::recompile(const bool vertex, const bool fragment, const bool geometry, const bool tessellation, const bool compute){
    _linked = false;
    _wasBound = _bound;

    if(_wasBound) unbind();

    //update refresh tags
    _refreshStage[VERTEX_SHADER] = vertex;
    _refreshStage[FRAGMENT_SHADER] = fragment;
    _refreshStage[GEOMETRY_SHADER] = geometry;
    _refreshStage[TESSELATION_CTRL_SHADER] = tessellation;
    _refreshStage[TESSELATION_EVAL_SHADER] = tessellation;
    _refreshStage[COMPUTE_SHADER] = compute;
    //recreate all the needed shaders
    generateHWResource(getName());

    if(_wasBound)  bind();
}

Commits for Divide-Framework/trunk/Source Code/Hardware/Video/Shaders/ShaderProgram.cpp

Diff revisions: vs.
Revision Author Commited Message
286 Diff Diff IonutCava picture IonutCava Fri 18 Jul, 2014 16:32:03 +0000

[Ionut] [[BR]]

    • very buggy commit ** [[BR]]

- New rendering pipeline: [[BR]]
— Bumped OpenGL version to 4.4 [[BR]]
— Command based rendering. GFXDevice dispatches rendering commands to their respective buffers [[BR]]
— State changing is exclusively controlled by the GFXDevice class [[BR]]
— Material properties and transform matrices are stored in shader storage buffers that are updated after culling and uploaded once per RenderPass. Objects use drawIDs to index data in shaders [[BR]]
— Removed all custom matrices and other, per shader, bind data [[BR]]
— Removed per node light data. Light culling and shader buffers will replace the old light management system [[BR]]
— Framebuffers now use the Texture class for attachments [[BR]]
— Sampler objects now work like RenderStateBlocks. GL_API handles them and stores them in a hash indexed map [[BR]]
— Removed “prepareMaterial” calls. Pre-draw material setup is now only limited to texture binding [[BR]]
— Moved immediate mode emulation and primitive rendering from API level to GFXDevice level [[BR]]
— Framebuffer rendering must be completed with a call to end() to ensure proper MSAA resolve (asserts, otherwise) [[BR]]
- Fixed hash code generation for RenderStateBlock (and now, glSamplerObject) using boost::hash_combine [[BR]]
- Temporarily disabled XML caching for materials [[BR]]

283 Diff Diff IonutCava picture IonutCava Tue 01 Jul, 2014 18:16:16 +0000

[Ionut][[BR]]
- Upload Viewport, camera position and zPlanes data to the gpu using the _matricesBuffer instead of ShaderProgram’s “uploadNodeMatrices” method [[BR]]
- Removed most matrices constructed with the worldMatrix (worldView, worldViewProjection, etc) to allow better batching of transforms. [[BR]]
— Both changes will allow the elimination of the “uploadNodeMatrices” and “setLoD” methods [[BR]]

280 Diff Diff IonutCava picture IonutCava Sat 28 Jun, 2014 19:11:37 +0000

[Ionut] [[BR]]
- Improve ClipPlane management (bunch equations into the matrix shader buffer) [[BR]]
- Immediate mode emulation primitives set their own state based on specified hash instead of relying on state functions to be defined [[BR]]
- updateStates() function is now called right before the actual draw call to facilitate future batching work [[BR]]
- added tracked bool values (similar to those in ShaderInfo) to SGN class to fix selection bug. [[BR]]
— will probably create a “stateTracker” class to allow multiple classes to use tracked variables without all of the code duplication [[BR]]

278 Diff Diff IonutCava picture IonutCava Thu 19 Jun, 2014 18:09:59 +0000

[Ionut][[BR]]
- Preliminary work on generic shader function selection infrastructure [[BR]]

277 Diff Diff IonutCava picture IonutCava Tue 17 Jun, 2014 19:27:29 +0000

[Ionut] [[BR]]
- Change PostFX shader to be subroutine-based (instead of using if-else statements) [[BR]]

275 Diff Diff IonutCava picture IonutCava Fri 13 Jun, 2014 15:11:02 +0000

[Ionut [[BR]]
- Removed all GLM dependencies (great library, but my math class can handle all of my requirements now) [[BR]]
- Moved view/projection/texture matrix management to GFXDevice class (from API specific classes) [[BR]]

274 Diff Diff IonutCava picture IonutCava Fri 13 Jun, 2014 12:56:03 +0000

[Ionut] [[BR]]
- Simplified buffer based rendering (VertexBuffer & GenericVertexData are now exclusively command based) [[BR]]
- Update bone buffer to persistent mapped-SSBO system with double-buffering [[BR]]
- Simplified sky rendering and (finally) reduced the sun’s radius [[BR]]

273 Diff Diff IonutCava picture IonutCava Wed 11 Jun, 2014 20:34:00 +0000

[Ionut] [[BR]]
- Improved batching part2: [[BR]]
— Moved all bone transformation matrices upload from uniform functions in SceneNode to Shader Storage Buffers in AnimationController class with updates controlled by SceneGraphNode’s AnimationComponent [[BR]]
-— No double-buffering or efficient mapping of data yet. Just raw buffer updates [[BR]]
— Replaced all RenderStateBlock* pointers with I64 hash values [[BR]]
-— Will be used later in draw commands as per-shader state hash [[BR]]
— Moved getShaderProgram from Material to Material::ShaderInfo [[BR]]
-— Improved redundant uniform checks [[BR]]
— Improved texture unit changing in case of redundant texture bind case (i.e. skip changing the texture unit) [[BR]]
[[BR]]
- Improved float and double comparison functions using algorithms described in http://randomascii.wordpress.com/2012/02/13/dont-store-that-in-a-float/ [[BR]]
- Added a new utility function, DIVIDE_ASSERT, to more easily bind an assert check with a specific message [[BR]]
- Added missing files from Forward+ renderer’s initial code [[BR]]

272 Diff Diff IonutCava picture IonutCava Wed 11 Jun, 2014 11:30:51 +0000

[Ionut] [[BR]]
- Added initial code for Forward+ rendering (grid based light culling) [[BR]]
- Simplified Light class [[BR]]
- Moved more light uniform data to ShaderBuffers [[BR]]
- Double buffered grass rendering [[BR]]
- Added a better attribute interface to GenericVertexData [[BR]]
- Fixed screenshot capture [[BR]]
- Fixed texture double-bind checks [[BR]]

268 IonutCava picture IonutCava Wed 04 Jun, 2014 10:20:27 +0000

[IonutCava] [[BR]]
- Terrain and vegetation updates: [[BR]]
— Use standard phong lighting model [[BR]]
— Separate grass patches per chunk [[BR]]
— Reduce number of required texture bind points for terrain by adding both textures and normal maps in a single texture array [[BR]]
— Draw terrain with 2 drawcalls (using glMultiDrawElements twice, once for LoD == 0 and once for LoD > 0) [[BR]]
[[BR]]
- Buffer management updates: [[BR]]
— Unified buffer binding system [[BR]]
— Made Uniform buffer objects visible to all classes and moved lightUBO to LightManager, matricesUBO to GFXDevice etc [[BR]]
— Added initial support for Shader Buffer Objects [[BR]]
— Moved viewport management to GFXDevice class [[BR]]
[[BR]]
- Rendering improvements: [[BR]]
— Added Hi-Z occlusion culling to instanceCull shader (using Hi-Z depth buffer constructed in GFXDevice class) [[BR]]
— Resolved issues with shadow maps overriding texture bind locations [[[BR]]
— Improved shader and shader program loading [[BR]]
— Improved material transparency support [[BR]]
— Added buffer lock manager class from “Approaching Zero Driver Overhead in OpenGL (Presented by NVIDIA)” speech at GDC14 [[BR]]