ifdef's for future py3 support, after this adding py3 can mostly be done with defines...
[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                 glMultMatrixd(oglmatrix);
272         }
273 }
274
275
276 void KX_BlenderRenderTools::RenderText2D(RAS_TEXT_RENDER_MODE mode,
277                                                                                  const char* text,
278                                                                                  int xco,
279                                                                                  int yco,                                                                        
280                                                                                  int width,
281                                                                                  int height)
282 {
283         STR_String tmpstr(text);
284
285         if(mode == RAS_IRenderTools::RAS_TEXT_PADDED)
286                 BL_print_gamedebug_line_padded(tmpstr.Ptr(), xco, yco, width, height);
287         else
288                 BL_print_gamedebug_line(tmpstr.Ptr(), xco, yco, width, height);
289 }
290
291 /* Render Text renders text into a (series of) polygon, using a texture font,
292  * Each character consists of one polygon (one quad or two triangles) */
293
294 void KX_BlenderRenderTools::RenderText(
295         int mode,
296         RAS_IPolyMaterial* polymat,
297         float v1[3], float v2[3], float v3[3], float v4[3], int glattrib)
298 {
299         STR_String mytext = ((CValue*)m_clientobject)->GetPropertyText("Text");
300         
301         const unsigned int flag = polymat->GetFlag();
302         struct MTFace* tface = 0;
303         unsigned int *col = 0;
304
305         if(flag & RAS_BLENDERMAT) {
306                 KX_BlenderMaterial *bl_mat = static_cast<KX_BlenderMaterial*>(polymat);
307                 tface = bl_mat->GetMTFace();
308                 col = bl_mat->GetMCol();
309         } else {
310                 KX_PolygonMaterial* blenderpoly = static_cast<KX_PolygonMaterial*>(polymat);
311                 tface = blenderpoly->GetMTFace();
312                 col = blenderpoly->GetMCol();
313         }
314         
315         GPU_render_text(tface, mode, mytext, mytext.Length(), col, v1, v2, v3, v4, glattrib);
316 }
317
318
319 void KX_BlenderRenderTools::PushMatrix()
320 {
321         glPushMatrix();
322 }
323
324 void KX_BlenderRenderTools::PopMatrix()
325 {
326         glPopMatrix();
327 }
328
329
330 int KX_BlenderRenderTools::applyLights(int objectlayer, const MT_Transform& viewmat)
331 {
332         // taken from blender source, incompatibility between Blender Object / GameObject       
333         KX_Scene* kxscene = (KX_Scene*)m_auxilaryClientInfo;
334         int scenelayer = ~0;
335         float glviewmat[16];
336         unsigned int count;
337         float vec[4];
338
339         vec[3]= 1.0;
340
341         if(kxscene && kxscene->GetBlenderScene())
342                 scenelayer = kxscene->GetBlenderScene()->lay;
343         
344         for(count=0; count<m_numgllights; count++)
345                 glDisable((GLenum)(GL_LIGHT0+count));
346         
347         //std::vector<struct    RAS_LightObject*> m_lights;
348         std::vector<struct      RAS_LightObject*>::iterator lit = m_lights.begin();
349
350         viewmat.getValue(glviewmat);
351         
352         glPushMatrix();
353         glLoadMatrixf(glviewmat);
354         for (lit = m_lights.begin(), count = 0; !(lit==m_lights.end()) && count < m_numgllights; ++lit)
355         {
356                 RAS_LightObject* lightdata = (*lit);
357                 KX_Scene* lightscene = (KX_Scene*)lightdata->m_scene;
358
359                 /* only use lights in the same layer as the object */
360                 if(!(lightdata->m_layer & objectlayer))
361                         continue;
362                 /* only use lights in the same scene, and in a visible layer */
363                 if(kxscene != lightscene || !(lightdata->m_layer & scenelayer))
364                         continue;
365
366                 vec[0] = (*(lightdata->m_worldmatrix))(0,3);
367                 vec[1] = (*(lightdata->m_worldmatrix))(1,3);
368                 vec[2] = (*(lightdata->m_worldmatrix))(2,3);
369                 vec[3] = 1;
370
371                 if(lightdata->m_type==RAS_LightObject::LIGHT_SUN) {
372                         
373                         vec[0] = (*(lightdata->m_worldmatrix))(0,2);
374                         vec[1] = (*(lightdata->m_worldmatrix))(1,2);
375                         vec[2] = (*(lightdata->m_worldmatrix))(2,2);
376                         //vec[0]= base->object->obmat[2][0];
377                         //vec[1]= base->object->obmat[2][1];
378                         //vec[2]= base->object->obmat[2][2];
379                         vec[3]= 0.0;
380                         glLightfv((GLenum)(GL_LIGHT0+count), GL_POSITION, vec); 
381                 }
382                 else {
383                         //vec[3]= 1.0;
384                         glLightfv((GLenum)(GL_LIGHT0+count), GL_POSITION, vec); 
385                         glLightf((GLenum)(GL_LIGHT0+count), GL_CONSTANT_ATTENUATION, 1.0);
386                         glLightf((GLenum)(GL_LIGHT0+count), GL_LINEAR_ATTENUATION, lightdata->m_att1/lightdata->m_distance);
387                         // without this next line it looks backward compatible.
388                         //attennuation still is acceptable 
389                         glLightf((GLenum)(GL_LIGHT0+count), GL_QUADRATIC_ATTENUATION, lightdata->m_att2/(lightdata->m_distance*lightdata->m_distance)); 
390                         
391                         if(lightdata->m_type==RAS_LightObject::LIGHT_SPOT) {
392                                 vec[0] = -(*(lightdata->m_worldmatrix))(0,2);
393                                 vec[1] = -(*(lightdata->m_worldmatrix))(1,2);
394                                 vec[2] = -(*(lightdata->m_worldmatrix))(2,2);
395                                 //vec[0]= -base->object->obmat[2][0];
396                                 //vec[1]= -base->object->obmat[2][1];
397                                 //vec[2]= -base->object->obmat[2][2];
398                                 glLightfv((GLenum)(GL_LIGHT0+count), GL_SPOT_DIRECTION, vec);
399                                 glLightf((GLenum)(GL_LIGHT0+count), GL_SPOT_CUTOFF, lightdata->m_spotsize/2.0);
400                                 glLightf((GLenum)(GL_LIGHT0+count), GL_SPOT_EXPONENT, 128.0*lightdata->m_spotblend);
401                         }
402                         else glLightf((GLenum)(GL_LIGHT0+count), GL_SPOT_CUTOFF, 180.0);
403                 }
404                 
405                 if (lightdata->m_nodiffuse)
406                 {
407                         vec[0] = vec[1] = vec[2] = vec[3] = 0.0;
408                 } else {
409                         vec[0]= lightdata->m_energy*lightdata->m_red;
410                         vec[1]= lightdata->m_energy*lightdata->m_green;
411                         vec[2]= lightdata->m_energy*lightdata->m_blue;
412                         vec[3]= 1.0;
413                 }
414                 glLightfv((GLenum)(GL_LIGHT0+count), GL_DIFFUSE, vec);
415                 if (lightdata->m_nospecular)
416                 {
417                         vec[0] = vec[1] = vec[2] = vec[3] = 0.0;
418                 } else if (lightdata->m_nodiffuse) {
419                         vec[0]= lightdata->m_energy*lightdata->m_red;
420                         vec[1]= lightdata->m_energy*lightdata->m_green;
421                         vec[2]= lightdata->m_energy*lightdata->m_blue;
422                         vec[3]= 1.0;
423                 }
424                 glLightfv((GLenum)(GL_LIGHT0+count), GL_SPECULAR, vec);
425                 glEnable((GLenum)(GL_LIGHT0+count));
426
427                 count++;
428         }
429         glPopMatrix();
430
431         return count;
432
433 }
434
435 void KX_BlenderRenderTools::MotionBlur(RAS_IRasterizer* rasterizer)
436 {
437         int state = rasterizer->GetMotionBlurState();
438         float motionblurvalue;
439         if(state)
440         {
441                 motionblurvalue = rasterizer->GetMotionBlurValue();
442                 if(state==1)
443                 {
444                         //bugfix:load color buffer into accum buffer for the first time(state=1)
445                         glAccum(GL_LOAD, 1.0);
446                         rasterizer->SetMotionBlurState(2);
447                 }
448                 else if(motionblurvalue>=0.0 && motionblurvalue<=1.0)
449                 {
450                         glAccum(GL_MULT, motionblurvalue);
451                         glAccum(GL_ACCUM, 1-motionblurvalue);
452                         glAccum(GL_RETURN, 1.0);
453                         glFlush();
454                 }
455         }
456 }
457
458 void KX_BlenderRenderTools::Update2DFilter(vector<STR_String>& propNames, void* gameObj, RAS_2DFilterManager::RAS_2DFILTER_MODE filtermode, int pass, STR_String& text)
459 {
460         m_filtermanager.EnableFilter(propNames, gameObj, filtermode, pass, text);
461 }
462
463 void KX_BlenderRenderTools::Render2DFilters(RAS_ICanvas* canvas)
464 {
465         m_filtermanager.RenderFilters(canvas);
466 }
467