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

#include "GUI/Headers/GUIText.h"
#include "Graphs/Headers/SceneGraph.h"
#include "Rendering/Headers/Frustum.h"
#include "Utility/Headers/ImageTools.h"
#include "Core/Math/Headers/Transform.h"
#include "Core/Resources/Headers/ResourceCache.h"

#include "Geometry/Shapes/Headers/SubMesh.h"
#include "Geometry/Shapes/Headers/Predefined/Box3D.h"
#include "Geometry/Shapes/Headers/Predefined/Sphere3D.h"
#include "Geometry/Shapes/Headers/Predefined/Quad3D.h"
#include "Geometry/Shapes/Headers/Predefined/Text3D.h"

#include "Hardware/Video/Headers/GFXDevice.h"

//Max number of frames before an unused primitive is deleted (default: 180 - 3 seconds at 60 fps)
#define GLIM_MAX_FRAMES_ZOMBIE_COUNT 180

#ifndef FTGL_LIBRARY_STATIC
#define FTGL_LIBRARY_STATIC
#endif
#include <FTGL/ftgl.h>
#include <glim.h>
#include <gtc/matrix_transform.hpp>
#include <gtc/type_ptr.hpp>

namespace IMPrimitiveValidation{
	inline bool zombieCountMatch(glIMPrimitive* const priv){
		if(priv->_canZombify) return priv->zombieCounter() < GLIM_MAX_FRAMES_ZOMBIE_COUNT;
		else return true;
	}
}

void GL_API::beginFrame(){
	GLCheck(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT));
	GL_API::clearColor(DIVIDE_BLUE());
	SET_DEFAULT_STATE_BLOCK();
}

void GL_API::endFrame(){
	
	//Remove dead primitives in 3 steps (or we could automate this with shared_ptr?):
	//1) Partition the vector in 2 parts: valid objects first, zombie objects second
	vectorImpl<glIMPrimitive* >::iterator zombie = std::partition(_glimInterfaces.begin(),
							  							          _glimInterfaces.end(),
															  	  IMPrimitiveValidation::zombieCountMatch);
	//2) For every zombie object, free the memory it's using
	for( vectorImpl<glIMPrimitive *>::iterator i = zombie ; i != _glimInterfaces.end() ; ++i ){
		SAFE_DELETE(*i);
	}

	//3) Remove all the zombie objects once the memory is freed
	_glimInterfaces.erase(zombie, _glimInterfaces.end());

	//unbind all states (shaders, textures, buffers)
    clearStates(false,false,false,true);

	glfwSwapBuffers(Divide::GL::_mainWindow);
}

void GL_API::debugDraw(){
	drawDebugAxisInternal();

	_imShader->bind();
	_imShader->Uniform("tex",0);

	NS_GLIM::GLIM_BATCH::s_bForceWireframe = false;

	for_each(glIMPrimitive* priv, _glimInterfaces){
		if(!priv->_inUse && priv->_canZombify) {
			++priv->_zombieCounter;
			continue;
		}
		
		if(!priv->_setupStates.empty()){
			priv->_setupStates();
		}else{
			SET_DEFAULT_STATE_BLOCK(true);
		}
		if(priv->_hasLines){
			GLCheck(glLineWidth(priv->_lineWidth));
		}

		bool texture = (priv->_texture != NULL);

		if(texture){
			priv->_texture->Bind(0);
		}

		_imShader->Uniform("useTexture", texture);
		_imShader->uploadModelMatrices();

		priv->renderBatch(priv->forceWireframe());

		if(priv->_hasLines) {
			GLCheck(glLineWidth(1.0f));
		}
		if(priv->_texture){
			priv->_texture->Unbind(0);
		}

		if(!priv->_resetStates.empty()){
			priv->_resetStates();
		}
		if(priv->_canZombify){
			priv->_inUse = false;
		}
	}
	_imShader->unbind();
}

void GL_API::flush(){
	
    clearStates(false,false,false,false);
}

