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

#include "Core/Headers/ParamHandler.h"
#include "Graphs/Headers/SceneGraphNode.h"
#include "Hardware/Video/Headers/GFXDevice.h"
#include "Core/Resources/Headers/ResourceCache.h"
#include "Rendering/Lighting/ShadowMapping/Headers/ShadowMap.h"
#include "Hardware/Video/Buffers/FrameBufferObject/Headers/FrameBufferObject.h"

LightManager::LightManager() : FrameListener(),
							   _shadowMapsEnabled(true),
							   _previewShadowMaps(false),
							   _dominantLight(NULL)
{
}

LightManager::~LightManager()
{
	clear();
}

void LightManager::init(){
	REGISTER_FRAME_LISTENER(&(this->getInstance()));
}

bool LightManager::clear(){
	//Lights are removed by the sceneGraph
	for_each(LightMap::value_type& it, _lights){
		//in case we had some light hanging
		RemoveResource(it.second);
	}

	_lights.clear();

	return _lights.empty();
}

bool LightManager::addLight(Light* const light){
	if(light->getId() == 0)
		light->setId(generateNewID());
	
	light->addShadowMapInfo(New ShadowMapInfo(light));

	if(_lights.find(light->getId()) != _lights.end()){
		ERROR_FN(Locale::get("ERROR_LIGHT_MANAGER_DUPLICATE"),light->getId());
		return false;
	}

	_lights.insert(std::make_pair(light->getId(),light));
	return true;
}

bool LightManager::removeLight(U32 lightId){
	LightMap::const_iterator it = _lights.find(lightId);

	if(it == _lights.end()){
		ERROR_FN(Locale::get("ERROR_LIGHT_MANAGER_REMOVE_LIGHT"),lightId);
		return false;
	}

	(it->second)->removeShadowMapInfo();
	_lights.erase(lightId); //remove it from the map
	return true;
}

U32 LightManager::generateNewID(){
	U32 tempId = _lights.size();

	while(!checkId(tempId))
		tempId++;
	
	return tempId;
}

bool LightManager::checkId(U32 value){
	for_each(LightMap::value_type& it, _lights)
		if(it.second->getId() == value)
			return false;

	return true;
}

void LightManager::idle(){
	_shadowMapsEnabled = ParamHandler::getInstance().getParam<bool>("rendering.enableShadows");
}

///Check light properties for every light (this is bound to the camera change listener group
///Update only if needed. Get projection and view matrices if they changed
///Also, search for the dominant light if any
void LightManager::update(){
	for_each(Light* light, _currLightsPerNode){
		light->updateState();
		if(!_dominantLight){ //if we do not have a dominant light registered, search for one
			if(light->getLightMode() == LIGHT_MODE_DOMINANT){
				//setting a light as dominant, will automatically inform the lightmanager, but just in case, make sure
				_dominantLight = light;
			}
		}
	}
}

///When pre-rendering is done, the Light Manager will generate the shadow maps
/// Returning false in any of the FrameListener methods will exit the entire application!
bool LightManager::framePreRenderEnded(const FrameEvent& evt){
	if(!_shadowMapsEnabled) 
		return true;

	//Stop if we have shadows disabled
	_lightProjectionMatricesCache.resize(Config::MAX_SHADOW_CASTING_LIGHTS_PER_NODE);
	//Tell the engine that we are drawing to depth maps
	RenderStage previousRS = GFX_DEVICE.getRenderStage();
	//set the current render stage to SHADOW_STAGE
	GFX_DEVICE.setRenderStage(SHADOW_STAGE);
	// if we have a dominant light, generate only it's shadows
	if(_dominantLight){
		 // When the entire scene is ready for rendering, generate the shadowmaps
		_dominantLight->generateShadowMaps(GET_ACTIVE_SCENE()->renderState());
	}else{
		//generate shadowmaps for each light
		for_each(LightMap::value_type& light, _lights){
			light.second->generateShadowMaps(GET_ACTIVE_SCENE()->renderState());
		}
	}
	//Revert back to the previous stage
	GFX_DEVICE.setRenderStage(previousRS);

	return true;
}

