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