void GL_API::renderInViewport(const vec4<GLuint>& rect, boost::function0<void> callback){
    setViewport(rect);
	callback();
	restoreViewport();
}

void GL_API::drawBox3D(const vec3<GLfloat>& min,const vec3<GLfloat>& max, const mat4<GLfloat>& globalOffset){
	IMPrimitive* priv = getOrCreateIMPrimitive();

	priv->_hasLines = true;
	priv->_lineWidth = 4.0f;

	priv->beginBatch();

    vec4<U8> color(0,0,255,255);
	priv->attribute4ub("inColorData", color);

	priv->begin(LINE_LOOP);
		priv->vertex( vec3<F32>(min.x, min.y, min.z) );
		priv->vertex( vec3<F32>(max.x, min.y, min.z) );
		priv->vertex( vec3<F32>(max.x, min.y, max.z) );
		priv->vertex( vec3<F32>(min.x, min.y, max.z) );
	priv->end();

	priv->begin(LINE_LOOP);
		priv->vertex( vec3<F32>(min.x, max.y, min.z) );
		priv->vertex( vec3<F32>(max.x, max.y, min.z) );
		priv->vertex( vec3<F32>(max.x, max.y, max.z) );
		priv->vertex( vec3<F32>(min.x, max.y, max.z) );
	priv->end();

    priv->begin(LINES);
		priv->vertex( vec3<F32>(min.x, min.y, min.z) );
		priv->vertex( vec3<F32>(min.x, max.y, min.z) );
		priv->vertex( vec3<F32>(max.x, min.y, min.z) );
		priv->vertex( vec3<F32>(max.x, max.y, min.z) );
		priv->vertex( vec3<F32>(max.x, min.y, max.z) );
		priv->vertex( vec3<F32>(max.x, max.y, max.z) );
		priv->vertex( vec3<F32>(min.x, min.y, max.z) );
		priv->vertex( vec3<F32>(min.x, max.y, max.z) );
	priv->end();

	priv->endBatch();
}

void GL_API::setupLineState(const OffsetMatrix& mat, RenderStateBlock* const drawState,const bool ortho){
    Divide::GL::_setModelMatrix(mat.mat,false);
    SET_STATE_BLOCK(drawState,true);

	if(ortho){
		setViewport(vec4<U32>(_cachedResolution.width - 128, 0, 128, 128));
		Divide::GL::_matrixMode(VIEW_MATRIX);
		Divide::GL::_pushMatrix();
		Divide::GL::_loadIdentity();
	}
}

void GL_API::releaseLineState(const bool ortho){
    Divide::GL::_resetModelMatrix();
	if(ortho){
		restoreViewport();
		Divide::GL::_resetModelMatrix();
		Divide::GL::_matrixMode(VIEW_MATRIX);
		Divide::GL::_popMatrix();
	}
}


void GL_API::drawDebugAxisInternal(){
    if(!GFX_DEVICE.drawDebugAxis()) return;
	static bool axisData = false;
    if(!axisData){
        vec3<GLfloat> ORG(0,0,0);
        vec3<GLfloat> XP(1,0,0);
        vec3<GLfloat> YP(0,1,0);
        vec3<GLfloat> ZP(0,0,1);

        //Red X-axis
        _pointsA.push_back(ORG);
        _pointsB.push_back(XP);
        _colors.push_back(vec4<U8>(255,0,0,255));

        //Green Y-axis
        _pointsA.push_back(ORG);
        _pointsB.push_back(YP);
        _colors.push_back(vec4<U8>(0,255,0,255));

        //Blue Z-axis
        _pointsA.push_back(ORG);
        _pointsB.push_back(ZP);
        _colors.push_back(vec4<U8>(0,0,255,255));
        axisData = true;
    }

	vec3<F32> eyeVector = - (Divide::GL::_currentViewDirection.top() * 2);
	const glm::mat4& viewMatrix = Divide::GL::_viewMatrix.top();

    drawLines(_pointsA, _pointsB, _colors,
			  mat4<GLfloat>(glm::value_ptr(glm::lookAt(glm::vec3(eyeVector.x, eyeVector.y, eyeVector.z),
			                                           glm::vec3(0.0f),
													   glm::vec3(viewMatrix[0][1], 
													             viewMatrix[1][1],
																 viewMatrix[2][1])))),
			  true,
			  true);
}

