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
/*
   Copyright (c) 2014 DIVIDE-Studio
   Copyright (c) 2009 Ionut Cava

   This file is part of DIVIDE Framework.

   Permission is hereby granted, free of charge, to any person obtaining a copy of this software
   and associated documentation files (the "Software"), to deal in the Software without restriction,
   including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
   subject to the following conditions:

   The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
   INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
   IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
   OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 */

#ifndef _MATERIAL_H_
#define _MATERIAL_H_

#include "core.h"
#include "Utility/Headers/XMLParser.h"
#include "Utility/Headers/StateTracker.h"
#include "Core/Resources/Headers/Resource.h"
#include "Hardware/Video/Headers/RenderAPIEnums.h"
#include "Core/Resources/Headers/ResourceDescriptor.h"

class Texture;
class ShaderProgram;
class RenderStateBlock;
class ResourceDescriptor;
class RenderStateBlockDescriptor;
enum RenderStage;
enum BlendProperty;

class Material : public Resource {
public:
  enum BumpMethod {
        BUMP_NONE = 0,   //<Use phong
        BUMP_NORMAL = 1, //<Normal mapping
        BUMP_PARALLAX = 2,
        BUMP_RELIEF = 3,
        BumpMethod_PLACEHOLDER = 4
    };

    enum TextureUsage {
        TEXTURE_UNIT0 = 0,
        TEXTURE_UNIT1 = 1,
        TEXTURE_NORMALMAP = 2,
        TEXTURE_OPACITY   = 3,
        TEXTURE_SPECULAR  = 4,
        TextureUsage_PLACEHOLDER = 5
    };

    /// How should each texture be added
    enum TextureOperation {
        TextureOperation_Multiply = 0x0,
        TextureOperation_Add = 0x1,
        TextureOperation_Subtract = 0x2,
        TextureOperation_Divide = 0x3,
        TextureOperation_SmoothAdd = 0x4,
        TextureOperation_SignedAdd = 0x5,
        TextureOperation_Decal = 0x6,
        TextureOperation_Replace = 0x7,
        TextureOperation_PLACEHOLDER = 0x8
    };

    enum TranslucencySource {
        TRANSLUCENT_DIFFUSE = 0,
        TRANSLUCENT_OPACITY_MAP,
        TRANSLUCENT_DIFFUSE_MAP,
        TRANSLUCENT_NONE
    };
    /// Not used yet but implemented for shading model selection in shaders
    /// This enum matches the ASSIMP one on a 1-to-1 basis
    enum ShadingMode {
        SHADING_FLAT = 0x1,
        SHADING_GOURAUD = 0x2,
        SHADING_PHONG = 0x3,
        SHADING_BLINN = 0x4,
        SHADING_TOON = 0x5,
        SHADING_OREN_NAYAR = 0x6,
        SHADING_MINNAERT = 0x7,
        SHADING_COOK_TORRANCE = 0x8,
        SHADING_NONE = 0x9,
        SHADING_FRESNEL = 0xa,
        ShadingMode_PLACEHOLDER = 0xb
    };

    /// ShaderData stores information needed by the shader code to properly shade objects
    struct ShaderData{
        vec4<F32> _diffuse;  /* diffuse component */
        vec4<F32> _ambient;  /* ambient component */
        vec4<F32> _specular; /* specular component*/
        vec4<F32> _emissive; /* emissive component*/
        F32 _shininess;      /* specular exponent */
        I32 _textureCount;

        ShaderData() : _textureCount(0),
            _ambient(vec4<F32>(vec3<F32>(1.0f) / 5.0f, 1)),
            _diffuse(vec4<F32>(vec3<F32>(1.0f) / 1.5f, 1)),
            _specular(0.8f, 0.8f, 0.8f, 1.0f),
            _emissive(0.6f, 0.6f, 0.6f, 1.0f),
            _shininess(5) {}
    };

    /// ShaderInfo stores information about the shader programs used by this material
    struct ShaderInfo {
        ShaderProgram* _shaderRef;
        std::string _shader;
        bool _computedShader;
        bool _isCustomShader;
        vectorImpl<std::string> _shaderDefines;

        ShaderProgram* const getProgram();

        inline StateTracker<bool>& getTrackedBools() { return _trackedBools; }

        ShaderInfo()
        {
            _shaderRef = nullptr;
            _shader = "";
            _computedShader = false;
            _isCustomShader = false;
            for(U8 i = 0; i < ShaderType_PLACEHOLDER; ++i)
                memset(_shadingFunction[i], 0, BumpMethod_PLACEHOLDER * sizeof(U32));
        }

        U32 _shadingFunction[ShaderType_PLACEHOLDER][BumpMethod_PLACEHOLDER];

    protected:
        StateTracker<bool> _trackedBools;
    };
  
public:
    Material();
    ~Material();

    bool unload();
    void update(const U64 deltaTime);

