revert r58693. patch [#36233], caused regression (bug report [#36959]).
[blender-staging.git] / source / gameengine / BlenderRoutines / KX_BlenderRenderTools.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file gameengine/BlenderRoutines/KX_BlenderRenderTools.cpp
29  *  \ingroup blroutines
30  */
31
32
33 #include "GL/glew.h"
34
35 #include "RAS_IRenderTools.h"
36 #include "RAS_IRasterizer.h"
37 #include "RAS_LightObject.h"
38 #include "RAS_ICanvas.h"
39 #include "RAS_GLExtensionManager.h"
40 #include "RAS_MeshObject.h"
41
42 #include "KX_GameObject.h"
43 #include "KX_PolygonMaterial.h"
44 #include "KX_BlenderMaterial.h"
45 #include "KX_RayCast.h"
46 #include "KX_IPhysicsController.h"
47 #include "KX_Light.h"
48
49 #include "PHY_IPhysicsEnvironment.h"
50
51 #include "STR_String.h"
52
53 #include "GPU_draw.h"
54
55 #include "KX_BlenderGL.h" // for text printing
56 #include "KX_BlenderRenderTools.h"
57
58 unsigned int KX_BlenderRenderTools::m_numgllights;
59
60 KX_BlenderRenderTools::KX_BlenderRenderTools()
61 {
62         glGetIntegerv(GL_MAX_LIGHTS, (GLint *) &m_numgllights);
63         if (m_numgllights < 8)
64                 m_numgllights = 8;
65 }
66
67 KX_BlenderRenderTools::~KX_BlenderRenderTools()
68 {
69 }
70
71 void KX_BlenderRenderTools::BeginFrame(RAS_IRasterizer* rasty)
72 {
73         m_clientobject = NULL;
74         m_lastlightlayer = -1;
75         m_lastauxinfo = NULL;
76         m_lastlighting = true; /* force disable in DisableOpenGLLights() */
77         DisableOpenGLLights();
78 }
79
80 void KX_BlenderRenderTools::EndFrame(RAS_IRasterizer* rasty)
81 {
82 }
83
84 /* ProcessLighting performs lighting on objects. the layer is a bitfield that
85  * contains layer information. There are 20 'official' layers in blender. A
86  * light is applied on an object only when they are in the same layer. OpenGL
87  * has a maximum of 8 lights (simultaneous), so 20 * 8 lights are possible in
88  * a scene. */
89
90 void KX_BlenderRenderTools::ProcessLighting(RAS_IRasterizer *rasty, bool uselights, const MT_Transform& viewmat)
91 {
92         bool enable = false;
93         int layer= -1;
94
95         /* find the layer */
96         if (uselights) {
97                 if (m_clientobject)
98                         layer = static_cast<KX_GameObject*>(m_clientobject)->GetLayer();
99         }
100
101         /* avoid state switching */
102         if (m_lastlightlayer == layer && m_lastauxinfo == m_auxilaryClientInfo)
103                 return;
104
105         m_lastlightlayer = layer;
106         m_lastauxinfo = m_auxilaryClientInfo;
107
108         /* enable/disable lights as needed */
109         if (layer >= 0)
110                 enable = applyLights(layer, viewmat);
111
112         if (enable)
113                 EnableOpenGLLights(rasty);
114         else
115                 DisableOpenGLLights();
116 }
117
118 void KX_BlenderRenderTools::EnableOpenGLLights(RAS_IRasterizer *rasty)
119 {
120         if (m_lastlighting == true)
121                 return;
122
123         glEnable(GL_LIGHTING);
124         glEnable(GL_COLOR_MATERIAL);
125
126         glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
127         glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
128         glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, (rasty->GetCameraOrtho())? GL_FALSE: GL_TRUE);
129         if (GLEW_EXT_separate_specular_color || GLEW_VERSION_1_2)
130                 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
131         
132         m_lastlighting = true;
133 }
134
135 void KX_BlenderRenderTools::DisableOpenGLLights()
136 {
137         if (m_lastlighting == false)
138                 return;
139
140         glDisable(GL_LIGHTING);
141         glDisable(GL_COLOR_MATERIAL);
142
143         m_lastlighting = false;
144 }
145
146
147 void KX_BlenderRenderTools::SetClientObject(RAS_IRasterizer *rasty, void* obj)
148 {
149         if (m_clientobject != obj)
150         {
151                 bool ccw = (obj == NULL || !((KX_GameObject*)obj)->IsNegativeScaling());
152                 rasty->SetFrontFace(ccw);
153
154                 m_clientobject = obj;
155         }
156 }
157
158 bool KX_BlenderRenderTools::RayHit(KX_ClientObjectInfo *client, KX_RayCast *result, void * const data)
159 {
160         double* const oglmatrix = (double* const) data;
161
162         RAS_Polygon* poly = result->m_hitMesh->GetPolygon(result->m_hitPolygon);
163         if (!poly->IsVisible())
164                 return false;
165
166         MT_Point3 resultpoint(result->m_hitPoint);
167         MT_Vector3 resultnormal(result->m_hitNormal);
168         MT_Vector3 left(oglmatrix[0],oglmatrix[1],oglmatrix[2]);
169         MT_Vector3 dir = -(left.cross(resultnormal)).safe_normalized();
170         left = (dir.cross(resultnormal)).safe_normalized();
171         // for the up vector, we take the 'resultnormal' returned by the physics
172         
173         double maat[16] = {left[0],         left[1],         left[2],         0,
174                            dir[0],          dir[1],          dir[2],          0,
175                            resultnormal[0], resultnormal[1], resultnormal[2], 0,
176                            0,               0,               0,               1};
177
178         glTranslated(resultpoint[0],resultpoint[1],resultpoint[2]);
179         //glMultMatrixd(oglmatrix);
180         glMultMatrixd(maat);
181         return true;
182 }
183
184 void KX_BlenderRenderTools::applyTransform(RAS_IRasterizer* rasty,double* oglmatrix,int objectdrawmode )
185 {
186         /* FIXME:
187         blender: intern/moto/include/MT_Vector3.inl:42: MT_Vector3 operator/(const
188         MT_Vector3&, double): Assertion `!MT_fuzzyZero(s)' failed. 
189         
190         Program received signal SIGABRT, Aborted. 
191         [Switching to Thread 16384 (LWP 1519)] 
192         0x40477571 in kill () from /lib/libc.so.6 
193         (gdb) bt 
194         #7  0x08334368 in MT_Vector3::normalized() const () 
195         #8  0x0833e6ec in KX_BlenderRenderTools::applyTransform(RAS_IRasterizer*, double*, int) () 
196         */
197
198         if (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED ||
199                 objectdrawmode & RAS_IPolyMaterial::BILLBOARD_AXISALIGNED)
200         {
201                 // rotate the billboard/halo
202                 //page 360/361 3D Game Engine Design, David Eberly for a discussion
203                 // on screen aligned and axis aligned billboards
204                 // assumed is that the preprocessor transformed all billboard polygons
205                 // so that their normal points into the positive x direction (1.0, 0.0, 0.0)
206                 // when new parenting for objects is done, this rotation
207                 // will be moved into the object
208                 
209                 MT_Point3 objpos (oglmatrix[12],oglmatrix[13],oglmatrix[14]);
210                 MT_Point3 campos = rasty->GetCameraPosition();
211                 MT_Vector3 dir = (campos - objpos).safe_normalized();
212                 MT_Vector3 up(0,0,1.0);
213
214                 KX_GameObject* gameobj = (KX_GameObject*)m_clientobject;
215                 // get scaling of halo object
216                 MT_Vector3  size = gameobj->GetSGNode()->GetWorldScaling();
217                 
218                 bool screenaligned = (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED)!=0;//false; //either screen or axisaligned
219                 if (screenaligned)
220                 {
221                         up = (up - up.dot(dir) * dir).safe_normalized();
222                 } else
223                 {
224                         dir = (dir - up.dot(dir)*up).safe_normalized();
225                 }
226
227                 MT_Vector3 left = dir.normalized();
228                 dir = (left.cross(up)).normalized();
229
230                 // we have calculated the row vectors, now we keep
231                 // local scaling into account:
232
233                 left *= size[0];
234                 dir  *= size[1];
235                 up   *= size[2];
236
237                 double maat[16] = {left[0], left[1], left[2], 0,
238                                    dir[0],  dir[1],  dir[2],  0,
239                                    up[0],   up[1],   up[2],   0,
240                                    0,       0,       0,       1};
241
242                 glTranslated(objpos[0],objpos[1],objpos[2]);
243                 glMultMatrixd(maat);
244
245         }
246         else {
247                 if (objectdrawmode & RAS_IPolyMaterial::SHADOW)
248                 {
249                         // shadow must be cast to the ground, physics system needed here!
250                         MT_Point3 frompoint(oglmatrix[12],oglmatrix[13],oglmatrix[14]);
251                         KX_GameObject *gameobj = (KX_GameObject*)m_clientobject;
252                         MT_Vector3 direction = MT_Vector3(0,0,-1);
253
254                         direction.normalize();
255                         direction *= 100000;
256
257                         MT_Point3 topoint = frompoint + direction;
258
259                         KX_Scene* kxscene = (KX_Scene*) m_auxilaryClientInfo;
260                         PHY_IPhysicsEnvironment* physics_environment = kxscene->GetPhysicsEnvironment();
261                         KX_IPhysicsController* physics_controller = gameobj->GetPhysicsController();
262                         
263                         KX_GameObject *parent = gameobj->GetParent();
264                         if (!physics_controller && parent)
265                                 physics_controller = parent->GetPhysicsController();
266                         if (parent)
267                                 parent->Release();
268                                 
269                         KX_RayCast::Callback<KX_BlenderRenderTools> callback(this, physics_controller, oglmatrix);
270                         if (!KX_RayCast::RayTest(physics_environment, frompoint, topoint, callback))
271                         {
272                                 // couldn't find something to cast the shadow on...
273                                 glMultMatrixd(oglmatrix);
274                         }
275                         else
276                         { // we found the "ground", but the cast matrix doesn't take
277                           // scaling in consideration, so we must apply the object scale
278                                 MT_Vector3  size = gameobj->GetSGNode()->GetLocalScale();
279                                 glScalef(size[0], size[1], size[2]);
280                         }
281                 } else
282                 {
283
284                         // 'normal' object
285                         glMultMatrixd(oglmatrix);
286                 }
287         }
288 }
289
290 void KX_BlenderRenderTools::RenderBox2D(int xco,
291                         int yco,
292                         int width,
293                         int height,
294                         float percentage)
295 {
296         BL_draw_gamedebug_box(xco, yco, width, height, percentage);
297 }
298
299 void KX_BlenderRenderTools::RenderText3D(int fontid,
300                                                                                  const char* text,
301                                                                                  int size,
302                                                                                  int dpi,
303                                                                                  float* color,
304                                                                                  double* mat,
305                                                                                  float aspect)
306 {
307         BL_print_game_line(fontid, text, size, dpi, color, mat, aspect);
308 }
309
310 void KX_BlenderRenderTools::RenderText2D(RAS_TEXT_RENDER_MODE mode,
311                                                                                  const char* text,
312                                                                                  int xco,
313                                                                                  int yco,                                                                        
314                                                                                  int width,
315                                                                                  int height)
316 {
317         if (mode == RAS_IRenderTools::RAS_TEXT_PADDED)
318                 BL_print_gamedebug_line_padded(text, xco, yco, width, height);
319         else
320                 BL_print_gamedebug_line(text, xco, yco, width, height);
321 }
322
323 /* Render Text renders text into a (series of) polygon, using a texture font,
324  * Each character consists of one polygon (one quad or two triangles) */
325
326 void KX_BlenderRenderTools::RenderText(
327         int mode,
328         RAS_IPolyMaterial* polymat,
329         float v1[3], float v2[3], float v3[3], float v4[3], int glattrib)
330 {
331         const STR_String& mytext = ((CValue*)m_clientobject)->GetPropertyText("Text");
332         
333         const unsigned int flag = polymat->GetFlag();
334         struct MTFace* tface = 0;
335         unsigned int *col = 0;
336
337         if (flag & RAS_BLENDERMAT) {
338                 KX_BlenderMaterial *bl_mat = static_cast<KX_BlenderMaterial*>(polymat);
339                 tface = bl_mat->GetMTFace();
340                 col = bl_mat->GetMCol();
341         } else {
342                 KX_PolygonMaterial* blenderpoly = static_cast<KX_PolygonMaterial*>(polymat);
343                 tface = blenderpoly->GetMTFace();
344                 col = blenderpoly->GetMCol();
345         }
346         
347         GPU_render_text(tface, mode, mytext, mytext.Length(), col, v1, v2, v3, v4, glattrib);
348 }
349
350
351 void KX_BlenderRenderTools::PushMatrix()
352 {
353         glPushMatrix();
354 }
355
356 void KX_BlenderRenderTools::PopMatrix()
357 {
358         glPopMatrix();
359 }
360
361
362 int KX_BlenderRenderTools::applyLights(int objectlayer, const MT_Transform& viewmat)
363 {
364         // taken from blender source, incompatibility between Blender Object / GameObject
365         KX_Scene* kxscene = (KX_Scene*)m_auxilaryClientInfo;
366         float glviewmat[16];
367         unsigned int count;
368         std::vector<struct      RAS_LightObject*>::iterator lit = m_lights.begin();
369
370         for (count=0; count<m_numgllights; count++)
371                 glDisable((GLenum)(GL_LIGHT0+count));
372
373         viewmat.getValue(glviewmat);
374         
375         glPushMatrix();
376         glLoadMatrixf(glviewmat);
377         for (lit = m_lights.begin(), count = 0; !(lit==m_lights.end()) && count < m_numgllights; ++lit)
378         {
379                 RAS_LightObject* lightdata = (*lit);
380                 KX_LightObject *kxlight = (KX_LightObject*)lightdata->m_light;
381
382                 if (kxlight->ApplyLight(kxscene, objectlayer, count))
383                         count++;
384         }
385         glPopMatrix();
386
387         return count;
388 }
389
390 void KX_BlenderRenderTools::MotionBlur(RAS_IRasterizer* rasterizer)
391 {
392         int state = rasterizer->GetMotionBlurState();
393         float motionblurvalue;
394         if (state)
395         {
396                 motionblurvalue = rasterizer->GetMotionBlurValue();
397                 if (state==1)
398                 {
399                         //bugfix:load color buffer into accum buffer for the first time(state=1)
400                         glAccum(GL_LOAD, 1.0);
401                         rasterizer->SetMotionBlurState(2);
402                 }
403                 else if (motionblurvalue >= 0.0f && motionblurvalue <= 1.0f) {
404                         glAccum(GL_MULT, motionblurvalue);
405                         glAccum(GL_ACCUM, 1-motionblurvalue);
406                         glAccum(GL_RETURN, 1.0);
407                         glFlush();
408                 }
409         }
410 }
411