void GL_API::drawLines(const vectorImpl<vec3<GLfloat> >& pointsA,
                       const vectorImpl<vec3<GLfloat> >& pointsB,
                       const vectorImpl<vec4<GLubyte> >& colors,
                       const mat4<GLfloat>& globalOffset,
					   const bool orthoMode,
					   const bool disableDepth){
	/// We need a perfect pair of point A's to point B's
	if(pointsA.size() != pointsB.size()) return;
	/// We need a color for each line, even if it is the same one
	if(pointsA.size() != colors.size()) return;

	IMPrimitive* priv = getOrCreateIMPrimitive();
	OffsetMatrix offset;
	std::copy(globalOffset.mat, globalOffset.mat+16, offset.mat);
	priv->_hasLines = true;
	priv->_lineWidth = 5.0f;
    if(!priv->hasRenderStates()){
		priv->setRenderStates(DELEGATE_BIND(&GL_API::setupLineState, this, offset, disableDepth ? _defaultStateNoDepth : GFX_DEVICE._defaultStateBlock,orthoMode),
			                  DELEGATE_BIND(&GL_API::releaseLineState, this, orthoMode));
    }
	priv->beginBatch();

    vec4<U8> color(255,0,0,255);
	priv->attribute4ub("inColorData", color);

    priv->begin(LINES);
	vec3<F32> vertA, vertB;
	for(GLushort i = 0; i < pointsA.size(); i++){
        color.set(colors[i].r, colors[i].g, colors[i].b,colors[i].a);
        vertA.set(pointsA[i].x,pointsA[i].y,pointsA[i].z);
        vertB.set(pointsB[i].x,pointsB[i].y,pointsB[i].z);
		priv->attribute4ub("inColorData", color);
		priv->vertex( vertA );
		priv->vertex( vertB );
	}

    priv->end();
	priv->endBatch();
}

void GL_API::drawText(const std::string& text, const I32 width, const std::string& fontName, const F32 fontSize){
    FTFont* font = getFont(fontName);
    if(!font) return;
	if(!FLOAT_COMPARE(_prevSizeNode,fontSize)){
		if (!font->FaceSize(fontSize)) {
			ERROR_FN(Locale::get("ERROR_FONT_HEIGHT"),fontSize);
		}
		_prevSizeNode = fontSize;
	}
    if(_prevWidthNode != width){
		GLCheck(glLineWidth(width));
		_prevWidthNode = width;
	}
    font->Render(text.c_str());
}

void GL_API::drawText(const std::string& text, const I32 width, const vec2<I32> position, const std::string& fontName, const F32 fontSize){
    FTFont* font = getFont(fontName);
    if(!font) return;

	if(!FLOAT_COMPARE(_prevSizeString,fontSize)){
		if (!font->FaceSize(fontSize)) {
			ERROR_FN(Locale::get("ERROR_FONT_HEIGHT"),fontSize);
		}
		_prevSizeString = fontSize;
	}

	if(_prevWidthString != width){
		GLCheck(glLineWidth(width));
		_prevWidthString = width;
	}

	F32 y = _cachedResolution.height - position.y;
	if(!FLOAT_COMPARE(_prevPointString->X(),position.x)){
		_prevPointString->X(position.x);
	}

	if(!FLOAT_COMPARE(_prevPointString->Y(), y)){
		_prevPointString->Y(y);
	}

    font->Render(text.c_str(),text.length(),*_prevPointString);
}

