OpenGL: stipple support added to basic GLSL shader
[blender.git] / source / gameengine / Rasterizer / RAS_OpenGLRasterizer / RAS_OpenGLRasterizer.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/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp
29  *  \ingroup bgerastogl
30  */
31
32  
33 #include <math.h>
34 #include <stdlib.h>
35  
36 #include "RAS_OpenGLRasterizer.h"
37
38 #include "glew-mx.h"
39
40 #include "RAS_ICanvas.h"
41 #include "RAS_Rect.h"
42 #include "RAS_TexVert.h"
43 #include "RAS_MeshObject.h"
44 #include "RAS_Polygon.h"
45 #include "RAS_ILightObject.h"
46 #include "MT_CmMatrix4x4.h"
47
48 #include "RAS_OpenGLLight.h"
49
50 #include "RAS_StorageVA.h"
51 #include "RAS_StorageVBO.h"
52
53 #include "GPU_draw.h"
54 #include "GPU_extensions.h"
55 #include "GPU_material.h"
56 #include "GPU_shader.h"
57
58 extern "C"{
59         #include "BLF_api.h"
60         #include "BKE_DerivedMesh.h"
61 }
62
63
64 // XXX Clean these up <<<
65 #include "EXP_Value.h"
66 #include "KX_Scene.h"
67 #include "KX_RayCast.h"
68 #include "KX_GameObject.h"
69 // >>>
70
71 #ifndef M_PI
72 #define M_PI            3.14159265358979323846
73 #endif
74
75 /**
76  *  32x32 bit masks for vinterlace stereo mode
77  */
78 static GLuint left_eye_vinterlace_mask[32];
79 static GLuint right_eye_vinterlace_mask[32];
80
81 /**
82  *  32x32 bit masks for hinterlace stereo mode.
83  *  Left eye = &hinterlace_mask[0]
84  *  Right eye = &hinterlace_mask[1]
85  */
86 static GLuint hinterlace_mask[33];
87
88 RAS_OpenGLRasterizer::RAS_OpenGLRasterizer(RAS_ICanvas* canvas, RAS_STORAGE_TYPE storage)
89         :RAS_IRasterizer(canvas),
90         m_2DCanvas(canvas),
91         m_fogenabled(false),
92         m_time(0.0f),
93         m_campos(0.0f, 0.0f, 0.0f),
94         m_camortho(false),
95         m_stereomode(RAS_STEREO_NOSTEREO),
96         m_curreye(RAS_STEREO_LEFTEYE),
97         m_eyeseparation(0.0f),
98         m_focallength(0.0f),
99         m_setfocallength(false),
100         m_noOfScanlines(32),
101         m_motionblur(0),
102         m_motionblurvalue(-1.0f),
103         m_usingoverrideshader(false),
104         m_clientobject(NULL),
105         m_auxilaryClientInfo(NULL),
106         m_drawingmode(KX_TEXTURED),
107         m_texco_num(0),
108         m_attrib_num(0),
109         //m_last_alphablend(GPU_BLEND_SOLID),
110         m_last_frontface(true),
111         m_materialCachingInfo(0),
112         m_storage_type(storage)
113 {
114         m_viewmatrix.setIdentity();
115         m_viewinvmatrix.setIdentity();
116         
117         for (int i = 0; i < 32; i++)
118         {
119                 left_eye_vinterlace_mask[i] = 0x55555555;
120                 right_eye_vinterlace_mask[i] = 0xAAAAAAAA;
121                 hinterlace_mask[i] = (i&1)*0xFFFFFFFF;
122         }
123         hinterlace_mask[32] = 0;
124
125         m_prevafvalue = GPU_get_anisotropic();
126
127         if (m_storage_type == RAS_VBO /*|| m_storage_type == RAS_AUTO_STORAGE && GLEW_ARB_vertex_buffer_object*/) {
128                 m_storage = new RAS_StorageVBO(&m_texco_num, m_texco, &m_attrib_num, m_attrib, m_attrib_layer);
129         }
130         else if ((m_storage_type == RAS_VA) || (m_storage_type == RAS_AUTO_STORAGE)) {
131                 m_storage = new RAS_StorageVA(&m_texco_num, m_texco, &m_attrib_num, m_attrib, m_attrib_layer);
132         }
133         else {
134                 printf("Unknown rasterizer storage type, falling back to vertex arrays\n");
135                 m_storage = new RAS_StorageVA(&m_texco_num, m_texco, &m_attrib_num, m_attrib, m_attrib_layer);
136         }
137
138         glGetIntegerv(GL_MAX_LIGHTS, (GLint *) &m_numgllights);
139         if (m_numgllights < 8)
140                 m_numgllights = 8;
141
142         PrintHardwareInfo();
143 }
144
145
146
147 RAS_OpenGLRasterizer::~RAS_OpenGLRasterizer()
148 {
149         // Restore the previous AF value
150         GPU_set_anisotropic(m_prevafvalue);
151
152         if (m_storage)
153                 delete m_storage;
154 }
155
156 bool RAS_OpenGLRasterizer::Init()
157 {
158         bool storage_init;
159         GPU_state_init();
160
161
162         m_ambr = 0.0f;
163         m_ambg = 0.0f;
164         m_ambb = 0.0f;
165
166         glDisable(GL_BLEND);
167         glDisable(GL_ALPHA_TEST);
168         //m_last_alphablend = GPU_BLEND_SOLID;
169         GPU_set_material_alpha_blend(GPU_BLEND_SOLID);
170
171         glFrontFace(GL_CCW);
172         m_last_frontface = true;
173
174         m_redback = 0.4375f;
175         m_greenback = 0.4375f;
176         m_blueback = 0.4375f;
177         m_alphaback = 0.0f;
178
179         glClearColor(m_redback,m_greenback,m_blueback,m_alphaback);
180         glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
181         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
182
183
184         glShadeModel(GL_SMOOTH);
185
186         storage_init = m_storage->Init();
187
188         return true && storage_init;
189 }
190
191
192 void RAS_OpenGLRasterizer::SetAmbientColor(float color[3])
193 {
194         m_ambr = color[0];
195         m_ambg = color[1];
196         m_ambb = color[2];
197 }
198
199 void RAS_OpenGLRasterizer::SetAmbient(float factor)
200 {
201         float ambient[] = {m_ambr * factor, m_ambg * factor, m_ambb * factor, 1.0f};
202         glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient);
203 }
204
205 void RAS_OpenGLRasterizer::SetBackColor(float color[3])
206 {
207         m_redback = color[0];
208         m_greenback = color[1];
209         m_blueback = color[2];
210         m_alphaback = 1.0f;
211 }
212
213 void RAS_OpenGLRasterizer::SetFog(short type, float start, float dist, float intensity, float color[3])
214 {
215         float params[4] = {color[0], color[1], color[2], 1.0f};
216         glFogi(GL_FOG_MODE, GL_LINEAR);
217         glFogf(GL_FOG_DENSITY, intensity / 10.0f);
218         glFogf(GL_FOG_START, start);
219         glFogf(GL_FOG_END, start + dist);
220         glFogfv(GL_FOG_COLOR, params);
221 }
222
223 void RAS_OpenGLRasterizer::EnableFog(bool enable)
224 {
225         m_fogenabled = enable;
226 }
227
228 void RAS_OpenGLRasterizer::DisplayFog()
229 {
230         if ((m_drawingmode >= KX_SOLID) && m_fogenabled) {
231                 glEnable(GL_FOG);
232         }
233         else {
234                 glDisable(GL_FOG);
235         }
236 }
237
238 bool RAS_OpenGLRasterizer::SetMaterial(const RAS_IPolyMaterial& mat)
239 {
240         return mat.Activate(this, m_materialCachingInfo);
241 }
242
243
244
245 void RAS_OpenGLRasterizer::Exit()
246 {
247
248         m_storage->Exit();
249
250         glEnable(GL_CULL_FACE);
251         glEnable(GL_DEPTH_TEST);
252         glClearDepth(1.0f);
253         glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
254         glClearColor(m_redback, m_greenback, m_blueback, m_alphaback);
255         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
256         glDepthMask (GL_TRUE);
257         glDepthFunc(GL_LEQUAL);
258         glBlendFunc(GL_ONE, GL_ZERO);
259         
260         glDisable(GL_POLYGON_STIPPLE);
261         
262         glDisable(GL_LIGHTING);
263         if (GLEW_EXT_separate_specular_color || GLEW_VERSION_1_2)
264                 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
265         
266         EndFrame();
267 }
268
269 bool RAS_OpenGLRasterizer::BeginFrame(double time)
270 {
271         m_time = time;
272
273         // Blender camera routine destroys the settings
274         if (m_drawingmode < KX_SOLID)
275         {
276                 glDisable(GL_CULL_FACE);
277                 glDisable(GL_DEPTH_TEST);
278         }
279         else
280         {
281                 glEnable(GL_DEPTH_TEST);
282                 glEnable(GL_CULL_FACE);
283         }
284
285         glDisable(GL_BLEND);
286         glDisable(GL_ALPHA_TEST);
287         //m_last_alphablend = GPU_BLEND_SOLID;
288         GPU_set_material_alpha_blend(GPU_BLEND_SOLID);
289
290         glFrontFace(GL_CCW);
291         m_last_frontface = true;
292
293         glShadeModel(GL_SMOOTH);
294
295         glEnable(GL_MULTISAMPLE_ARB);
296
297         m_2DCanvas->BeginFrame();
298
299         // Render Tools
300         m_clientobject = NULL;
301         m_lastlightlayer = -1;
302         m_lastauxinfo = NULL;
303         m_lastlighting = true; /* force disable in DisableOpenGLLights() */
304         DisableOpenGLLights();
305         
306         return true;
307 }
308
309
310
311 void RAS_OpenGLRasterizer::SetDrawingMode(int drawingmode)
312 {
313         m_drawingmode = drawingmode;
314
315         if (m_drawingmode == KX_WIREFRAME)
316                 glDisable(GL_CULL_FACE);
317
318         m_storage->SetDrawingMode(drawingmode);
319 }
320
321 int RAS_OpenGLRasterizer::GetDrawingMode()
322 {
323         return m_drawingmode;
324 }
325
326
327 void RAS_OpenGLRasterizer::SetDepthMask(DepthMask depthmask)
328 {
329         glDepthMask(depthmask == KX_DEPTHMASK_DISABLED ? GL_FALSE : GL_TRUE);
330 }
331
332
333 void RAS_OpenGLRasterizer::ClearColorBuffer()
334 {
335         m_2DCanvas->ClearColor(m_redback,m_greenback,m_blueback,m_alphaback);
336         m_2DCanvas->ClearBuffer(RAS_ICanvas::COLOR_BUFFER);
337 }
338
339
340 void RAS_OpenGLRasterizer::ClearDepthBuffer()
341 {
342         m_2DCanvas->ClearBuffer(RAS_ICanvas::DEPTH_BUFFER);
343 }
344
345
346 void RAS_OpenGLRasterizer::ClearCachingInfo(void)
347 {
348         m_materialCachingInfo = 0;
349 }
350
351 void RAS_OpenGLRasterizer::FlushDebugShapes(SCA_IScene *scene)
352 {
353         std::vector<OglDebugShape> &debugShapes = m_debugShapes[scene];
354         if (debugShapes.empty())
355                 return;
356
357         // DrawDebugLines
358         GLboolean light, tex;
359
360         light= glIsEnabled(GL_LIGHTING);
361         tex= glIsEnabled(GL_TEXTURE_2D);
362
363         if (light) glDisable(GL_LIGHTING);
364         if (tex) glDisable(GL_TEXTURE_2D);
365
366         //draw lines
367         glBegin(GL_LINES);
368         for (unsigned int i = 0; i < debugShapes.size(); i++) {
369                 if (debugShapes[i].m_type != OglDebugShape::LINE)
370                         continue;
371                 glColor4f(debugShapes[i].m_color[0], debugShapes[i].m_color[1], debugShapes[i].m_color[2], 1.0f);
372                 const MT_Scalar *fromPtr = &debugShapes[i].m_pos.x();
373                 const MT_Scalar *toPtr= &debugShapes[i].m_param.x();
374                 glVertex3fv(fromPtr);
375                 glVertex3fv(toPtr);
376         }
377         glEnd();
378
379         //draw circles
380         for (unsigned int i = 0; i < debugShapes.size(); i++) {
381                 if (debugShapes[i].m_type != OglDebugShape::CIRCLE)
382                         continue;
383                 glBegin(GL_LINE_LOOP);
384                 glColor4f(debugShapes[i].m_color[0], debugShapes[i].m_color[1], debugShapes[i].m_color[2], 1.0f);
385
386                 static const MT_Vector3 worldUp(0.0f, 0.0f, 1.0f);
387                 MT_Vector3 norm = debugShapes[i].m_param;
388                 MT_Matrix3x3 tr;
389                 if (norm.fuzzyZero() || norm == worldUp)
390                 {
391                         tr.setIdentity();
392                 }
393                 else
394                 {
395                         MT_Vector3 xaxis, yaxis;
396                         xaxis = MT_cross(norm, worldUp);
397                         yaxis = MT_cross(xaxis, norm);
398                         tr.setValue(xaxis.x(), xaxis.y(), xaxis.z(),
399                                 yaxis.x(), yaxis.y(), yaxis.z(),
400                                 norm.x(), norm.y(), norm.z());
401                 }
402                 MT_Scalar rad = debugShapes[i].m_param2.x();
403                 int n = (int)debugShapes[i].m_param2.y();
404                 for (int j = 0; j<n; j++)
405                 {
406                         MT_Scalar theta = j*(float)M_PI*2/n;
407                         MT_Vector3 pos(cosf(theta) * rad, sinf(theta) * rad, 0.0f);
408                         pos = pos*tr;
409                         pos += debugShapes[i].m_pos;
410                         const MT_Scalar* posPtr = &pos.x();
411                         glVertex3fv(posPtr);
412                 }
413                 glEnd();
414         }
415
416         if (light) glEnable(GL_LIGHTING);
417         if (tex) glEnable(GL_TEXTURE_2D);
418
419         debugShapes.clear();
420 }
421
422 void RAS_OpenGLRasterizer::EndFrame()
423 {
424         glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
425
426         glDisable(GL_MULTISAMPLE_ARB);
427
428         m_2DCanvas->EndFrame();
429 }
430
431 void RAS_OpenGLRasterizer::SetRenderArea()
432 {
433         RAS_Rect area;
434         // only above/below stereo method needs viewport adjustment
435         switch (m_stereomode)
436         {
437                 case RAS_STEREO_ABOVEBELOW:
438                         switch (m_curreye) {
439                                 case RAS_STEREO_LEFTEYE:
440                                         // upper half of window
441                                         area.SetLeft(0);
442                                         area.SetBottom(m_2DCanvas->GetHeight() -
443                                                 int(m_2DCanvas->GetHeight() - m_noOfScanlines) / 2);
444         
445                                         area.SetRight(int(m_2DCanvas->GetWidth()));
446                                         area.SetTop(int(m_2DCanvas->GetHeight()));
447                                         m_2DCanvas->SetDisplayArea(&area);
448                                         break;
449                                 case RAS_STEREO_RIGHTEYE:
450                                         // lower half of window
451                                         area.SetLeft(0);
452                                         area.SetBottom(0);
453                                         area.SetRight(int(m_2DCanvas->GetWidth()));
454                                         area.SetTop(int(m_2DCanvas->GetHeight() - m_noOfScanlines) / 2);
455                                         m_2DCanvas->SetDisplayArea(&area);
456                                         break;
457                         }
458                         break;
459                 case RAS_STEREO_3DTVTOPBOTTOM:
460                         switch (m_curreye) {
461                                 case RAS_STEREO_LEFTEYE:
462                                         // upper half of window
463                                         area.SetLeft(0);
464                                         area.SetBottom(m_2DCanvas->GetHeight() -
465                                                 m_2DCanvas->GetHeight() / 2);
466         
467                                         area.SetRight(m_2DCanvas->GetWidth());
468                                         area.SetTop(m_2DCanvas->GetHeight());
469                                         m_2DCanvas->SetDisplayArea(&area);
470                                         break;
471                                 case RAS_STEREO_RIGHTEYE:
472                                         // lower half of window
473                                         area.SetLeft(0);
474                                         area.SetBottom(0);
475                                         area.SetRight(m_2DCanvas->GetWidth());
476                                         area.SetTop(m_2DCanvas->GetHeight() / 2);
477                                         m_2DCanvas->SetDisplayArea(&area);
478                                         break;
479                         }
480                         break;
481                 case RAS_STEREO_SIDEBYSIDE:
482                         switch (m_curreye)
483                         {
484                                 case RAS_STEREO_LEFTEYE:
485                                         // Left half of window
486                                         area.SetLeft(0);
487                                         area.SetBottom(0);
488                                         area.SetRight(m_2DCanvas->GetWidth()/2);
489                                         area.SetTop(m_2DCanvas->GetHeight());
490                                         m_2DCanvas->SetDisplayArea(&area);
491                                         break;
492                                 case RAS_STEREO_RIGHTEYE:
493                                         // Right half of window
494                                         area.SetLeft(m_2DCanvas->GetWidth()/2);
495                                         area.SetBottom(0);
496                                         area.SetRight(m_2DCanvas->GetWidth());
497                                         area.SetTop(m_2DCanvas->GetHeight());
498                                         m_2DCanvas->SetDisplayArea(&area);
499                                         break;
500                         }
501                         break;
502                 default:
503                         // every available pixel
504                         area.SetLeft(0);
505                         area.SetBottom(0);
506                         area.SetRight(int(m_2DCanvas->GetWidth()));
507                         area.SetTop(int(m_2DCanvas->GetHeight()));
508                         m_2DCanvas->SetDisplayArea(&area);
509                         break;
510         }
511 }
512         
513 void RAS_OpenGLRasterizer::SetStereoMode(const StereoMode stereomode)
514 {
515         m_stereomode = stereomode;
516 }
517
518 RAS_IRasterizer::StereoMode RAS_OpenGLRasterizer::GetStereoMode()
519 {
520         return m_stereomode;
521 }
522
523 bool RAS_OpenGLRasterizer::Stereo()
524 {
525         if (m_stereomode > RAS_STEREO_NOSTEREO) // > 0
526                 return true;
527         else
528                 return false;
529 }
530
531 bool RAS_OpenGLRasterizer::InterlacedStereo()
532 {
533         return m_stereomode == RAS_STEREO_VINTERLACE || m_stereomode == RAS_STEREO_INTERLACED;
534 }
535
536 void RAS_OpenGLRasterizer::SetEye(const StereoEye eye)
537 {
538         m_curreye = eye;
539         switch (m_stereomode)
540         {
541                 case RAS_STEREO_QUADBUFFERED:
542                         glDrawBuffer(m_curreye == RAS_STEREO_LEFTEYE ? GL_BACK_LEFT : GL_BACK_RIGHT);
543                         break;
544                 case RAS_STEREO_ANAGLYPH:
545                         if (m_curreye == RAS_STEREO_LEFTEYE) {
546                                 glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_FALSE);
547                         }
548                         else {
549                                 //glAccum(GL_LOAD, 1.0f);
550                                 glColorMask(GL_FALSE, GL_TRUE, GL_TRUE, GL_FALSE);
551                                 ClearDepthBuffer();
552                         }
553                         break;
554                 case RAS_STEREO_VINTERLACE:
555                 {
556                         // OpenGL stippling is deprecated, it is no longer possible to affect all shaders
557                         // this way, offscreen rendering and then compositing may be the better solution
558                         glEnable(GL_POLYGON_STIPPLE);
559                         glPolygonStipple((const GLubyte*) ((m_curreye == RAS_STEREO_LEFTEYE) ? left_eye_vinterlace_mask : right_eye_vinterlace_mask));
560                         if (m_curreye == RAS_STEREO_RIGHTEYE)
561                                 ClearDepthBuffer();
562                         break;
563                 }
564                 case RAS_STEREO_INTERLACED:
565                 {
566                         glEnable(GL_POLYGON_STIPPLE);
567                         glPolygonStipple((const GLubyte*) &hinterlace_mask[m_curreye == RAS_STEREO_LEFTEYE?0:1]);
568                         if (m_curreye == RAS_STEREO_RIGHTEYE)
569                                 ClearDepthBuffer();
570                         break;
571                 }
572                 default:
573                         break;
574         }
575 }
576
577 RAS_IRasterizer::StereoEye RAS_OpenGLRasterizer::GetEye()
578 {
579         return m_curreye;
580 }
581
582
583 void RAS_OpenGLRasterizer::SetEyeSeparation(const float eyeseparation)
584 {
585         m_eyeseparation = eyeseparation;
586 }
587
588 float RAS_OpenGLRasterizer::GetEyeSeparation()
589 {
590         return m_eyeseparation;
591 }
592
593 void RAS_OpenGLRasterizer::SetFocalLength(const float focallength)
594 {
595         m_focallength = focallength;
596         m_setfocallength = true;
597 }
598
599 float RAS_OpenGLRasterizer::GetFocalLength()
600 {
601         return m_focallength;
602 }
603
604
605 void RAS_OpenGLRasterizer::SwapBuffers()
606 {
607         m_2DCanvas->SwapBuffers();
608 }
609
610
611
612 const MT_Matrix4x4& RAS_OpenGLRasterizer::GetViewMatrix() const
613 {
614         return m_viewmatrix;
615 }
616
617 const MT_Matrix4x4& RAS_OpenGLRasterizer::GetViewInvMatrix() const
618 {
619         return m_viewinvmatrix;
620 }
621
622 void RAS_OpenGLRasterizer::IndexPrimitives_3DText(RAS_MeshSlot& ms,
623                                                                         class RAS_IPolyMaterial* polymat)
624
625         bool obcolor = ms.m_bObjectColor;
626         MT_Vector4& rgba = ms.m_RGBAcolor;
627         RAS_MeshSlot::iterator it;
628
629         const STR_String& mytext = ((CValue*)m_clientobject)->GetPropertyText("Text");
630
631         // handle object color
632         if (obcolor) {
633                 glDisableClientState(GL_COLOR_ARRAY);
634                 glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]);
635         }
636         else
637                 glEnableClientState(GL_COLOR_ARRAY);
638
639         for (ms.begin(it); !ms.end(it); ms.next(it)) {
640                 RAS_TexVert *vertex;
641                 size_t i, j, numvert;
642                 
643                 numvert = it.array->m_type;
644
645                 if (it.array->m_type == RAS_DisplayArray::LINE) {
646                         // line drawing, no text
647                         glBegin(GL_LINES);
648
649                         for (i=0; i<it.totindex; i+=2)
650                         {
651                                 vertex = &it.vertex[it.index[i]];
652                                 glVertex3fv(vertex->getXYZ());
653
654                                 vertex = &it.vertex[it.index[i+1]];
655                                 glVertex3fv(vertex->getXYZ());
656                         }
657
658                         glEnd();
659                 }
660                 else {
661                         // triangle and quad text drawing
662                         for (i=0; i<it.totindex; i+=numvert)
663                         {
664                                 float  v[4][3];
665                                 const float  *v_ptr[4] = {NULL};
666                                 const float *uv_ptr[4] = {NULL};
667                                 int glattrib, unit;
668
669                                 for (j=0; j<numvert; j++) {
670                                         vertex = &it.vertex[it.index[i+j]];
671
672                                         v[j][0] = vertex->getXYZ()[0];
673                                         v[j][1] = vertex->getXYZ()[1];
674                                         v[j][2] = vertex->getXYZ()[2];
675                                         v_ptr[j] = v[j];
676
677                                         uv_ptr[j] = vertex->getUV(0);
678                                 }
679
680                                 // find the right opengl attribute
681                                 glattrib = -1;
682                                 if (GLEW_ARB_vertex_program)
683                                         for (unit=0; unit<m_attrib_num; unit++)
684                                                 if (m_attrib[unit] == RAS_TEXCO_UV)
685                                                         glattrib = unit;
686
687                                 GPU_render_text(
688                                         polymat->GetMTexPoly(), polymat->GetDrawingMode(), mytext, mytext.Length(), polymat->GetMCol(),
689                                         v_ptr, uv_ptr, glattrib);
690
691                                 ClearCachingInfo();
692                         }
693                 }
694         }
695
696         glDisableClientState(GL_COLOR_ARRAY);
697 }
698
699 void RAS_OpenGLRasterizer::SetTexCoordNum(int num)
700 {
701         m_texco_num = num;
702         if (m_texco_num > RAS_MAX_TEXCO)
703                 m_texco_num = RAS_MAX_TEXCO;
704 }
705
706 void RAS_OpenGLRasterizer::SetAttribNum(int num)
707 {
708         m_attrib_num = num;
709         if (m_attrib_num > RAS_MAX_ATTRIB)
710                 m_attrib_num = RAS_MAX_ATTRIB;
711 }
712
713 void RAS_OpenGLRasterizer::SetTexCoord(TexCoGen coords, int unit)
714 {
715         // this changes from material to material
716         if (unit < RAS_MAX_TEXCO)
717                 m_texco[unit] = coords;
718 }
719
720 void RAS_OpenGLRasterizer::SetAttrib(TexCoGen coords, int unit, int layer)
721 {
722         // this changes from material to material
723         if (unit < RAS_MAX_ATTRIB) {
724                 m_attrib[unit] = coords;
725                 m_attrib_layer[unit] = layer;
726         }
727 }
728
729 void RAS_OpenGLRasterizer::IndexPrimitives(RAS_MeshSlot& ms)
730 {
731         if (ms.m_pDerivedMesh)
732                 DrawDerivedMesh(ms);
733         else
734                 m_storage->IndexPrimitives(ms);
735 }
736
737 // Code for hooking into Blender's mesh drawing for derived meshes.
738 // If/when we use more of Blender's drawing code, we may be able to
739 // clean this up
740 static bool current_wireframe;
741 static RAS_MaterialBucket *current_bucket;
742 static RAS_IPolyMaterial *current_polymat;
743 static RAS_MeshSlot *current_ms;
744 static RAS_MeshObject *current_mesh;
745 static int current_blmat_nr;
746 static GPUVertexAttribs current_gpu_attribs;
747 static Image *current_image;
748 static int CheckMaterialDM(int matnr, void *attribs)
749 {
750         // only draw the current material
751         if (matnr != current_blmat_nr)
752                 return 0;
753         GPUVertexAttribs *gattribs = (GPUVertexAttribs *)attribs;
754         if (gattribs)
755                 memcpy(gattribs, &current_gpu_attribs, sizeof(GPUVertexAttribs));
756         return 1;
757 }
758
759 static DMDrawOption CheckTexDM(MTexPoly *mtexpoly, const bool has_mcol, int matnr)
760 {
761
762         // index is the original face index, retrieve the polygon
763         if (matnr == current_blmat_nr &&
764                 (mtexpoly == NULL || mtexpoly->tpage == current_image)) {
765                 // must handle color.
766                 if (current_wireframe)
767                         return DM_DRAW_OPTION_NO_MCOL;
768                 if (current_ms->m_bObjectColor) {
769                         MT_Vector4& rgba = current_ms->m_RGBAcolor;
770                         glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]);
771                         // don't use mcol
772                         return DM_DRAW_OPTION_NO_MCOL;
773                 }
774                 if (!has_mcol) {
775                         // we have to set the color from the material
776                         unsigned char rgba[4];
777                         current_polymat->GetMaterialRGBAColor(rgba);
778                         glColor4ubv((const GLubyte *)rgba);
779                         return DM_DRAW_OPTION_NO_MCOL;
780                 }
781                 return DM_DRAW_OPTION_NORMAL;
782         }
783         return DM_DRAW_OPTION_SKIP;
784 }
785
786 void RAS_OpenGLRasterizer::DrawDerivedMesh(class RAS_MeshSlot &ms)
787 {
788         // mesh data is in derived mesh,
789         current_bucket = ms.m_bucket;
790         current_polymat = current_bucket->GetPolyMaterial();
791         current_ms = &ms;
792         current_mesh = ms.m_mesh;
793         current_wireframe = m_drawingmode <= RAS_IRasterizer::KX_WIREFRAME;
794         // MCol *mcol = (MCol*)ms.m_pDerivedMesh->getFaceDataArray(ms.m_pDerivedMesh, CD_MCOL); /* UNUSED */
795
796         // handle two-side
797         if (current_polymat->GetDrawingMode() & RAS_IRasterizer::KX_BACKCULL)
798                 this->SetCullFace(true);
799         else
800                 this->SetCullFace(false);
801
802         if (current_polymat->GetFlag() & RAS_BLENDERGLSL) {
803                 // GetMaterialIndex return the original mface material index,
804                 // increment by 1 to match what derived mesh is doing
805                 current_blmat_nr = current_polymat->GetMaterialIndex()+1;
806                 // For GLSL we need to retrieve the GPU material attribute
807                 Material* blmat = current_polymat->GetBlenderMaterial();
808                 Scene* blscene = current_polymat->GetBlenderScene();
809                 if (!current_wireframe && blscene && blmat)
810                         GPU_material_vertex_attributes(GPU_material_from_blender(blscene, blmat, false), &current_gpu_attribs);
811                 else
812                         memset(&current_gpu_attribs, 0, sizeof(current_gpu_attribs));
813                 // DM draw can mess up blending mode, restore at the end
814                 int current_blend_mode = GPU_get_material_alpha_blend();
815                 ms.m_pDerivedMesh->drawFacesGLSL(ms.m_pDerivedMesh, CheckMaterialDM);
816                 GPU_set_material_alpha_blend(current_blend_mode);
817         } else {
818                 //ms.m_pDerivedMesh->drawMappedFacesTex(ms.m_pDerivedMesh, CheckTexfaceDM, mcol);
819                 current_blmat_nr = current_polymat->GetMaterialIndex();
820                 current_image = current_polymat->GetBlenderImage();
821                 ms.m_pDerivedMesh->drawFacesTex(ms.m_pDerivedMesh, CheckTexDM, NULL, NULL, DM_DRAW_USE_ACTIVE_UV);
822         }
823 }
824
825 void RAS_OpenGLRasterizer::SetProjectionMatrix(MT_CmMatrix4x4 &mat)
826 {
827         glMatrixMode(GL_PROJECTION);
828         float* matrix = &mat(0, 0);
829         glLoadMatrixf(matrix);
830
831         m_camortho = (mat(3, 3) != 0.0f);
832 }
833
834 void RAS_OpenGLRasterizer::SetProjectionMatrix(const MT_Matrix4x4 & mat)
835 {
836         glMatrixMode(GL_PROJECTION);
837         float matrix[16];
838         /* Get into argument. Looks a bit dodgy, but it's ok. */
839         mat.getValue(matrix);
840         /* Internally, MT_Matrix4x4 uses doubles (MT_Scalar). */
841         glLoadMatrixf(matrix);
842
843         m_camortho= (mat[3][3] != 0.0f);
844 }
845
846 MT_Matrix4x4 RAS_OpenGLRasterizer::GetFrustumMatrix(
847         float left,
848         float right,
849         float bottom,
850         float top,
851         float frustnear,
852         float frustfar,
853         float focallength,
854         bool 
855 ) {
856         MT_Matrix4x4 result;
857         float mat[16];
858
859         // correction for stereo
860         if (Stereo())
861         {
862                         float near_div_focallength;
863                         float offset;
864
865                         // if Rasterizer.setFocalLength is not called we use the camera focallength
866                         if (!m_setfocallength)
867                                 // if focallength is null we use a value known to be reasonable
868                                 m_focallength = (focallength == 0.f) ? m_eyeseparation * 30.0f
869                                         : focallength;
870
871                         near_div_focallength = frustnear / m_focallength;
872                         offset = 0.5f * m_eyeseparation * near_div_focallength;
873                         switch (m_curreye) {
874                                 case RAS_STEREO_LEFTEYE:
875                                                 left += offset;
876                                                 right += offset;
877                                                 break;
878                                 case RAS_STEREO_RIGHTEYE:
879                                                 left -= offset;
880                                                 right -= offset;
881                                                 break;
882                         }
883                         // leave bottom and top untouched
884                         if (m_stereomode == RAS_STEREO_3DTVTOPBOTTOM) {
885                                 // restore the vertical frustrum because the 3DTV will 
886                                 // expande the top and bottom part to the full size of the screen
887                                 bottom *= 2.0f;
888                                 top *= 2.0f;
889                         }
890         }
891         
892         glMatrixMode(GL_PROJECTION);
893         glLoadIdentity();
894         glFrustum(left, right, bottom, top, frustnear, frustfar);
895                 
896         glGetFloatv(GL_PROJECTION_MATRIX, mat);
897         result.setValue(mat);
898
899         return result;
900 }
901
902 MT_Matrix4x4 RAS_OpenGLRasterizer::GetOrthoMatrix(
903         float left,
904         float right,
905         float bottom,
906         float top,
907         float frustnear,
908         float frustfar
909 ) {
910         MT_Matrix4x4 result;
911         float mat[16];
912
913         // stereo is meaning less for orthographic, disable it
914         glMatrixMode(GL_PROJECTION);
915         glLoadIdentity();
916         glOrtho(left, right, bottom, top, frustnear, frustfar);
917                 
918         glGetFloatv(GL_PROJECTION_MATRIX, mat);
919         result.setValue(mat);
920
921         return result;
922 }
923
924
925 // next arguments probably contain redundant info, for later...
926 void RAS_OpenGLRasterizer::SetViewMatrix(const MT_Matrix4x4 &mat, 
927                                                                                  const MT_Matrix3x3 & camOrientMat3x3,
928                                                                                  const MT_Point3 & pos,
929                                                                                  bool perspective)
930 {
931         m_viewmatrix = mat;
932
933         // correction for stereo
934         if (Stereo() && perspective)
935         {
936                 MT_Vector3 unitViewDir(0.0f, -1.0f, 0.0f);  // minus y direction, Blender convention
937                 MT_Vector3 unitViewupVec(0.0f, 0.0f, 1.0f);
938                 MT_Vector3 viewDir, viewupVec;
939                 MT_Vector3 eyeline;
940
941                 // actual viewDir
942                 viewDir = camOrientMat3x3 * unitViewDir;  // this is the moto convention, vector on right hand side
943                 // actual viewup vec
944                 viewupVec = camOrientMat3x3 * unitViewupVec;
945
946                 // vector between eyes
947                 eyeline = viewDir.cross(viewupVec);
948
949                 switch (m_curreye) {
950                         case RAS_STEREO_LEFTEYE:
951                                 {
952                                 // translate to left by half the eye distance
953                                 MT_Transform transform;
954                                 transform.setIdentity();
955                                 transform.translate(-(eyeline * m_eyeseparation / 2.0f));
956                                 m_viewmatrix *= transform;
957                                 }
958                                 break;
959                         case RAS_STEREO_RIGHTEYE:
960                                 {
961                                 // translate to right by half the eye distance
962                                 MT_Transform transform;
963                                 transform.setIdentity();
964                                 transform.translate(eyeline * m_eyeseparation / 2.0f);
965                                 m_viewmatrix *= transform;
966                                 }
967                                 break;
968                 }
969         }
970
971         m_viewinvmatrix = m_viewmatrix;
972         m_viewinvmatrix.invert();
973
974         // note: getValue gives back column major as needed by OpenGL
975         MT_Scalar glviewmat[16];
976         m_viewmatrix.getValue(glviewmat);
977
978         glMatrixMode(GL_MODELVIEW);
979         glLoadMatrixf(glviewmat);
980         m_campos = pos;
981 }
982
983
984 const MT_Point3& RAS_OpenGLRasterizer::GetCameraPosition()
985 {
986         return m_campos;
987 }
988
989 bool RAS_OpenGLRasterizer::GetCameraOrtho()
990 {
991         return m_camortho;
992 }
993
994 void RAS_OpenGLRasterizer::SetCullFace(bool enable)
995 {
996         if (enable)
997                 glEnable(GL_CULL_FACE);
998         else
999                 glDisable(GL_CULL_FACE);
1000 }
1001
1002 void RAS_OpenGLRasterizer::SetLines(bool enable)
1003 {
1004         if (enable)
1005                 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
1006         else
1007                 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1008 }
1009
1010 void RAS_OpenGLRasterizer::SetSpecularity(float specX,
1011                                                                                   float specY,
1012                                                                                   float specZ,
1013                                                                                   float specval)
1014 {
1015         GLfloat mat_specular[] = {specX, specY, specZ, specval};
1016         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
1017 }
1018
1019
1020
1021 void RAS_OpenGLRasterizer::SetShinyness(float shiny)
1022 {
1023         GLfloat mat_shininess[] = {     shiny };
1024         glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess);
1025 }
1026
1027
1028
1029 void RAS_OpenGLRasterizer::SetDiffuse(float difX,float difY,float difZ,float diffuse)
1030 {
1031         GLfloat mat_diffuse [] = {difX, difY,difZ, diffuse};
1032         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diffuse);
1033 }
1034
1035 void RAS_OpenGLRasterizer::SetEmissive(float eX, float eY, float eZ, float e)
1036 {
1037         GLfloat mat_emit [] = {eX,eY,eZ,e};
1038         glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, mat_emit);
1039 }
1040
1041
1042 double RAS_OpenGLRasterizer::GetTime()
1043 {
1044         return m_time;
1045 }
1046
1047 void RAS_OpenGLRasterizer::SetPolygonOffset(float mult, float add)
1048 {
1049         glPolygonOffset(mult, add);
1050         GLint mode = GL_POLYGON_OFFSET_FILL;
1051         if (m_drawingmode < KX_SHADED)
1052                 mode = GL_POLYGON_OFFSET_LINE;
1053         if (mult != 0.0f || add != 0.0f)
1054                 glEnable(mode);
1055         else
1056                 glDisable(mode);
1057 }
1058
1059 void RAS_OpenGLRasterizer::EnableMotionBlur(float motionblurvalue)
1060 {
1061         /* don't just set m_motionblur to 1, but check if it is 0 so
1062          * we don't reset a motion blur that is already enabled */
1063         if (m_motionblur == 0)
1064                 m_motionblur = 1;
1065         m_motionblurvalue = motionblurvalue;
1066 }
1067
1068 void RAS_OpenGLRasterizer::DisableMotionBlur()
1069 {
1070         m_motionblur = 0;
1071         m_motionblurvalue = -1.0f;
1072 }
1073
1074 void RAS_OpenGLRasterizer::SetAlphaBlend(int alphablend)
1075 {
1076         /* Variance shadow maps don't handle alpha well, best to not allow it for now  */
1077         if (m_drawingmode == KX_SHADOW && m_usingoverrideshader)
1078                 GPU_set_material_alpha_blend(GPU_BLEND_SOLID);
1079         else
1080                 GPU_set_material_alpha_blend(alphablend);
1081 /*
1082         if (alphablend == m_last_alphablend)
1083                 return;
1084
1085         if (alphablend == GPU_BLEND_SOLID) {
1086                 glDisable(GL_BLEND);
1087                 glDisable(GL_ALPHA_TEST);
1088                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1089         }
1090         else if (alphablend == GPU_BLEND_ADD) {
1091                 glBlendFunc(GL_ONE, GL_ONE);
1092                 glEnable(GL_BLEND);
1093                 glDisable(GL_ALPHA_TEST);
1094         }
1095         else if (alphablend == GPU_BLEND_ALPHA) {
1096                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1097                 glEnable(GL_BLEND);
1098                 glEnable(GL_ALPHA_TEST);
1099                 glAlphaFunc(GL_GREATER, 0.0f);
1100         }
1101         else if (alphablend == GPU_BLEND_CLIP) {
1102                 glDisable(GL_BLEND); 
1103                 glEnable(GL_ALPHA_TEST);
1104                 glAlphaFunc(GL_GREATER, 0.5f);
1105         }
1106
1107         m_last_alphablend = alphablend;
1108 */
1109 }
1110
1111 void RAS_OpenGLRasterizer::SetFrontFace(bool ccw)
1112 {
1113         if (m_last_frontface == ccw)
1114                 return;
1115
1116         if (ccw)
1117                 glFrontFace(GL_CCW);
1118         else
1119                 glFrontFace(GL_CW);
1120         
1121         m_last_frontface = ccw;
1122 }
1123
1124 void RAS_OpenGLRasterizer::SetAnisotropicFiltering(short level)
1125 {
1126         GPU_set_anisotropic((float)level);
1127 }
1128
1129 short RAS_OpenGLRasterizer::GetAnisotropicFiltering()
1130 {
1131         return (short)GPU_get_anisotropic();
1132 }
1133
1134 void RAS_OpenGLRasterizer::SetMipmapping(MipmapOption val)
1135 {
1136         if (val == RAS_IRasterizer::RAS_MIPMAP_LINEAR)
1137         {
1138                 GPU_set_linear_mipmap(1);
1139                 GPU_set_mipmap(1);
1140         }
1141         else if (val == RAS_IRasterizer::RAS_MIPMAP_NEAREST)
1142         {
1143                 GPU_set_linear_mipmap(0);
1144                 GPU_set_mipmap(1);
1145         }
1146         else
1147         {
1148                 GPU_set_linear_mipmap(0);
1149                 GPU_set_mipmap(0);
1150         }
1151 }
1152
1153 RAS_IRasterizer::MipmapOption RAS_OpenGLRasterizer::GetMipmapping()
1154 {
1155         if (GPU_get_mipmap()) {
1156                 if (GPU_get_linear_mipmap()) {
1157                         return RAS_IRasterizer::RAS_MIPMAP_LINEAR;
1158                 }
1159                 else {
1160                         return RAS_IRasterizer::RAS_MIPMAP_NEAREST;
1161                 }
1162         }
1163         else {
1164                 return RAS_IRasterizer::RAS_MIPMAP_NONE;
1165         }
1166 }
1167
1168 void RAS_OpenGLRasterizer::SetUsingOverrideShader(bool val)
1169 {
1170         m_usingoverrideshader = val;
1171 }
1172
1173 bool RAS_OpenGLRasterizer::GetUsingOverrideShader()
1174 {
1175         return m_usingoverrideshader;
1176 }
1177
1178 /**
1179  * Render Tools
1180  */
1181
1182 /* ProcessLighting performs lighting on objects. the layer is a bitfield that
1183  * contains layer information. There are 20 'official' layers in blender. A
1184  * light is applied on an object only when they are in the same layer. OpenGL
1185  * has a maximum of 8 lights (simultaneous), so 20 * 8 lights are possible in
1186  * a scene. */
1187
1188 void RAS_OpenGLRasterizer::ProcessLighting(bool uselights, const MT_Transform& viewmat)
1189 {
1190         bool enable = false;
1191         int layer= -1;
1192
1193         /* find the layer */
1194         if (uselights) {
1195                 if (m_clientobject)
1196                         layer = static_cast<KX_GameObject*>(m_clientobject)->GetLayer();
1197         }
1198
1199         /* avoid state switching */
1200         if (m_lastlightlayer == layer && m_lastauxinfo == m_auxilaryClientInfo)
1201                 return;
1202
1203         m_lastlightlayer = layer;
1204         m_lastauxinfo = m_auxilaryClientInfo;
1205
1206         /* enable/disable lights as needed */
1207         if (layer >= 0) {
1208                 //enable = ApplyLights(layer, viewmat);
1209                 // taken from blender source, incompatibility between Blender Object / GameObject
1210                 KX_Scene* kxscene = (KX_Scene*)m_auxilaryClientInfo;
1211                 float glviewmat[16];
1212                 unsigned int count;
1213                 std::vector<RAS_OpenGLLight*>::iterator lit = m_lights.begin();
1214
1215                 for (count=0; count<m_numgllights; count++)
1216                         glDisable((GLenum)(GL_LIGHT0+count));
1217
1218                 viewmat.getValue(glviewmat);
1219
1220                 glPushMatrix();
1221                 glLoadMatrixf(glviewmat);
1222                 for (lit = m_lights.begin(), count = 0; !(lit==m_lights.end()) && count < m_numgllights; ++lit)
1223                 {
1224                         RAS_OpenGLLight* light = (*lit);
1225
1226                         if (light->ApplyFixedFunctionLighting(kxscene, layer, count))
1227                                 count++;
1228                 }
1229                 glPopMatrix();
1230
1231                 enable = count > 0;
1232         }
1233
1234         if (enable)
1235                 EnableOpenGLLights();
1236         else
1237                 DisableOpenGLLights();
1238 }
1239
1240 void RAS_OpenGLRasterizer::EnableOpenGLLights()
1241 {
1242         if (m_lastlighting == true)
1243                 return;
1244
1245         glEnable(GL_LIGHTING);
1246         glEnable(GL_COLOR_MATERIAL);
1247
1248         glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
1249         glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
1250         glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, (GetCameraOrtho())? GL_FALSE: GL_TRUE);
1251         if (GLEW_EXT_separate_specular_color || GLEW_VERSION_1_2)
1252                 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1253
1254         m_lastlighting = true;
1255 }
1256
1257 void RAS_OpenGLRasterizer::DisableOpenGLLights()
1258 {
1259         if (m_lastlighting == false)
1260                 return;
1261
1262         glDisable(GL_LIGHTING);
1263         glDisable(GL_COLOR_MATERIAL);
1264
1265         m_lastlighting = false;
1266 }
1267
1268 RAS_ILightObject *RAS_OpenGLRasterizer::CreateLight()
1269 {
1270         return new RAS_OpenGLLight(this);
1271 }
1272
1273 void RAS_OpenGLRasterizer::AddLight(RAS_ILightObject* lightobject)
1274 {
1275         RAS_OpenGLLight* gllight = dynamic_cast<RAS_OpenGLLight*>(lightobject);
1276         assert(gllight);
1277         m_lights.push_back(gllight);
1278 }
1279
1280 void RAS_OpenGLRasterizer::RemoveLight(RAS_ILightObject* lightobject)
1281 {
1282         RAS_OpenGLLight* gllight = dynamic_cast<RAS_OpenGLLight*>(lightobject);
1283         assert(gllight);
1284
1285         std::vector<RAS_OpenGLLight*>::iterator lit =
1286                 std::find(m_lights.begin(),m_lights.end(),gllight);
1287
1288         if (!(lit==m_lights.end()))
1289                 m_lights.erase(lit);
1290 }
1291
1292 bool RAS_OpenGLRasterizer::RayHit(struct KX_ClientObjectInfo *client, KX_RayCast *result, float *oglmatrix)
1293 {
1294         if (result->m_hitMesh) {
1295
1296                 RAS_Polygon* poly = result->m_hitMesh->GetPolygon(result->m_hitPolygon);
1297                 if (!poly->IsVisible())
1298                         return false;
1299
1300                 MT_Vector3 resultnormal(result->m_hitNormal);
1301                 MT_Vector3 left(oglmatrix[0],oglmatrix[1],oglmatrix[2]);
1302                 MT_Vector3 dir = -(left.cross(resultnormal)).safe_normalized();
1303                 left = (dir.cross(resultnormal)).safe_normalized();
1304                 // for the up vector, we take the 'resultnormal' returned by the physics
1305
1306                 float maat[16] = {left[0],         left[1],         left[2],         0,
1307                                        dir[0],          dir[1],          dir[2],          0,
1308                                            resultnormal[0], resultnormal[1], resultnormal[2], 0,
1309                                                0,               0,               0,               1};
1310
1311                 glTranslatef(oglmatrix[12],oglmatrix[13],oglmatrix[14]);
1312                 //glMultMatrixd(oglmatrix);
1313                 glMultMatrixf(maat);
1314                 return true;
1315         }
1316         else {
1317                 return false;
1318         }
1319 }
1320
1321 void RAS_OpenGLRasterizer::applyTransform(float* oglmatrix,int objectdrawmode )
1322 {
1323         /* FIXME:
1324         blender: intern/moto/include/MT_Vector3.inl:42: MT_Vector3 operator/(const
1325         MT_Vector3&, double): Assertion `!MT_fuzzyZero(s)' failed.
1326
1327         Program received signal SIGABRT, Aborted.
1328         [Switching to Thread 16384 (LWP 1519)]
1329         0x40477571 in kill () from /lib/libc.so.6
1330         (gdb) bt
1331         #7  0x08334368 in MT_Vector3::normalized() const ()
1332         #8  0x0833e6ec in RAS_OpenGLRasterizer::applyTransform(RAS_IRasterizer*, double*, int) ()
1333         */
1334
1335         if (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED ||
1336                 objectdrawmode & RAS_IPolyMaterial::BILLBOARD_AXISALIGNED)
1337         {
1338                 // rotate the billboard/halo
1339                 //page 360/361 3D Game Engine Design, David Eberly for a discussion
1340                 // on screen aligned and axis aligned billboards
1341                 // assumed is that the preprocessor transformed all billboard polygons
1342                 // so that their normal points into the positive x direction (1.0f, 0.0f, 0.0f)
1343                 // when new parenting for objects is done, this rotation
1344                 // will be moved into the object
1345
1346                 MT_Point3 objpos (oglmatrix[12],oglmatrix[13],oglmatrix[14]);
1347                 MT_Point3 campos = GetCameraPosition();
1348                 MT_Vector3 dir = (campos - objpos).safe_normalized();
1349                 MT_Vector3 up(0,0,1.0f);
1350
1351                 KX_GameObject* gameobj = (KX_GameObject*)m_clientobject;
1352                 // get scaling of halo object
1353                 MT_Vector3  size = gameobj->GetSGNode()->GetWorldScaling();
1354
1355                 bool screenaligned = (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED)!=0;//false; //either screen or axisaligned
1356                 if (screenaligned)
1357                 {
1358                         up = (up - up.dot(dir) * dir).safe_normalized();
1359                 } else
1360                 {
1361                         dir = (dir - up.dot(dir)*up).safe_normalized();
1362                 }
1363
1364                 MT_Vector3 left = dir.normalized();
1365                 dir = (up.cross(left)).normalized();
1366
1367                 // we have calculated the row vectors, now we keep
1368                 // local scaling into account:
1369
1370                 left *= size[0];
1371                 dir  *= size[1];
1372                 up   *= size[2];
1373
1374                 float maat[16] = {left[0], left[1], left[2], 0,
1375                                    dir[0],  dir[1],  dir[2],  0,
1376                                    up[0],   up[1],   up[2],   0,
1377                                    0,       0,       0,       1};
1378
1379                 glTranslatef(objpos[0],objpos[1],objpos[2]);
1380                 glMultMatrixf(maat);
1381
1382         }
1383         else {
1384                 if (objectdrawmode & RAS_IPolyMaterial::SHADOW)
1385                 {
1386                         // shadow must be cast to the ground, physics system needed here!
1387                         MT_Point3 frompoint(oglmatrix[12],oglmatrix[13],oglmatrix[14]);
1388                         KX_GameObject *gameobj = (KX_GameObject*)m_clientobject;
1389                         MT_Vector3 direction = MT_Vector3(0,0,-1);
1390
1391                         direction.normalize();
1392                         direction *= 100000;
1393
1394                         MT_Point3 topoint = frompoint + direction;
1395
1396                         KX_Scene* kxscene = (KX_Scene*) m_auxilaryClientInfo;
1397                         PHY_IPhysicsEnvironment* physics_environment = kxscene->GetPhysicsEnvironment();
1398                         PHY_IPhysicsController* physics_controller = gameobj->GetPhysicsController();
1399
1400                         KX_GameObject *parent = gameobj->GetParent();
1401                         if (!physics_controller && parent)
1402                                 physics_controller = parent->GetPhysicsController();
1403
1404                         KX_RayCast::Callback<RAS_OpenGLRasterizer, float> callback(this, physics_controller, oglmatrix);
1405                         if (!KX_RayCast::RayTest(physics_environment, frompoint, topoint, callback))
1406                         {
1407                                 // couldn't find something to cast the shadow on...
1408                                 glMultMatrixf(oglmatrix);
1409                         }
1410                         else
1411                         { // we found the "ground", but the cast matrix doesn't take
1412                           // scaling in consideration, so we must apply the object scale
1413                                 MT_Vector3  size = gameobj->GetSGNode()->GetLocalScale();
1414                                 glScalef(size[0], size[1], size[2]);
1415                         }
1416                 } else
1417                 {
1418
1419                         // 'normal' object
1420                         glMultMatrixf(oglmatrix);
1421                 }
1422         }
1423 }
1424
1425 static void DisableForText()
1426 {
1427         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); /* needed for texture fonts otherwise they render as wireframe */
1428
1429         glDisable(GL_BLEND);
1430         glDisable(GL_ALPHA_TEST);
1431
1432         glDisable(GL_LIGHTING);
1433         glDisable(GL_COLOR_MATERIAL);
1434
1435         if (GLEW_ARB_multitexture) {
1436                 for (int i=0; i<RAS_MAX_TEXCO; i++) {
1437                         glActiveTextureARB(GL_TEXTURE0_ARB+i);
1438
1439                         if (GLEW_ARB_texture_cube_map) {
1440                                 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1441                                 glDisable(GL_TEXTURE_GEN_S);
1442                                 glDisable(GL_TEXTURE_GEN_T);
1443                                 glDisable(GL_TEXTURE_GEN_Q);
1444                                 glDisable(GL_TEXTURE_GEN_R);
1445                         }
1446                         glDisable(GL_TEXTURE_2D);
1447                 }
1448
1449                 glActiveTextureARB(GL_TEXTURE0_ARB);
1450         }
1451         else {
1452                 if (GLEW_ARB_texture_cube_map)
1453                         glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1454
1455                 glDisable(GL_TEXTURE_2D);
1456         }
1457 }
1458
1459 void RAS_OpenGLRasterizer::RenderBox2D(int xco,
1460                         int yco,
1461                         int width,
1462                         int height,
1463                         float percentage)
1464 {
1465         /* This is a rather important line :( The gl-mode hasn't been left
1466          * behind quite as neatly as we'd have wanted to. I don't know
1467          * what cause it, though :/ .*/
1468         glDisable(GL_DEPTH_TEST);
1469
1470         glMatrixMode(GL_PROJECTION);
1471         glPushMatrix();
1472         glLoadIdentity();
1473
1474         glOrtho(0, width, 0, height, -100, 100);
1475
1476         glMatrixMode(GL_MODELVIEW);
1477         glPushMatrix();
1478         glLoadIdentity();
1479
1480         yco = height - yco;
1481         int barsize = 50;
1482
1483         /* draw in black first*/
1484         glColor3ub(0, 0, 0);
1485         glBegin(GL_QUADS);
1486         glVertex2f(xco + 1 + 1 + barsize * percentage, yco - 1 + 10);
1487         glVertex2f(xco + 1, yco - 1 + 10);
1488         glVertex2f(xco + 1, yco - 1);
1489         glVertex2f(xco + 1 + 1 + barsize * percentage, yco - 1);
1490         glEnd();
1491
1492         glColor3ub(255, 255, 255);
1493         glBegin(GL_QUADS);
1494         glVertex2f(xco + 1 + barsize * percentage, yco + 10);
1495         glVertex2f(xco, yco + 10);
1496         glVertex2f(xco, yco);
1497         glVertex2f(xco + 1 + barsize * percentage, yco);
1498         glEnd();
1499
1500         glMatrixMode(GL_PROJECTION);
1501         glPopMatrix();
1502         glMatrixMode(GL_MODELVIEW);
1503         glPopMatrix();
1504         glEnable(GL_DEPTH_TEST);
1505 }
1506
1507 void RAS_OpenGLRasterizer::RenderText3D(
1508         int fontid, const char *text, int size, int dpi,
1509         const float color[4], const float mat[16], float aspect)
1510 {
1511         /* gl prepping */
1512         DisableForText();
1513
1514         /* the actual drawing */
1515         glColor4fv(color);
1516
1517         /* multiply the text matrix by the object matrix */
1518         BLF_enable(fontid, BLF_MATRIX|BLF_ASPECT);
1519         BLF_matrix(fontid, mat);
1520
1521         /* aspect is the inverse scale that allows you to increase */
1522         /* your resolution without sizing the final text size      */
1523         /* the bigger the size, the smaller the aspect             */
1524         BLF_aspect(fontid, aspect, aspect, aspect);
1525
1526         BLF_size(fontid, size, dpi);
1527         BLF_position(fontid, 0, 0, 0);
1528         BLF_draw(fontid, text, 65535);
1529
1530         BLF_disable(fontid, BLF_MATRIX|BLF_ASPECT);
1531 }
1532
1533 void RAS_OpenGLRasterizer::RenderText2D(
1534         RAS_TEXT_RENDER_MODE mode,
1535         const char* text,
1536         int xco, int yco,
1537         int width, int height)
1538 {
1539         /* This is a rather important line :( The gl-mode hasn't been left
1540          * behind quite as neatly as we'd have wanted to. I don't know
1541          * what cause it, though :/ .*/
1542         DisableForText();
1543         glDisable(GL_DEPTH_TEST);
1544
1545         glMatrixMode(GL_PROJECTION);
1546         glPushMatrix();
1547         glLoadIdentity();
1548
1549         glOrtho(0, width, 0, height, -100, 100);
1550
1551         glMatrixMode(GL_MODELVIEW);
1552         glPushMatrix();
1553         glLoadIdentity();
1554
1555         if (mode == RAS_TEXT_PADDED) {
1556                 /* draw in black first*/
1557                 glColor3ub(0, 0, 0);
1558                 BLF_size(blf_mono_font, 11, 72);
1559                 BLF_position(blf_mono_font, (float)xco+1, (float)(height-yco-1), 0.0f);
1560                 BLF_draw(blf_mono_font, text, 65535); /* XXX, use real len */
1561         }
1562
1563         /* the actual drawing */
1564         glColor3ub(255, 255, 255);
1565         BLF_size(blf_mono_font, 11, 72);
1566         BLF_position(blf_mono_font, (float)xco, (float)(height-yco), 0.0f);
1567         BLF_draw(blf_mono_font, text, 65535); /* XXX, use real len */
1568
1569         glMatrixMode(GL_PROJECTION);
1570         glPopMatrix();
1571         glMatrixMode(GL_MODELVIEW);
1572         glPopMatrix();
1573         glEnable(GL_DEPTH_TEST);
1574 }
1575
1576 void RAS_OpenGLRasterizer::PushMatrix()
1577 {
1578         glPushMatrix();
1579 }
1580
1581 void RAS_OpenGLRasterizer::PopMatrix()
1582 {
1583         glPopMatrix();
1584 }
1585
1586 void RAS_OpenGLRasterizer::MotionBlur()
1587 {
1588         int state = GetMotionBlurState();
1589         float motionblurvalue;
1590         if (state)
1591         {
1592                 motionblurvalue = GetMotionBlurValue();
1593                 if (state==1)
1594                 {
1595                         //bugfix:load color buffer into accum buffer for the first time(state=1)
1596                         glAccum(GL_LOAD, 1.0f);
1597                         SetMotionBlurState(2);
1598                 }
1599                 else if (motionblurvalue >= 0.0f && motionblurvalue <= 1.0f) {
1600                         glAccum(GL_MULT, motionblurvalue);
1601                         glAccum(GL_ACCUM, 1-motionblurvalue);
1602                         glAccum(GL_RETURN, 1.0f);
1603                         glFlush();
1604                 }
1605         }
1606 }
1607
1608 void RAS_OpenGLRasterizer::SetClientObject(void* obj)
1609 {
1610         if (m_clientobject != obj)
1611         {
1612                 bool ccw = (obj == NULL || !((KX_GameObject*)obj)->IsNegativeScaling());
1613                 SetFrontFace(ccw);
1614
1615                 m_clientobject = obj;
1616         }
1617 }
1618
1619 void RAS_OpenGLRasterizer::SetAuxilaryClientInfo(void* inf)
1620 {
1621         m_auxilaryClientInfo = inf;
1622 }
1623
1624 void RAS_OpenGLRasterizer::PrintHardwareInfo()
1625 {
1626         #define pprint(x) std::cout << x << std::endl;
1627
1628         pprint("GL_VENDOR: " << glGetString(GL_VENDOR));
1629         pprint("GL_RENDERER: " << glGetString(GL_RENDERER));
1630         pprint("GL_VERSION:  " << glGetString(GL_VERSION));
1631         bool support=0;
1632         pprint("Supported Extensions...");
1633         pprint(" GL_ARB_shader_objects supported?       "<< (GLEW_ARB_shader_objects?"yes.":"no."));
1634
1635         support= GLEW_ARB_vertex_shader;
1636         pprint(" GL_ARB_vertex_shader supported?        "<< (support?"yes.":"no."));
1637         if (support) {
1638                 pprint(" ----------Details----------");
1639                 int max=0;
1640                 glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB, (GLint*)&max);
1641                 pprint("  Max uniform components." << max);
1642
1643                 glGetIntegerv(GL_MAX_VARYING_FLOATS_ARB, (GLint*)&max);
1644                 pprint("  Max varying floats." << max);
1645
1646                 glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB, (GLint*)&max);
1647                 pprint("  Max vertex texture units." << max);
1648
1649                 glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB, (GLint*)&max);
1650                 pprint("  Max combined texture units." << max);
1651                 pprint("");
1652         }
1653
1654         support=GLEW_ARB_fragment_shader;
1655         pprint(" GL_ARB_fragment_shader supported?      "<< (support?"yes.":"no."));
1656         if (support) {
1657                 pprint(" ----------Details----------");
1658                 int max=0;
1659                 glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB, (GLint*)&max);
1660                 pprint("  Max uniform components." << max);
1661                 pprint("");
1662         }
1663
1664         support = GLEW_ARB_texture_cube_map;
1665         pprint(" GL_ARB_texture_cube_map supported?     "<< (support?"yes.":"no."));
1666         if (support) {
1667                 pprint(" ----------Details----------");
1668                 int size=0;
1669                 glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB, (GLint*)&size);
1670                 pprint("  Max cubemap size." << size);
1671                 pprint("");
1672         }
1673
1674         support = GLEW_ARB_multitexture;
1675         pprint(" GL_ARB_multitexture supported?         "<< (support?"yes.":"no."));
1676         if (support) {
1677                 pprint(" ----------Details----------");
1678                 int units=0;
1679                 glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, (GLint*)&units);
1680                 pprint("  Max texture units available.  " << units);
1681                 pprint("");
1682         }
1683
1684         pprint(" GL_ARB_texture_env_combine supported?  "<< (GLEW_ARB_texture_env_combine?"yes.":"no."));
1685
1686         pprint(" GL_ARB_texture_non_power_of_two supported  " << (GPU_full_non_power_of_two_support()?"yes.":"no."));
1687 }
1688