Merge from trunk 16122-16307
[blender.git] / source / gameengine / BlenderRoutines / KX_BlenderRenderTools.cpp
1 /**
2  * $Id$
3  * ***** BEGIN GPL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18  *
19  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
20  * All rights reserved.
21  *
22  * The Original Code is: all of this file.
23  *
24  * Contributor(s): none yet.
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 #include "KX_BlenderRenderTools.h"
30
31 #include "GL/glew.h"
32
33 #include "RAS_IRenderTools.h"
34 #include "RAS_IRasterizer.h"
35 #include "RAS_LightObject.h"
36 #include "RAS_ICanvas.h"
37 #include "RAS_GLExtensionManager.h"
38
39 // next two includes/dependencies come from the shadow feature
40 // it needs the gameobject and the sumo physics scene for a raycast
41 #include "KX_GameObject.h"
42
43 #include "KX_PolygonMaterial.h"
44 #include "KX_BlenderMaterial.h"
45
46 #include "Value.h"
47
48 #include "KX_BlenderGL.h" // for text printing
49 #include "STR_String.h"
50 #include "RAS_BucketManager.h" // for polymaterial (needed for textprinting)
51
52 #include "KX_RayCast.h"
53 #include "KX_IPhysicsController.h"
54 #include "PHY_IPhysicsEnvironment.h"
55 #include "KX_Scene.h"
56
57 KX_BlenderRenderTools::KX_BlenderRenderTools()
58 {
59         glGetIntegerv(GL_MAX_LIGHTS, (GLint*) &m_numgllights);
60         if (m_numgllights < 8)
61                 m_numgllights = 8;
62 }
63
64 /**
65 ProcessLighting performs lighting on objects. the layer is a bitfield that contains layer information.
66 There are 20 'official' layers in blender.
67 A light is applied on an object only when they are in the same layer.
68 OpenGL has a maximum of 8 lights (simultaneous), so 20 * 8 lights are possible in a scene.
69 */
70
71 int     KX_BlenderRenderTools::ProcessLighting(int layer) 
72 {
73         
74         int result = false;
75
76         if (layer < 0)
77         {
78                 DisableOpenGLLights();
79                 result = false;
80         } else
81         {
82                 if (m_clientobject)
83                 {
84                         if (layer == RAS_LIGHT_OBJECT_LAYER)
85                         {
86                                 layer = static_cast<KX_GameObject*>(m_clientobject)->GetLayer();
87                         }
88                         if (applyLights(layer))
89                         {
90                                 EnableOpenGLLights();
91                                 result = true;
92                         } else
93                         {
94                                 DisableOpenGLLights();
95                                 result = false;
96                         }                       
97                 }
98         }
99         return result;
100         
101         
102 }
103
104
105 void KX_BlenderRenderTools::BeginFrame(RAS_IRasterizer* rasty)
106 {
107         m_clientobject = NULL;
108         m_lastblenderobject = NULL;
109         m_lastblenderlights = false;
110         m_lastlayer = -1;
111         m_lastlighting = false;
112         m_modified = true;
113         DisableOpenGLLights();
114
115
116 }
117
118 void KX_BlenderRenderTools::SetClientObject(void* obj)
119 {
120         if (m_clientobject != obj)
121         {
122                 if (obj == NULL || !((KX_GameObject*)obj)->IsNegativeScaling())
123                 {
124                         glFrontFace(GL_CCW);
125                 } else 
126                 {
127                         glFrontFace(GL_CW);
128                 }
129                 m_clientobject = obj;
130                 m_modified = true;
131         }
132 }
133
134 bool KX_BlenderRenderTools::RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data)
135 {
136         double* const oglmatrix = (double* const) data;
137         MT_Point3 resultpoint(result->m_hitPoint);
138         MT_Vector3 resultnormal(result->m_hitNormal);
139         MT_Vector3 left(oglmatrix[0],oglmatrix[1],oglmatrix[2]);
140         MT_Vector3 dir = -(left.cross(resultnormal)).safe_normalized();
141         left = (dir.cross(resultnormal)).safe_normalized();
142         // for the up vector, we take the 'resultnormal' returned by the physics
143         
144         double maat[16]={
145                         left[0],        left[1],        left[2], 0,
146                                 dir[0],         dir[1],         dir[2], 0,
147                 resultnormal[0],resultnormal[1],resultnormal[2], 0,
148                                 0,              0,              0, 1};
149         glTranslated(resultpoint[0],resultpoint[1],resultpoint[2]);
150         //glMultMatrixd(oglmatrix);
151         glMultMatrixd(maat);
152         return true;
153 }
154
155 void KX_BlenderRenderTools::applyTransform(RAS_IRasterizer* rasty,double* oglmatrix,int objectdrawmode )
156 {
157         /* FIXME:
158         blender: intern/moto/include/MT_Vector3.inl:42: MT_Vector3 operator/(const
159         MT_Vector3&, double): Assertion `!MT_fuzzyZero(s)' failed. 
160         
161         Program received signal SIGABRT, Aborted. 
162         [Switching to Thread 16384 (LWP 1519)] 
163         0x40477571 in kill () from /lib/libc.so.6 
164         (gdb) bt 
165         #7  0x08334368 in MT_Vector3::normalized() const () 
166         #8  0x0833e6ec in KX_BlenderRenderTools::applyTransform(RAS_IRasterizer*, double*, int) () 
167         */
168
169         if (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED ||
170                 objectdrawmode & RAS_IPolyMaterial::BILLBOARD_AXISALIGNED)
171         {
172                 // rotate the billboard/halo
173                 //page 360/361 3D Game Engine Design, David Eberly for a discussion
174                 // on screen aligned and axis aligned billboards
175                 // assumed is that the preprocessor transformed all billboard polygons
176                 // so that their normal points into the positive x direction (1.0 , 0.0 , 0.0)
177                 // when new parenting for objects is done, this rotation
178                 // will be moved into the object
179                 
180                 MT_Point3 objpos (oglmatrix[12],oglmatrix[13],oglmatrix[14]);
181                 MT_Point3 campos = rasty->GetCameraPosition();
182                 MT_Vector3 dir = (campos - objpos).safe_normalized();
183                 MT_Vector3 up(0,0,1.0);
184
185                 KX_GameObject* gameobj = (KX_GameObject*) this->m_clientobject;
186                 // get scaling of halo object
187                 MT_Vector3  size = gameobj->GetSGNode()->GetLocalScale();
188                 
189                 bool screenaligned = (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED)!=0;//false; //either screen or axisaligned
190                 if (screenaligned)
191                 {
192                         up = (up - up.dot(dir) * dir).safe_normalized();
193                 } else
194                 {
195                         dir = (dir - up.dot(dir)*up).safe_normalized();
196                 }
197
198                 MT_Vector3 left = dir.normalized();
199                 dir = (left.cross(up)).normalized();
200
201                 // we have calculated the row vectors, now we keep
202                 // local scaling into account:
203
204                 left *= size[0];
205                 dir  *= size[1];
206                 up   *= size[2];
207                 double maat[16]={
208                         left[0], left[1],left[2], 0,
209                                 dir[0], dir[1],dir[2],0,
210                                 up[0],up[1],up[2],0,
211                                 0,0,0,1};
212                         glTranslated(objpos[0],objpos[1],objpos[2]);
213                         glMultMatrixd(maat);
214                         
215         } else
216         {
217                 if (objectdrawmode & RAS_IPolyMaterial::SHADOW)
218                 {
219                         // shadow must be cast to the ground, physics system needed here!
220                         MT_Point3 frompoint(oglmatrix[12],oglmatrix[13],oglmatrix[14]);
221                         KX_GameObject *gameobj = (KX_GameObject*) this->m_clientobject;
222                         MT_Vector3 direction = MT_Vector3(0,0,-1);
223
224                         direction.normalize();
225                         direction *= 100000;
226
227                         MT_Point3 topoint = frompoint + direction;
228
229                         KX_Scene* kxscene = (KX_Scene*) m_auxilaryClientInfo;
230                         PHY_IPhysicsEnvironment* physics_environment = kxscene->GetPhysicsEnvironment();
231                         KX_IPhysicsController* physics_controller = gameobj->GetPhysicsController();
232                         
233                         KX_GameObject *parent = gameobj->GetParent();
234                         if (!physics_controller && parent)
235                                 physics_controller = parent->GetPhysicsController();
236                         if (parent)
237                                 parent->Release();
238                                 
239                         KX_RayCast::Callback<KX_BlenderRenderTools> callback(this, physics_controller, oglmatrix);
240                         if (!KX_RayCast::RayTest(physics_environment, frompoint, topoint, callback))
241                         {
242                                 // couldn't find something to cast the shadow on...
243                                 glMultMatrixd(oglmatrix);
244                         }
245                 } else
246                 {
247
248                         // 'normal' object
249                         glMultMatrixd(oglmatrix);
250                 }
251         }
252 }
253
254
255 /**
256 Render Text renders text into a (series of) polygon, using a texture font,
257 Each character consists of one polygon (one quad or two triangles)
258 */
259 void    KX_BlenderRenderTools::RenderText(int mode,RAS_IPolyMaterial* polymat,float v1[3],float v2[3],float v3[3],float v4[3])
260 {
261                 
262         STR_String mytext = ((CValue*)m_clientobject)->GetPropertyText("Text");
263         
264         const unsigned int flag = polymat->GetFlag();
265         struct MTFace* tface = 0;
266         unsigned int *col = 0;
267
268         if(flag & RAS_BLENDERMAT) {
269                 KX_BlenderMaterial *bl_mat = static_cast<KX_BlenderMaterial*>(polymat);
270                 tface = bl_mat->GetMTFace();
271                 col = bl_mat->GetMCol();
272         } else {
273                 KX_PolygonMaterial* blenderpoly = static_cast<KX_PolygonMaterial*>(polymat);
274                 tface = blenderpoly->GetMTFace();
275                 col = blenderpoly->GetMCol();
276         }
277         
278         BL_RenderText( mode,mytext,mytext.Length(),tface,col,v1,v2,v3,v4);
279         
280 }
281
282
283
284 KX_BlenderRenderTools::~KX_BlenderRenderTools()
285 {
286 };
287         
288         
289 void    KX_BlenderRenderTools::EndFrame(RAS_IRasterizer* rasty)
290 {
291 }
292         
293
294         
295 void KX_BlenderRenderTools::DisableOpenGLLights()
296 {
297         glDisable(GL_LIGHTING);
298         glDisable(GL_COLOR_MATERIAL);
299 }
300
301         
302 void KX_BlenderRenderTools::EnableOpenGLLights()
303 {
304         glEnable(GL_LIGHTING);
305         
306         glEnable(GL_COLOR_MATERIAL);
307         glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
308         glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, true);
309         if (GLEW_EXT_separate_specular_color || GLEW_VERSION_1_2)
310                 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
311
312 }
313         
314
315 /**
316  * Rendering text using 2D bitmap functionality.  
317  */
318 void KX_BlenderRenderTools::RenderText2D(RAS_TEXT_RENDER_MODE mode,
319                                                                                  const char* text,
320                                                                                  int xco,
321                                                                                  int yco,                                                                        
322                                                                                  int width,
323                                                                                  int height)
324 {
325         switch (mode) {
326         case RAS_IRenderTools::RAS_TEXT_PADDED: {
327                 STR_String tmpstr(text);
328                 BL_print_gamedebug_line_padded(tmpstr.Ptr(),xco,yco,width,height);
329                 break;
330         }
331         default: {
332                 STR_String tmpstr(text);
333                 BL_print_gamedebug_line(tmpstr.Ptr(),xco,yco,width,height);
334         }
335         }
336 }
337
338         
339
340 void KX_BlenderRenderTools::PushMatrix()
341 {
342         glPushMatrix();
343 }
344
345 void KX_BlenderRenderTools::PopMatrix()
346 {
347         glPopMatrix();
348 }
349
350
351
352 int     KX_BlenderRenderTools::applyLights(int objectlayer)
353 {
354 // taken from blender source, incompatibility between Blender Object / GameObject       
355         
356         unsigned int count;
357         float vec[4];
358                 
359         vec[3]= 1.0;
360         
361         for(count=0; count<m_numgllights; count++)
362                 glDisable((GLenum)(GL_LIGHT0+count));
363         
364         //std::vector<struct    RAS_LightObject*> m_lights;
365         std::vector<struct      RAS_LightObject*>::iterator lit = m_lights.begin();
366         
367         glPushMatrix();
368         glLoadMatrixf(m_viewmat);
369         for (lit = m_lights.begin(), count = 0; !(lit==m_lights.end()) && count < m_numgllights; ++lit)
370         {
371                 RAS_LightObject* lightdata = (*lit);
372                 if (lightdata->m_layer & objectlayer)
373                 {
374                         vec[0] = (*(lightdata->m_worldmatrix))(0,3);
375                         vec[1] = (*(lightdata->m_worldmatrix))(1,3);
376                         vec[2] = (*(lightdata->m_worldmatrix))(2,3);
377                         vec[3] = 1;
378
379                         if(lightdata->m_type==RAS_LightObject::LIGHT_SUN) {
380                                 
381                                 vec[0] = (*(lightdata->m_worldmatrix))(0,2);
382                                 vec[1] = (*(lightdata->m_worldmatrix))(1,2);
383                                 vec[2] = (*(lightdata->m_worldmatrix))(2,2);
384                                 //vec[0]= base->object->obmat[2][0];
385                                 //vec[1]= base->object->obmat[2][1];
386                                 //vec[2]= base->object->obmat[2][2];
387                                 vec[3]= 0.0;
388                                 glLightfv((GLenum)(GL_LIGHT0+count), GL_POSITION, vec); 
389                         }
390                         else {
391                                 //vec[3]= 1.0;
392                                 glLightfv((GLenum)(GL_LIGHT0+count), GL_POSITION, vec); 
393                                 glLightf((GLenum)(GL_LIGHT0+count), GL_CONSTANT_ATTENUATION, 1.0);
394                                 glLightf((GLenum)(GL_LIGHT0+count), GL_LINEAR_ATTENUATION, lightdata->m_att1/lightdata->m_distance);
395                                 // without this next line it looks backward compatible.
396                                 //attennuation still is acceptable 
397                                 glLightf((GLenum)(GL_LIGHT0+count), GL_QUADRATIC_ATTENUATION, lightdata->m_att2/(lightdata->m_distance*lightdata->m_distance)); 
398                                 
399                                 if(lightdata->m_type==RAS_LightObject::LIGHT_SPOT) {
400                                         vec[0] = -(*(lightdata->m_worldmatrix))(0,2);
401                                         vec[1] = -(*(lightdata->m_worldmatrix))(1,2);
402                                         vec[2] = -(*(lightdata->m_worldmatrix))(2,2);
403                                         //vec[0]= -base->object->obmat[2][0];
404                                         //vec[1]= -base->object->obmat[2][1];
405                                         //vec[2]= -base->object->obmat[2][2];
406                                         glLightfv((GLenum)(GL_LIGHT0+count), GL_SPOT_DIRECTION, vec);
407                                         glLightf((GLenum)(GL_LIGHT0+count), GL_SPOT_CUTOFF, lightdata->m_spotsize/2.0);
408                                         glLightf((GLenum)(GL_LIGHT0+count), GL_SPOT_EXPONENT, 128.0*lightdata->m_spotblend);
409                                 }
410                                 else glLightf((GLenum)(GL_LIGHT0+count), GL_SPOT_CUTOFF, 180.0);
411                         }
412                         
413                         if (lightdata->m_nodiffuse)
414                         {
415                                 vec[0] = vec[1] = vec[2] = vec[3] = 0.0;
416                         } else {
417                                 vec[0]= lightdata->m_energy*lightdata->m_red;
418                                 vec[1]= lightdata->m_energy*lightdata->m_green;
419                                 vec[2]= lightdata->m_energy*lightdata->m_blue;
420                                 vec[3]= 1.0;
421                         }
422                         glLightfv((GLenum)(GL_LIGHT0+count), GL_DIFFUSE, vec);
423                         if (lightdata->m_nospecular)
424                         {
425                                 vec[0] = vec[1] = vec[2] = vec[3] = 0.0;
426                         } else if (lightdata->m_nodiffuse) {
427                                 vec[0]= lightdata->m_energy*lightdata->m_red;
428                                 vec[1]= lightdata->m_energy*lightdata->m_green;
429                                 vec[2]= lightdata->m_energy*lightdata->m_blue;
430                                 vec[3]= 1.0;
431                         }
432                         glLightfv((GLenum)(GL_LIGHT0+count), GL_SPECULAR, vec);
433                         glEnable((GLenum)(GL_LIGHT0+count));
434
435                         count++;
436                         
437                 }
438         }
439         glPopMatrix();
440
441         return count;
442
443 }
444
445
446
447 RAS_IPolyMaterial* KX_BlenderRenderTools::CreateBlenderPolyMaterial(
448                 const STR_String &texname,
449                 bool ba,const STR_String& matname,int tile,int tilexrep,int tileyrep,int mode,bool transparant,bool zsort, int lightlayer
450                 ,bool bIsTriangle,void* clientobject,void* tface)
451 {
452         assert(!"Deprecated");
453 /*      return new KX_BlenderPolyMaterial(
454
455                 texname,
456                 ba,matname,tile,tilexrep,tileyrep,mode,transparant,zsort, lightlayer
457                 ,bIsTriangle,clientobject,(struct MTFace*)tface);*/
458         return NULL;
459 }
460
461 void KX_BlenderRenderTools::MotionBlur(RAS_IRasterizer* rasterizer)
462 {
463         int state = rasterizer->GetMotionBlurState();
464         float motionblurvalue;
465         if(state)
466         {
467                 motionblurvalue = rasterizer->GetMotionBlurValue();
468                 if(state==1)
469                 {
470                         //bugfix:load color buffer into accum buffer for the first time(state=1)
471                         glAccum(GL_LOAD, 1.0);
472                         rasterizer->SetMotionBlurState(2);
473                 }
474                 else if(motionblurvalue>=0.0 && motionblurvalue<=1.0)
475                 {
476                         glAccum(GL_MULT, motionblurvalue);
477                         glAccum(GL_ACCUM, 1-motionblurvalue);
478                         glAccum(GL_RETURN, 1.0);
479                         glFlush();
480                 }
481         }
482 }
483
484 void KX_BlenderRenderTools::Update2DFilter(vector<STR_String>& propNames, void* gameObj, RAS_2DFilterManager::RAS_2DFILTER_MODE filtermode, int pass, STR_String& text)
485 {
486         m_filtermanager.EnableFilter(propNames, gameObj, filtermode, pass, text);
487 }
488
489 void KX_BlenderRenderTools::Render2DFilters(RAS_ICanvas* canvas)
490 {
491         m_filtermanager.RenderFilters(canvas);
492 }
493
494 unsigned int KX_BlenderRenderTools::m_numgllights;