    inline void setDiffuse(const vec4<F32>& value)  { _dirty = true; _shaderData._diffuse = value;  if (value.a < 0.95f) _translucencyCheck  = false; }
    inline void setAmbient(const vec4<F32>& value)  { _dirty = true; _shaderData._ambient = value;  }
    inline void setSpecular(const vec4<F32>& value) { _dirty = true; _shaderData._specular = value; }
    inline void setEmissive(const vec3<F32>& value) { _dirty = true; _shaderData._emissive = value; }

    inline void setHardwareSkinning(const bool state) { _dirty = true; _hardwareSkinning = state; }
    inline void setOpacity(F32 value)   { _dirty = true; _shaderData._diffuse.a = value; _translucencyCheck = false; }
    inline void setShininess(F32 value) { _dirty = true; _shaderData._shininess = value; }

    inline void useAlphaTest(const bool state)          { _useAlphaTest = state; }
    inline void setShadingMode(const ShadingMode& mode) { _shadingMode = mode; }

    void setDoubleSided(const bool state, const bool useAlphaTest = true);
    void setTexture(TextureUsage textureUsageSlot, Texture* const texture, const TextureOperation& op = TextureOperation_Replace);
    /// Add a texture <-> bind slot pair to be bound with the default textures on each "bindTexture" call
    inline void addCustomTexture(Texture* texture, U32 offset) {
        // custom textures are not material dependencies!
        _customTextures.push_back(std::make_pair(texture, offset));
    }

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

        _customTextures.erase(it);

        return true;
    }
        
    ///Set the desired bump mapping method.
    void setBumpMethod(const BumpMethod& newBumpMethod);
    ///Shader modifiers add tokens to the end of the shader name.
    ///Add as many tokens as needed but separate them with a ".". i.e: "Tree.NoWind.Glow"
    inline void addShaderModifier(const std::string& shaderModifier) { _shaderModifier = shaderModifier; }
    ///Shader defines, separated by commas, are added to the generated shader
    ///The shader generator appends "#define " to the start of each define
    ///For example, to define max light count and max shadow casters add this string:
    ///"MAX_LIGHT_COUNT 4, MAX_SHADOW_CASTERS 2"
    ///The above strings becomes, in the shader:
    ///#define MAX_LIGHT_COUNT 4
    ///#define MAX_SHADOW_CASTERS 2
    inline void addShaderDefines(RenderStage renderStage, const std::string& shaderDefines) {
        _shaderInfo[renderStage]._shaderDefines.push_back(shaderDefines);
    }

    inline void addShaderDefines(const std::string& shaderDefines)	{
        addShaderDefines(FINAL_STAGE, shaderDefines);
        addShaderDefines(Z_PRE_PASS_STAGE, shaderDefines);
        addShaderDefines(SHADOW_STAGE, shaderDefines);
    }

    ///toggle multi-threaded shader loading on or off for this material
    inline void setShaderLoadThreaded(const bool state) {_shaderThreadedLoad = state;}
    void setShaderProgram(const std::string& shader, const RenderStage& renderStage = FINAL_STAGE, const bool computeOnAdd = false);
    size_t setRenderStateBlock(const RenderStateBlockDescriptor& descriptor, const RenderStage& renderStage);

    void getSortKeys(I32& shaderKey, I32& textureKey) const;

   inline void getMaterialMatrix(mat4<F32>& retMatrix) const {
        retMatrix.setCol(0,_shaderData._ambient);
        retMatrix.setCol(1,_shaderData._diffuse);
        retMatrix.setCol(2,_shaderData._specular);
        retMatrix.setCol(3,vec4<F32>(_shaderData._emissive, _shaderData._shininess));
    }

    inline U8    getTextureCount() const {return _shaderData._textureCount;}

                 size_t            getRenderStateBlock(RenderStage currentStage);
    inline       Texture*	 const getTexture(TextureUsage textureUsage) {return _textures[textureUsage];}
             ShaderInfo&           getShaderInfo(RenderStage renderStage = FINAL_STAGE);
    
    inline const TextureOperation& getTextureOperation() const { return _operation; }
    inline const ShaderData&       getShaderData()       const { return _shaderData; }
    inline const ShadingMode&      getShadingMode()      const { return _shadingMode; }
    inline const BumpMethod&       getBumpMethod()       const { return _bumpMethod; }

    void bindTextures();

    void clean();
    bool isTranslucent();

    inline void dumpToFile(bool state) { _dumpToFile  = state;}
    inline bool isDirty()       const {return _dirty;}
    inline bool isDoubleSided() const {return _doubleSided;}
    inline bool useAlphaTest()  const {return _useAlphaTest;}

    // Checks if the shader needed for the current stage is already constructed. Returns false if the shader was already ready.
    bool computeShader(const RenderStage& renderStage = FINAL_STAGE); //Set shaders;

    static void unlockShaderQueue()   {_shaderQueueLocked = false; }
    static void serializeShaderLoad(const bool state) { _serializeShaderLoad = state; }