void LightManager::previewShadowMaps(Light* light) {
	//Stop if we have shadows disabled
	if(!_shadowMapsEnabled || !_previewShadowMaps ||  !GFX_DEVICE.isCurrentRenderStage(DISPLAY_STAGE))
		return;

	Light* localLight = light;

	if(_dominantLight){
		localLight = _dominantLight;
	}else{
		if(localLight == NULL)	
			localLight = _lights[0];
	}

	if(!localLight->castsShadows())
		return;

	localLight->getShadowMapInfo()->getShadowMap()->previewShadowMaps();
}

//If we have computed shadowmaps, bind them before rendering any geometry;
//Always bind shadowmaps to slots Config::MAX_TEXTURE_STORAGE, Config::MAX_TEXTURE_STORAGE+1, Config::MAX_TEXTURE_STORAGE+2 ...
void LightManager::bindDepthMaps(Light* light, U8 lightIndex, U8 offset, bool overrideDominant){
	//Skip applying shadows if we are rendering to depth map, or we have shadows disabled
	if(!_shadowMapsEnabled || _lightProjectionMatricesCache.empty()) 
		return;

	Light* lightLocal = light;
	///If we have a dominant light, then both shadow casting lights are the same = the dominant one
	///Shadow map binding has a failsafe check for this, so it's ok to call bind twice
	if(_dominantLight && !overrideDominant)
		lightLocal = _dominantLight;
	
	if(!lightLocal->castsShadows())
		return;

	if(lightLocal->getLightType() == LIGHT_TYPE_DIRECTIONAL)
		offset = Config::MAX_TEXTURE_STORAGE + Config::MAX_SHADOW_CASTING_LIGHTS_PER_NODE;
	
	if(lightLocal->getLightType() == LIGHT_TYPE_POINT)
		offset = Config::MAX_TEXTURE_STORAGE + Config::MAX_SHADOW_CASTING_LIGHTS_PER_NODE + 1;
	
	_lightProjectionMatricesCache[lightIndex] = lightLocal->getLightProjectionMatrix();

	lightLocal->getShadowMapInfo()->getShadowMap()->Bind(offset);
}

void LightManager::unbindDepthMaps(Light* light, U8 offset, bool overrideDominant){
    if(!_shadowMapsEnabled || _lightProjectionMatricesCache.empty()) 
		return;

	Light* lightLocal = light;

	if(_dominantLight && !overrideDominant)
		lightLocal = _dominantLight;
	
	if(!lightLocal->castsShadows())
		return;

	if(lightLocal->getLightType() == LIGHT_TYPE_DIRECTIONAL)
		offset =  Config::MAX_TEXTURE_STORAGE + Config::MAX_SHADOW_CASTING_LIGHTS_PER_NODE;
	
	if(lightLocal->getLightType() == LIGHT_TYPE_POINT)
		offset = Config::MAX_TEXTURE_STORAGE + Config::MAX_SHADOW_CASTING_LIGHTS_PER_NODE + 1;
	
	lightLocal->getShadowMapInfo()->getShadowMap()->Unbind(offset);
}

bool LightManager::shadowMappingEnabled() const {
	if(!_shadowMapsEnabled)
		return false;

	for_each(LightMap::value_type light, _lights){
		if(!light.second->castsShadows()) 
			continue;

		ShadowMapInfo* smi = light.second->getShadowMapInfo();
		//no shadow info;
		if(!smi) 
			continue; 

		ShadowMap* sm = smi->getShadowMap();
		//no shadow map;
		if(!sm) 
			continue; 

		if(sm->getDepthMap()) 
			return true;
	}

	return false;
}

struct scoreCmpFnc{
	bool operator()(Light* const a, Light* const b) const {
		return (a)->getScore() < (b)->getScore();
	}
};