void GL_API::renderInstance(RenderInstance* const instance){
	Object3D* model = instance->object3D();
	assert(model != NULL);

	if(model->getType() ==	Object3D::OBJECT_3D_PLACEHOLDER){
		ERROR_FN(Locale::get("ERROR_GL_INVALID_OBJECT_TYPE"),model->getName().c_str());
		return;
	}

	Transform* transform = instance->transform();

	if(transform){
        Divide::GL::_setModelMatrix(transform->getGlobalMatrix(), transform->isUniformScaled());
    }

	if(model->getType() == Object3D::TEXT_3D){
        Text3D* text = dynamic_cast<Text3D*>(model);
		setActiveVAO(0);
		drawText(text->getText(),text->getWidth(),text->getFont(),text->getHeight());
		return;
	}

	VertexBufferObject* VBO = model->getGeometryVBO();

	//Send our transformation matrixes (projection, model view, inv model view, MVP, etc)
	VBO->currentShader()->uploadModelMatrices();
	//Render our current vertex array object
	VBO->Draw(model->getCurrentLOD());

	if(transform){
		Divide::GL::_resetModelMatrix();
	}
}

void GL_API::renderBuffer(VertexBufferObject* const vbo, Transform* const vboTransform){
    assert(vbo != NULL);

	if(vboTransform){
		 Divide::GL::_setModelMatrix(vboTransform->getGlobalMatrix(), vboTransform->isUniformScaled());
		 vbo->currentShader()->uploadModelMatrices();
	}

	//Render our current vertex array object
	vbo->DrawRange();

	if(vboTransform){
		Divide::GL::_resetModelMatrix();
	}
}

//Save the area designated by the rectangle "rect" to a TGA file
void GL_API::Screenshot(char *filename, const vec4<GLfloat>& rect){
	// compute width and heidth of the image
	GLushort w = rect.z - rect.x; //maxX - minX
	GLushort h = rect.w - rect.y; //maxY - minY

	// allocate memory for the pixels
	GLubyte *imageData = New GLubyte[w * h * 4];
	// read the pixels from the frame buffer
	GLCheck(glReadPixels(rect.x,rect.y,rect.z,rect.w,GL_RGBA,GL_UNSIGNED_BYTE, (GLvoid*)imageData));
	//save to file
	ImageTools::SaveSeries(filename,vec2<U16>(w,h),32,imageData);
}

Commits for Divide-Framework/trunk/Source Code/Hardware/Video/OpenGL/GLWrapper.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]]

157 Diff Diff k1ngp1n picture k1ngp1n Sat 06 Jul, 2013 00:07:09 +0000

[Ionut] [[BR]]
- Added per-scene ini config file for NavMesh creation [[BR]]
- Improved some IMEmulation cleanup code and fixed a memory leak with NavMesh debug rendering [[BR]]
- NavMesh debug rendering can now be toggled on/off in the Editor [[BR]]

156 Diff Diff k1ngp1n picture k1ngp1n Thu 04 Jul, 2013 21:50:54 +0000

[Ionut] [[BR]]
- More work on Navigation Mesh creation [[BR]]
- IMEmulation primitives were not recycled properly (old, unused primitives were saved, new ones were deleted and recreated – behavior reversed ) [[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]]

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

141 Diff Diff k1ngp1n picture k1ngp1n Wed 30 Jan, 2013 19:35:31 +0000

[Ionut] [[BR]]
-Updated to boost 1.52 and CEGUI 0.7.9 [[BR]]
-Updated to PhysX 3.2 [[BR]]
-Updated copyright notices [[BR]]

126 Diff Diff k1ngp1n picture k1ngp1n Sun 01 Jul, 2012 11:07:05 +0000

[Ionut] [[BR]]
-Renamed “CommunicationSensor” to “CommunicationInterface” [[BR]]
-More work on ReCast implementation [[BR]]
-Header and namespace cleanups [[BR]]

125 k1ngp1n picture k1ngp1n Thu 14 Jun, 2012 17:47:34 +0000

[Ionut] [[BR]]
-Added CEGUI (http://www.cegui.org.uk/wiki/index.php/Main_Page) to the framework (disabled for now, but working) [[BR]]
--All library dependencies now included in the LIBS folder along with copyright notices for every one of them [[BR]]