private:
    void recomputeShaders();
    void computeShaderInternal();
    void setShaderProgramInternal(const std::string& shader, const RenderStage& renderStage = FINAL_STAGE, const bool computeOnAdd = false);
    static bool isShaderQueueLocked() {return _shaderQueueLocked; }
    static void lockShaderQueue()     {if(_serializeShaderLoad) _shaderQueueLocked = true; }
    
private:
    static bool _shaderQueueLocked;
    static bool _serializeShaderLoad;

    std::queue<std::pair<RenderStage, ResourceDescriptor> > _shaderComputeQueue;
    ShadingMode _shadingMode;
    std::string _shaderModifier; //<use for special shader tokens, such as "Tree"
    vectorImpl<TranslucencySource > _translucencySource;
    bool _dirty;
    bool _dumpToFile;
    bool _translucencyCheck;
    bool _useAlphaTest; //< use discard if true / blend if otherwise
    bool _doubleSided;
    bool _hardwareSkinning;     ///< Use shaders that have bone transforms implemented
    typedef Unordered_map<RenderStage, ShaderInfo > shaderInfoMap;
    shaderInfoMap _shaderInfo;

    bool        _shaderThreadedLoad;
    bool        _computedShaderTextures;//<if we should recompute only fragment shader on texture change
    /// use this map to add more render states mapped to a specific state
    /// 3 render state's: Normal, reflection and shadow
    typedef Unordered_map<RenderStage, size_t /*renderStateBlockHash*/ > renderStateBlockMap;
    renderStateBlockMap _defaultRenderStates;
    
    /// use this map to add textures to the material
    vectorImpl<Texture* > _textures;
    vectorImpl<std::pair<Texture*, U32> > _customTextures;

    /// use the below map to define texture operation
    TextureOperation _operation;

    BumpMethod _bumpMethod;

    ShaderData _shaderData;
};

#endif

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

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]]

281 Diff Diff IonutCava picture IonutCava Sat 28 Jun, 2014 20:55:30 +0000

[Ionut] [[BR]]
- Added a basic and primitive state tracking class [[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]]

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

264 Diff Diff k1ngp1n picture k1ngp1n Tue 27 May, 2014 13:04:38 +0000

[Ionut] [[BR]]
- New camera system: [[BR]]
— Stack based (push/pop active camera) [[BR]]
— Per camera frustum [[BR]]
— Per camera projection [[BR]]
— Shadow mapping now uses the new camera system (each light has a shadow camera) [[BR]]
[[BR]]
- New terrain, water and vegetation system: [[BR]]
— Direct import of terrain from L3DT both as 8-bit grayscale and 16-bit raw formats [[BR]]
— Multiple alpha maps for texture splatting support [[BR]]
— Per texture detail map support [[BR]]
— Transform feedback based visibility culling for vegetation [[BR]]
— Alpha-map based vegetation placing on terrain [[BR]]
— Water now uses a refraction map instead of alpha blending for better refraction effects [[BR]]
[[BR]]
- SceneGraph improvements: [[BR]]
— Better bounding box updates from child to parent [[BR]]
— Better onDraw / postDraw implementation [[BR]]
[[BR]]
- Performance improvements: [[BR]]
— Batch 2D rendering tasks together as much as possible[[BR]]
— Improve renderStateBlock hash generation for better sorting [[BR]]
— Move most state related gfx changes from API implementation to the GFXDevice class [[BR]]
— Move viewport stack to the GFXDevice class [[BR]]
— Added various performance counters (frame duration with round-robin query system, draw call count, etc) [[BR]]
— Fixed and improved clip plane management [[BR]]
— Delete client-side texture data after GPU upload [[BR]]
[[BR]]
- New features: [[BR]]
— Added callback support to the Task class so that a specific task may call a function in the main thread upon completion [[BR]]
— Added mouse-wheel zoom support to Orbit/ThirdPerson cameras [[BR]]
— Added 2D Texture Array support (e.g. used for terrain textures) [[BR]]

262 Diff Diff k1ngp1n picture k1ngp1n Tue 06 May, 2014 21:04:00 +0000

[Ionut] [[BR]]
- Some AI refactoring (basic AIEntity <-> AESOP interoperability) [[BR]]
- Some render batch sorting code refactored and fixed (wasn’t properly sorted in FINAL_STAGE) [[BR]]
- Simplified RenderStateBlockDescriptor and deferred hash value calculation [[BR]]
- Basic draw call count implementation [[BR]]
- Renamed some classes [[BR]]

260 k1ngp1n picture k1ngp1n Sat 03 May, 2014 19:33:41 +0000

[Ionut] [[BR]]
- More work on CSM. Reverted back to VSM to allow easier blurring and filtering [[BR]]
- Rewrote FrameBuffer classes to fix MSAA and memory leaks that occurred on resize (double creation of textures) [[BR]]
— Removed FBType. FrameBuffer types depend only on attachment types and if it’s MSAA enabled or not [[BR]]
- Rewrote RenderState classes to be API agnostic [[BR]]
- Bug fixes in math classes [[BR]]
- Changed “resolution change” logic [[BR]]
- Simplified some options in config.xml [[BR]]
- Improved per-light shadow options [[BR]]