U8 LightManager::findLightsForSceneNode(SceneGraphNode* const node, LightType typeFilter){
	const vec3<F32> lumDot( 0.2125f, 0.7154f, 0.0721f );
	F32 luminace = 0.0f;
	F32 dist = 0.0f;
	F32 weight = 1.0f; // later
	U8 i = 0;
	vec3<F32> distToLight;
	// Reset light buffer
	_tempLightsPerNode.resize(_lights.size());
	_currLightsPerNode.resize(0);
	_currLightTypes.resize(0);
    _currLightsEnabled.resize(0);
	_currShadowLights.resize(0);
	// loop over every light in the scene
	// ToDo: add a grid based light search system? -Ionut
	for_each(LightMap::value_type& lightIt, _lights){
		Light* light = lightIt.second;
		if(!light->getEnabled())
			continue;
			
		LightType lType = light->getLightType();
		if(lType != LIGHT_TYPE_DIRECTIONAL )  {
			// get the luminosity.
			luminace = vec3<F32>(light->getVProperty(LIGHT_PROPERTY_DIFFUSE)).dot(lumDot);
			luminace *= light->getFProperty(LIGHT_PROPERTY_BRIGHTNESS);

	        F32 radiusSq = squared(light->getFProperty(LIGHT_PROPERTY_RANGE) + node->getBoundingSphere().getRadius());
			// get the distance to the light... score it 1 to 0 near to far.
			distToLight = node->getBoundingBox().getCenter() - light->getPosition();
            F32 distSq = radiusSq - distToLight.lengthSquared();

			if ( distSq > 0.0f )
			{
				dist = distSq /( 1000.0f * 1000.0f );
				CLAMP<F32>(dist, 0.0f, 1.0f );
			}
			light->setScore( luminace * weight * dist );

		}else{// directional
			light->setScore( weight );
		}
				
		// use type filter
		if((typeFilter != LIGHT_TYPE_PLACEHOLDER && lType == typeFilter) || //< wether we have the correct light type
			typeFilter == LIGHT_TYPE_PLACEHOLDER){ //< or we did not specify a type filter
			_tempLightsPerNode[i++] = light;
		}
	}

	// sort the lights by score
	std::sort(_tempLightsPerNode.begin(), 
		      _tempLightsPerNode.end(),
			  scoreCmpFnc());

	// create the light buffer for the specified node
	I32 maxLights = _tempLightsPerNode.size();
	CLAMP<I32>(maxLights, 0, Config::MAX_LIGHTS_PER_SCENE_NODE);
	for(U8 i = 0; i < maxLights; i++){
		_currLightsPerNode.push_back(_tempLightsPerNode[i]);
		_currLightTypes.push_back(_tempLightsPerNode[i]->getLightType());
        _currLightsEnabled.push_back(_tempLightsPerNode[i]->getEnabled() ? 1 : 0);
		_currShadowLights.push_back(_tempLightsPerNode[i]->castsShadows() ? 1 : 0);
	}

	return maxLights;
}

Commits for Divide-Framework/trunk/Source Code/Managers/LightManager.cpp

Diff revisions: vs.
Revision Author Commited Message
168 Diff Diff k1ngp1n picture k1ngp1n Sat 26 Oct, 2013 19:03:21 +0000

- Reworked the Camera class[[BR]]
— Now fully quaternion based [[BR]]
— Basic camera types added but not used yet (third person, first person, orbit) [[BR]]
- Cleaned up Material and Texture handling [[BR]]
- Added clipping plane support [[BR]]
— Similar to OpenGL fixed-function clip planes but fully shader driven [[BR]]
— Added a new class, “Plane”, that helps define clip planes [[BR]]
- Optimized the Singleton class to allow faster “getInstance” calls without performance penalties [[BR]]
-- “createInstance” must be called for each singleton class before usage. Or “gerOrCreateInstance” can be used, which is basically the former “getInstance” implementation [[BR]]
- Improved console logging by changing some heap allocations to stack and removing dependencies on the std::string class [[BR]]
- Added a lot of performance optimizations related to coding standards and redundant calculations [[BR]]
— e.g. Frustum AABB check didn’t need to recompute the AABB points as they were calculated already [[BR]]
— e.g. A vector did not need to be set to 0 on initialization as that is already it’s default state on creation [[BR]]
— e.g. Faster Framerate and Timing calculations by using less member variables that are not needed outsied of calling functions [[BR]]
- The SceneState now contains the SceneRenderState and is passed on to the SceneGraph’s update calls [[BR]]
- Better material export/import to/from XML format [[BR]]
- More bug fixes and cleanups [[BR]]

163 Diff Diff k1ngp1n picture k1ngp1n Thu 18 Jul, 2013 12:24:26 +0000

