Merge from 2.5 rev 20647 through 20776.
[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 "GL/glew.h"
30
31 #include "DNA_scene_types.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 #include "KX_GameObject.h"
40 #include "KX_PolygonMaterial.h"
41 #include "KX_BlenderMaterial.h"
42 #include "KX_RayCast.h"
43 #include "KX_IPhysicsController.h"
44
45 #include "PHY_IPhysicsEnvironment.h"
46
47 #include "STR_String.h"
48
49 #include "GPU_draw.h"
50
51 #include "KX_BlenderGL.h" // for text printing
52 #include "KX_BlenderRenderTools.h"
53
54 unsigned int KX_BlenderRenderTools::m_numgllights;
55
56 KX_BlenderRenderTools::KX_BlenderRenderTools()
57 {
58         glGetIntegerv(GL_MAX_LIGHTS, (GLint*) &m_numgllights);
59         if (m_numgllights < 8)
60                 m_numgllights = 8;
61 }
62
63 KX_BlenderRenderTools::~KX_BlenderRenderTools()
64 {
65 }
66
67 void KX_BlenderRenderTools::BeginFrame(RAS_IRasterizer* rasty)
68 {
69         m_clientobject = NULL;
70         m_lastlightlayer = -1;
71         m_lastauxinfo = NULL;
72         m_lastlighting = true; /* force disable in DisableOpenGLLights() */
73         DisableOpenGLLights();
74 }
75
76 void KX_BlenderRenderTools::EndFrame(RAS_IRasterizer* rasty)
77 {
78 }
79
80 /* ProcessLighting performs lighting on objects. the layer is a bitfield that
81  * contains layer information. There are 20 'official' layers in blender. A
82  * light is applied on an object only when they are in the same layer. OpenGL
83  * has a maximum of 8 lights (simultaneous), so 20 * 8 lights are possible in
84  * a scene. */
85
86 void KX_BlenderRenderTools::ProcessLighting(RAS_IRasterizer *rasty, bool uselights, const MT_Transform& viewmat)
87 {
88         bool enable = false;
89         int layer= -1;
90
91         /* find the layer */
92         if(uselights) {
93                 if(m_clientobject)
94                         layer = static_cast<KX_GameObject*>(m_clientobject)->GetLayer();
95         }
96
97         /* avoid state switching */
98         if(m_lastlightlayer == layer && m_lastauxinfo == m_auxilaryClientInfo)
99                 return;
100
101         m_lastlightlayer = layer;
102         m_lastauxinfo = m_auxilaryClientInfo;
103
104         /* enable/disable lights as needed */
105         if(layer >= 0)
106                 enable = applyLights(layer, viewmat);
107
108         if(enable)
109                 EnableOpenGLLights(rasty);
110         else
111                 DisableOpenGLLights();
112 }
113
114 void KX_BlenderRenderTools::EnableOpenGLLights(RAS_IRasterizer *rasty)
115 {
116         if(m_lastlighting == true)
117                 return;
118
119         glEnable(GL_LIGHTING);
120         glEnable(GL_COLOR_MATERIAL);
121
122         glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
123         glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
124         glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, (rasty->GetCameraOrtho())? GL_FALSE: GL_TRUE);
125         if (GLEW_EXT_separate_specular_color || GLEW_VERSION_1_2)
126                 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
127         
128         m_lastlighting = true;
129 }
130
131 void KX_BlenderRenderTools::DisableOpenGLLights()
132 {
133         if(m_lastlighting == false)
134                 return;
135
136         glDisable(GL_LIGHTING);
137         glDisable(GL_COLOR_MATERIAL);
138
139         m_lastlighting = false;
140 }
141
142
143 void KX_BlenderRenderTools::SetClientObject(RAS_IRasterizer *rasty, void* obj)
144 {
145         if (m_clientobject != obj)
146         {
147                 bool ccw = (obj == NULL || !((KX_GameObject*)obj)->IsNegativeScaling());
148                 rasty->SetFrontFace(ccw);
149
150                 m_clientobject = obj;
151         }
152 }
153
154 bool KX_BlenderRenderTools::RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data)
155 {
156         double* const oglmatrix = (double* const) data;
157         MT_Point3 resultpoint(result->m_hitPoint);
158         MT_Vector3 resultnormal(result->m_hitNormal);
159         MT_Vector3 left(oglmatrix[0],oglmatrix[1],oglmatrix[2]);
160         MT_Vector3 dir = -(left.cross(resultnormal)).safe_normalized();
161         left = (dir.cross(resultnormal)).safe_normalized();
162         // for the up vector, we take the 'resultnormal' returned by the physics
163         
164         double maat[16]={
165                         left[0],        left[1],        left[2], 0,
166                                 dir[0],         dir[1],         dir[2], 0,
167                 resultnormal[0],resultnormal[1],resultnormal[2], 0,
168                                 0,              0,              0, 1};
169         glTranslated(resultpoint[0],resultpoint[1],resultpoint[2]);
170         //glMultMatrixd(oglmatrix);
171         glMultMatrixd(maat);
172         return true;
173 }
174
175 void KX_BlenderRenderTools::applyTransform(RAS_IRasterizer* rasty,double* oglmatrix,int objectdrawmode )
176 {
177         /* FIXME:
178         blender: intern/moto/include/MT_Vector3.inl:42: MT_Vector3 operator/(const
179         MT_Vector3&, double): Assertion `!MT_fuzzyZero(s)' failed. 
180         
181         Program received signal SIGABRT, Aborted. 
182         [Switching to Thread 16384 (LWP 1519)] 
183         0x40477571 in kill () from /lib/libc.so.6 
184         (gdb) bt 
185         #7  0x08334368 in MT_Vector3::normalized() const () 
186         #8  0x0833e6ec in KX_BlenderRenderTools::applyTransform(RAS_IRasterizer*, double*, int) () 
187         */
188
189         if (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED ||
190                 objectdrawmode & RAS_IPolyMaterial::BILLBOARD_AXISALIGNED)
191         {
192                 // rotate the billboard/halo
193                 //page 360/361 3D Game Engine Design, David Eberly for a discussion
194                 // on screen aligned and axis aligned billboards
195                 // assumed is that the preprocessor transformed all billboard polygons
196                 // so that their normal points into the positive x direction (1.0 , 0.0 , 0.0)
197                 // when new parenting for objects is done, this rotation
198                 // will be moved into the object
199                 
200                 MT_Point3 objpos (oglmatrix[12],oglmatrix[13],oglmatrix[14]);
201                 MT_Point3 campos = rasty->GetCameraPosition();
202                 MT_Vector3 dir = (campos - objpos).safe_normalized();
203                 MT_Vector3 up(0,0,1.0);
204
205                 KX_GameObject* gameobj = (KX_GameObject*)m_clientobject;
206                 // get scaling of halo object
207                 MT_Vector3  size = gameobj->GetSGNode()->GetLocalScale();
208                 
209                 bool screenaligned = (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED)!=0;//false; //either screen or axisaligned
210                 if (screenaligned)
211                 {
212                         up = (up - up.dot(dir) * dir).safe_normalized();
213                 } else
214                 {
215                         dir = (dir - up.dot(dir)*up).safe_normalized();
216                 }
217
218                 MT_Vector3 left = dir.normalized();
219                 dir = (left.cross(up)).normalized();
220
221                 // we have calculated the row vectors, now we keep
222                 // local scaling into account:
223
224                 left *= size[0];
225                 dir  *= size[1];
226                 up   *= size[2];
227                 double maat[16]={
228                         left[0], left[1],left[2], 0,
229                                 dir[0], dir[1],dir[2],0,
230                                 up[0],up[1],up[2],0,
231                                 0,0,0,1};
232                         glTranslated(objpos[0],objpos[1],objpos[2]);
233                         glMultMatrixd(maat);
234                         
235         } else
236         {
237                 if (objectdrawmode & RAS_IPolyMaterial::SHADOW)
238                 {
239                         // shadow must be cast to the ground, physics system needed here!
240                         MT_Point3 frompoint(oglmatrix[12],oglmatrix[13],oglmatrix[14]);
241                         KX_GameObject *gameobj = (KX_GameObject*)m_clientobject;
242                         MT_Vector3 direction = MT_Vector3(0,0,-1);
243
244                         direction.normalize();
245                         direction *= 100000;
246
247                         MT_Point3 topoint = frompoint + direction;
248
249                         KX_Scene* kxscene = (KX_Scene*) m_auxilaryClientInfo;
250                         PHY_IPhysicsEnvironment* physics_environment = kxscene->GetPhysicsEnvironment();
251                         KX_IPhysicsController* physics_controller = gameobj->GetPhysicsController();
252                         
253                         KX_GameObject *parent = gameobj->GetParent();
254                         if (!physics_controller && parent)
255                                 physics_controller = parent->GetPhysicsController();
256                         if (parent)
257                                 parent->Release();
258                                 
259                         KX_RayCast::Callback<KX_BlenderRenderTools> callback(this, physics_controller, oglmatrix);
260                         if (!KX_RayCast::RayTest(physics_environment, frompoint, topoint, callback))
261                         {
262                                 // couldn't find something to cast the shadow on...
263                                 glMultMatrixd(oglmatrix);
264                         }
265                 } else
266                 {
267
268                         // 'normal' object
269                         glMultMatrixd(oglmatrix);
270                 }
271         }
272 }
273
274
275 void KX_BlenderRenderTools::RenderText2D(RAS_TEXT_RENDER_MODE mode,
276                                                                                  const char* text,
277                                                                                  int xco,
278                                                                                  int yco,                                                                        
279                                                                                  int width,
280                                                                                  int height)
281 {
282         STR_String tmpstr(text);
283
284         if(mode == RAS_IRenderTools::RAS_TEXT_PADDED)
285                 BL_print_gamedebug_line_padded(tmpstr.Ptr(), xco, yco, width, height);
286         else
287                 BL_print_gamedebug_line(tmpstr.Ptr(), xco, yco, width, height);
288 }
289
290 /* Render Text renders text into a (series of) polygon, using a texture font,
291  * Each character consists of one polygon (one quad or two triangles) */
292
293 void KX_BlenderRenderTools::RenderText(
294         int mode,
295         RAS_IPolyMaterial* polymat,
296         float v1[3], float v2[3], float v3[3], float v4[3], int glattrib)
297 {
298         const STR_String& mytext = ((CValue*)m_clientobject)->GetPropertyText("Text");
299         
300         const unsigned int flag = polymat->GetFlag();
301         struct MTFace* tface = 0;
302         unsigned int *col = 0;
303
304         if(flag & RAS_BLENDERMAT) {
305                 KX_BlenderMaterial *bl_mat = static_cast<KX_BlenderMaterial*>(polymat);
306                 tface = bl_mat->GetMTFace();
307                 col = bl_mat->GetMCol();
308         } else {
309                 KX_PolygonMaterial* blenderpoly = static_cast<KX_PolygonMaterial*>(polymat);
310                 tface = blenderpoly->GetMTFace();
311                 col = blenderpoly->GetMCol();
312         }
313         
314         GPU_render_text(tface, mode, mytext, mytext.Length(), col, v1, v2, v3, v4, glattrib);
315 }
316
317
318 void KX_BlenderRenderTools::PushMatrix()
319 {
320         glPushMatrix();
321 }
322
323 void KX_BlenderRenderTools::PopMatrix()
324 {
325         glPopMatrix();
326 }
327
328
329 int KX_BlenderRenderTools::applyLights(int objectlayer, const MT_Transform& viewmat)
330 {
331         // taken from blender source, incompatibility between Blender Object / GameObject       
332         KX_Scene* kxscene = (KX_Scene*)m_auxilaryClientInfo;
333         int scenelayer = ~0;
334         float glviewmat[16];
335         unsigned int count;
336         float vec[4];
337
338         vec[3]= 1.0;
339
340         if(kxscene && kxscene->GetBlenderScene())
341                 scenelayer = kxscene->GetBlenderScene()->lay;
342         
343         for(count=0; count<m_numgllights; count++)
344                 glDisable((GLenum)(GL_LIGHT0+count));
345         
346         //std::vector<struct    RAS_LightObject*> m_lights;
347         std::vector<struct      RAS_LightObject*>::iterator lit = m_lights.begin();
348
349         viewmat.getValue(glviewmat);
350         
351         glPushMatrix();
352         glLoadMatrixf(glviewmat);
353         for (lit = m_lights.begin(), count = 0; !(lit==m_lights.end()) && count < m_numgllights; ++lit)
354         {
355                 RAS_LightObject* lightdata = (*lit);
356                 KX_Scene* lightscene = (KX_Scene*)lightdata->m_scene;
357
358                 /* only use lights in the same layer as the object */
359                 if(!(lightdata->m_layer & objectlayer))
360                         continue;
361                 /* only use lights in the same scene, and in a visible layer */
362                 if(kxscene != lightscene || !(lightdata->m_layer & scenelayer))
363                         continue;
364
365                 vec[0] = (*(lightdata->m_worldmatrix))(0,3);
366                 vec[1] = (*(lightdata->m_worldmatrix))(1,3);
367                 vec[2] = (*(lightdata->m_worldmatrix))(2,3);
368                 vec[3] = 1;
369
370                 if(lightdata->m_type==RAS_LightObject::LIGHT_SUN) {
371                         
372                         vec[0] = (*(lightdata->m_worldmatrix))(0,2);
373                         vec[1] = (*(lightdata->m_worldmatrix))(1,2);
374                         vec[2] = (*(lightdata->m_worldmatrix))(2,2);
375                         //vec[0]= base->object->obmat[2][0];
376                         //vec[1]= base->object->obmat[2][1];
377                         //vec[2]= base->object->obmat[2][2];
378                         vec[3]= 0.0;
379                         glLightfv((GLenum)(GL_LIGHT0+count), GL_POSITION, vec); 
380                 }
381                 else {
382                         //vec[3]= 1.0;
383                         glLightfv((GLenum)(GL_LIGHT0+count), GL_POSITION, vec); 
384                         glLightf((GLenum)(GL_LIGHT0+count), GL_CONSTANT_ATTENUATION, 1.0);
385                         glLightf((GLenum)(GL_LIGHT0+count), GL_LINEAR_ATTENUATION, lightdata->m_att1/lightdata->m_distance);
386                         // without this next line it looks backward compatible.
387                         //attennuation still is acceptable 
388                         glLightf((GLenum)(GL_LIGHT0+count), GL_QUADRATIC_ATTENUATION, lightdata->m_att2/(lightdata->m_distance*lightdata->m_distance)); 
389                         
390                         if(lightdata->m_type==RAS_LightObject::LIGHT_SPOT) {
391                                 vec[0] = -(*(lightdata->m_worldmatrix))(0,2);
392                                 vec[1] = -(*(lightdata->m_worldmatrix))(1,2);
393                                 vec[2] = -(*(lightdata->m_worldmatrix))(2,2);
394                                 //vec[0]= -base->object->obmat[2][0];
395                                 //vec[1]= -base->object->obmat[2][1];
396                                 //vec[2]= -base->object->obmat[2][2];
397                                 glLightfv((GLenum)(GL_LIGHT0+count), GL_SPOT_DIRECTION, vec);
398                                 glLightf((GLenum)(GL_LIGHT0+count), GL_SPOT_CUTOFF, lightdata->m_spotsize/2.0);
399                                 glLightf((GLenum)(GL_LIGHT0+count), GL_SPOT_EXPONENT, 128.0*lightdata->m_spotblend);
400                         }
401                         else glLightf((GLenum)(GL_LIGHT0+count), GL_SPOT_CUTOFF, 180.0);
402                 }
403                 
404                 if (lightdata->m_nodiffuse)
405                 {
406                         vec[0] = vec[1] = vec[2] = vec[3] = 0.0;
407                 } else {
408                         vec[0]= lightdata->m_energy*lightdata->m_red;
409                         vec[1]= lightdata->m_energy*lightdata->m_green;
410                         vec[2]= lightdata->m_energy*lightdata->m_blue;
411                         vec[3]= 1.0;
412                 }
413                 glLightfv((GLenum)(GL_LIGHT0+count), GL_DIFFUSE, vec);
414                 if (lightdata->m_nospecular)
415                 {
416                         vec[0] = vec[1] = vec[2] = vec[3] = 0.0;
417                 } else if (lightdata->m_nodiffuse) {
418                         vec[0]= lightdata->m_energy*lightdata->m_red;
419                         vec[1]= lightdata->m_energy*lightdata->m_green;
420                         vec[2]= lightdata->m_energy*lightdata->m_blue;
421                         vec[3]= 1.0;
422                 }
423                 glLightfv((GLenum)(GL_LIGHT0+count), GL_SPECULAR, vec);
424                 glEnable((GLenum)(GL_LIGHT0+count));
425
426                 count++;
427         }
428         glPopMatrix();
429
430         return count;
431
432 }
433
434 void KX_BlenderRenderTools::MotionBlur(RAS_IRasterizer* rasterizer)
435 {
436         int state = rasterizer->GetMotionBlurState();
437         float motionblurvalue;
438         if(state)
439         {
440                 motionblurvalue = rasterizer->GetMotionBlurValue();
441                 if(state==1)
442                 {
443                         //bugfix:load color buffer into accum buffer for the first time(state=1)
444                         glAccum(GL_LOAD, 1.0);
445                         rasterizer->SetMotionBlurState(2);
446                 }
447                 else if(motionblurvalue>=0.0 && motionblurvalue<=1.0)
448                 {
449                         glAccum(GL_MULT, motionblurvalue);
450                         glAccum(GL_ACCUM, 1-motionblurvalue);
451                         glAccum(GL_RETURN, 1.0);
452                         glFlush();
453                 }
454         }
455 }
456
457 void KX_BlenderRenderTools::Update2DFilter(vector<STR_String>& propNames, void* gameObj, RAS_2DFilterManager::RAS_2DFILTER_MODE filtermode, int pass, STR_String& text)
458 {
459         m_filtermanager.EnableFilter(propNames, gameObj, filtermode, pass, text);
460 }
461
462 void KX_BlenderRenderTools::Render2DFilters(RAS_ICanvas* canvas)
463 {
464         m_filtermanager.RenderFilters(canvas);
465 }
466