[Ionut] [[BR]]
- Fixed a rendering bug with the previous terrain rendering system (number of strips was not calculated correctly. had to add the primitive restart indices to the list as well) [[BR]]
- Fixed a rendering bug with the previous double sided Quad3D patch (water planes should not be double sided. The first parameter of the bool mask of the resource descriptor for water planes now controls whether the Quad will be single or double sided) [[BR]]
- NavMesh debug draw now uses a caching system for rendering instead of re-submitting the same geometry every frame [[BR]]
— Fixed a bug that prevented GLIM primitives to be cached if they had “canZombify” set to false [[BR]]
- Navigation meshes are now saved and loaded from file on creation. Delete the “nm” file from the navMeshes subfolder to recreate a navigation mesh for a scene. [[BR]]
- LightManager is now a FrameListener. ShadowMap generation is called with the “FramePreRenderEnd” event [[BR]]
- Terrain NavMesh uses the lowest LoD possible for now to improve creation times until all bugs are resolved [[BR]]
- Geometry importer now uses the “replace” operation for the base texture of objects [[BR]]
- glUniformBufferObjects are now a little less dependent on the GLM library [[BR]]
- Primitive restart is now toggled on or off at each VAO draw call [[BR]]
- Some GFXDevice inlining [[BR]]

152 Diff Diff k1ngp1n picture k1ngp1n Thu 20 Jun, 2013 14:23:31 +0000

[Ionut] [[BR]]
- New rendering pipeline (experimental and unstable): [[BR]]
— OpenGL 3.x clean context (glLight commands are still used for now, but UBO support is there, but not used yet) [[BR]]
— Custom matrix stacks and UBO based shader data (UBOs cause some link errors on some nVidia cards)[[BR]]
— Multi-threaded texture loading and shader compilation (mt shader compilation disabled for now. needs more tests) [[BR]]
— VAO rendering is self contained (no more enable/disable calls before a draw request) [[BR]]
— Render instance class used for rendering information [[BR]]
[[BR]]
- New unique ID generation base class: GUIDWrapper. Each class that derives from this, gets an application wide unique id on construction [[BR]]
- Added base code for an in-game editor using CEGUI [[BR]]
- Replaced some mutex locks with lockless data structures or atomic data [[BR]]
- CEGUI 0.8.2, FTGL-GL3 and GLIM 0.4 modified to support GLEW_MX if defined [[BR]]
- Dropped VS2008 support [[BR]]
- Networking library, server framework and ReCast files are now projects inside the Divide Framework solution [[BR]]
- New console command “setFov” that modifies the horizontal FoV value in realtime [[BR]]
- New console command “recompileShader” that reparses shader files, recompiles shaders and relinks shader programs who’s names match or contain the argument string [[BR]]
- New debug utility: axis angle drawn in corner of the screen if needed [[BR]]
- More ‘const’-s pasted around the code, more loop performance tweaks (allocations before a loop, tighter loops, etc), more utility member functions added to various classes [[BR]]

151 Diff Diff k1ngp1n picture k1ngp1n Tue 07 May, 2013 00:00:52 +0000

[Ionut] [[BR]]
- Better ReCast integration [[BR]]
— Any entity can be used as an obstacle in the NavMesh if that’s specified in each scene’s assets.xml file for said entity [[BR]]
— New console command, “createNavMesh”, that passes geometry data to ReCast [[BR]]
-— NavMesh generation is not yet complete [[BR]]
- Better PhysX integration [[BR]]
— Each scene passes data to and gets data from the Physics API better and safer[[BR]]
- Multi-threaded support extended: [[BR]]
— Event class replaced with Task [[BR]]
— Kernel uses a threadpool for scene tasks [[BR]]
— Each task can be added to a different threadpool if needed [[BR]]
— Most critical sections use the new boost::atomic wrapper for thread safety [[BR]]
- Rendering system updated [[BR]]
— VBO’s keep track of the geometry type internally [[BR]]
— Rendering by specific element list is internal to the VBO [[BR]]
— VBO’s can draw a “lite” version that doesn’t send Tangent, BiTangent and TexCoord data for depth rendering (disabled) [[BR]]
- Reflectors now offer a preview of the generated reflective texture if needed [[BR]]
- Buttons are now added and rendered by CEGUI [[BR]]
[[BR]]
Deprecation: [[BR]]
- Removed fixed pipeline material system [[BR]]
- Removed BoundingBox late update system [[BR]]
- Shadow references in the material system are now depth references [[BR]]
[[BR]]
Bug fixes: [[BR]]
- Problematic FBO double bind check removed [[BR]]
- Faster terrain rendering via chunk size selection through each scene’s terrain.xml[[BR]]
- Rendering is paused when the window is minimized [[BR]]
- CEGUI and impostors now render properly in deferred rendering mode [[BR]]
- Fixed various level 4 (VS2008) warnings [[BR]]
- Better state management and cleaning [[BR]]
- Better SceneGraph node management and trasformation/AABB update calls [[BR]]
- AITenisScene has proper collisions now [[BR]]

148 Diff Diff k1ngp1n picture k1ngp1n Sun 14 Apr, 2013 23:07:58 +0000

[Ionut] [[BR]]
- Changed the ParamHandler from using “boost::any” to the more faster “cdiggins::any”. More info here: http://bit.ly/YVGa9X [[BR]]
- Disabled mutexes from BoundingBox. Thread safety should be applied from a higher level [[BR]]
- Fixed a bug with important light selection for scene nodes [[BR]]
- Fixed a bug with material cache involving bump maps [[BR]]
- Fixed a bug with priority vertex properties for GLSL shaders [[BR]]

146 Diff Diff k1ngp1n picture k1ngp1n Wed 10 Apr, 2013 13:20:15 +0000

[Ionut] [[BR]]
*Final LightBranch updates 2/3 : Main trunk merge and build test (VC90, VC100, gDebugger) [[BR]]
-Merged light branch with trunk [[BR]]
-Deleted light branch [[BR]]

122 Diff Diff k1ngp1n picture k1ngp1n Mon 11 Jun, 2012 14:39:08 +0000

[Ionut] [[BR]]
-Restructured “Hardware” folder to match the rest of the projects header-separation pattern [[BR]]

121 Diff Diff k1ngp1n picture k1ngp1n Sun 10 Jun, 2012 16:40:45 +0000

[Ionut] [[BR]]
-Added basic localization support [[BR]]
-Added cross-platform INI parsing [[BR]]
-Moved ReCast+Detour to LIBS folder [[BR]]

117 Diff Diff k1ngp1n picture k1ngp1n Tue 05 Jun, 2012 17:30:40 +0000

[Ionut] [[BR]]
-Separated responsibilities between “Application” and “Kernel” [[BR]]
--“Application” handles data such as window dimensions, logs, “ParamHandler” etc [[BR]]
--“Kernel” handles the main loop, SFX, GFX, physics, sceneManager etc updates [[BR]]
---“Kernel” is now a “Core” component [[BR]]
-Reduced coupling between some classes by passing more info via parameters rather than relying on singleton access [[BR]]
--Ex: eyePos in “Terrain”,“Water” and “Trigger” classes is now passed as a "vec3<F32>" on render call rather than querying “CameraManager” [[BR]]
-Reworked “GLWrapper” shutdown routine [[BR]]
Singleton witch hunt [[BR]]
-“Kernel” is no longer a singleton and it’s initialized on application startup in the “Application” class[[BR]]
-“CameraManager” is no longer a singleton and it’s instantiated in the kernel [[BR]]

114 k1ngp1n picture k1ngp1n Sat 02 Jun, 2012 13:03:01 +0000

[Ionut][[BR]]
-First steps in moving away from a generalized “ResourceManager”: [[BR]]
--Added templated resource loaders (Core\Resources\ConcreteLoaders). Just add a new loader for a new resource type and it’s ready for use [[BR]]
---Next step involves moving loading responsibility from the resource itself to the resource loader that handles it’s creation [[BR]]
--Renamed the ResourceManager to ResourceCache and limited it’s responsibility from general resource operations to a more standard abstract template factory with cache [[BR]]
---Manager base class is renamed to BaseCache as it’s a wrapper for a cache map in essence [[BR]]
---Next step involves adding a ResourceCache per scene (dropping Singleton status) with the possibility of sharing resources between them (to avoid reloading existing resources for a new scene) [[BR]]
-Translated AITenisScene and PingPongScene source code to english [[BR]]