Bugfix:
[blender.git] / source / gameengine / Rasterizer / RAS_OpenGLRasterizer / RAS_OpenGLRasterizer.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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 /** \file gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp
30  *  \ingroup bgerastogl
31  */
32
33  
34 #include <math.h>
35 #include <stdlib.h>
36  
37 #include "RAS_OpenGLRasterizer.h"
38
39 #include "GL/glew.h"
40
41 #include "RAS_Rect.h"
42 #include "RAS_TexVert.h"
43 #include "RAS_MeshObject.h"
44 #include "MT_CmMatrix4x4.h"
45 #include "RAS_IRenderTools.h" // rendering text
46
47 #include "GPU_draw.h"
48 #include "GPU_material.h"
49 #include "GPU_extensions.h"
50
51 #include "DNA_image_types.h"
52 #include "DNA_meshdata_types.h"
53 #include "DNA_material_types.h"
54 #include "DNA_scene_types.h"
55
56 #include "BKE_DerivedMesh.h"
57
58 /**
59  *  32x32 bit masks for vinterlace stereo mode
60  */
61 static GLuint left_eye_vinterlace_mask[32];
62 static GLuint right_eye_vinterlace_mask[32];
63
64 /**
65  *  32x32 bit masks for hinterlace stereo mode.
66  *  Left eye = &hinterlace_mask[0]
67  *  Right eye = &hinterlace_mask[1]
68  */
69 static GLuint hinterlace_mask[33];
70
71 RAS_OpenGLRasterizer::RAS_OpenGLRasterizer(RAS_ICanvas* canvas)
72         :RAS_IRasterizer(canvas),
73         m_2DCanvas(canvas),
74         m_fogenabled(false),
75         m_time(0.0),
76         m_campos(0.0f, 0.0f, 0.0f),
77         m_camortho(false),
78         m_stereomode(RAS_STEREO_NOSTEREO),
79         m_curreye(RAS_STEREO_LEFTEYE),
80         m_eyeseparation(0.0),
81         m_focallength(0.0),
82         m_setfocallength(false),
83         m_noOfScanlines(32),
84         m_motionblur(0),
85         m_motionblurvalue(-1.0),
86         m_texco_num(0),
87         m_attrib_num(0),
88         //m_last_blendmode(GPU_BLEND_SOLID),
89         m_last_frontface(true),
90         m_materialCachingInfo(0)
91 {
92         m_viewmatrix.setIdentity();
93         m_viewinvmatrix.setIdentity();
94         
95         for (int i = 0; i < 32; i++)
96         {
97                 left_eye_vinterlace_mask[i] = 0x55555555;
98                 right_eye_vinterlace_mask[i] = 0xAAAAAAAA;
99                 hinterlace_mask[i] = (i&1)*0xFFFFFFFF;
100         }
101         hinterlace_mask[32] = 0;
102 }
103
104
105
106 RAS_OpenGLRasterizer::~RAS_OpenGLRasterizer()
107 {
108 }
109
110 bool RAS_OpenGLRasterizer::Init()
111 {
112         GPU_state_init();
113
114
115         m_ambr = 0.0f;
116         m_ambg = 0.0f;
117         m_ambb = 0.0f;
118
119         glDisable(GL_BLEND);
120         glDisable(GL_ALPHA_TEST);
121         //m_last_blendmode = GPU_BLEND_SOLID;
122         GPU_set_material_blend_mode(GPU_BLEND_SOLID);
123
124         glFrontFace(GL_CCW);
125         m_last_frontface = true;
126
127         glClearColor(m_redback,m_greenback,m_blueback,m_alphaback);
128         glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
129         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
130
131
132         m_redback = 0.4375;
133         m_greenback = 0.4375;
134         m_blueback = 0.4375;
135         m_alphaback = 0.0;
136
137         glShadeModel(GL_SMOOTH);
138
139         return true;
140 }
141
142
143 void RAS_OpenGLRasterizer::SetAmbientColor(float red, float green, float blue)
144 {
145         m_ambr = red;
146         m_ambg = green;
147         m_ambb = blue;
148 }
149
150
151 void RAS_OpenGLRasterizer::SetAmbient(float factor)
152 {
153         float ambient[] = { m_ambr*factor, m_ambg*factor, m_ambb*factor, 1.0f };
154         glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient);
155 }
156
157
158 void RAS_OpenGLRasterizer::SetBackColor(float red,
159                                                                                 float green,
160                                                                                 float blue,
161                                                                                 float alpha)
162 {
163         m_redback = red;
164         m_greenback = green;
165         m_blueback = blue;
166         m_alphaback = alpha;
167 }
168
169
170
171 void RAS_OpenGLRasterizer::SetFogColor(float r,
172                                                                            float g,
173                                                                            float b)
174 {
175         m_fogr = r;
176         m_fogg = g;
177         m_fogb = b;
178         m_fogenabled = true;
179 }
180
181
182
183 void RAS_OpenGLRasterizer::SetFogStart(float start)
184 {
185         m_fogstart = start;
186         m_fogenabled = true;
187 }
188
189
190
191 void RAS_OpenGLRasterizer::SetFogEnd(float fogend)
192 {
193         m_fogdist = fogend;
194         m_fogenabled = true;
195 }
196
197
198
199 void RAS_OpenGLRasterizer::SetFog(float start,
200                                                                   float dist,
201                                                                   float r,
202                                                                   float g,
203                                                                   float b)
204 {
205         m_fogstart = start;
206         m_fogdist = dist;
207         m_fogr = r;
208         m_fogg = g;
209         m_fogb = b;
210         m_fogenabled = true;
211 }
212
213
214
215 void RAS_OpenGLRasterizer::DisableFog()
216 {
217         m_fogenabled = false;
218 }
219
220 bool RAS_OpenGLRasterizer::IsFogEnabled()
221 {
222         return m_fogenabled;
223 }
224
225
226 void RAS_OpenGLRasterizer::DisplayFog()
227 {
228         if ((m_drawingmode >= KX_SOLID) && m_fogenabled)
229         {
230                 float params[5];
231                 glFogi(GL_FOG_MODE, GL_LINEAR);
232                 glFogf(GL_FOG_DENSITY, 0.1f);
233                 glFogf(GL_FOG_START, m_fogstart);
234                 glFogf(GL_FOG_END, m_fogstart + m_fogdist);
235                 params[0]= m_fogr;
236                 params[1]= m_fogg;
237                 params[2]= m_fogb;
238                 params[3]= 0.0;
239                 glFogfv(GL_FOG_COLOR, params); 
240                 glEnable(GL_FOG);
241         } 
242         else
243         {
244                 glDisable(GL_FOG);
245         }
246 }
247
248
249
250 bool RAS_OpenGLRasterizer::SetMaterial(const RAS_IPolyMaterial& mat)
251 {
252         return mat.Activate(this, m_materialCachingInfo);
253 }
254
255
256
257 void RAS_OpenGLRasterizer::Exit()
258 {
259
260         glEnable(GL_CULL_FACE);
261         glEnable(GL_DEPTH_TEST);
262         glClearDepth(1.0); 
263         glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
264         glClearColor(m_redback, m_greenback, m_blueback, m_alphaback);
265         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
266         glDepthMask (GL_TRUE);
267         glDepthFunc(GL_LEQUAL);
268         glBlendFunc(GL_ONE, GL_ZERO);
269         
270         glDisable(GL_POLYGON_STIPPLE);
271         
272         glDisable(GL_LIGHTING);
273         if (GLEW_EXT_separate_specular_color || GLEW_VERSION_1_2)
274                 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
275         
276         EndFrame();
277 }
278
279 bool RAS_OpenGLRasterizer::BeginFrame(int drawingmode, double time)
280 {
281         m_time = time;
282         m_drawingmode = drawingmode;
283
284         // Blender camera routine destroys the settings
285         if (m_drawingmode < KX_SOLID)
286         {
287                 glDisable (GL_CULL_FACE);
288                 glDisable (GL_DEPTH_TEST);
289         }
290         else
291         {
292                 glEnable(GL_DEPTH_TEST);
293                 glEnable (GL_CULL_FACE);
294         }
295
296         glDisable(GL_BLEND);
297         glDisable(GL_ALPHA_TEST);
298         //m_last_blendmode = GPU_BLEND_SOLID;
299         GPU_set_material_blend_mode(GPU_BLEND_SOLID);
300
301         glFrontFace(GL_CCW);
302         m_last_frontface = true;
303
304         glShadeModel(GL_SMOOTH);
305
306         m_2DCanvas->BeginFrame();
307         
308         return true;
309 }
310
311
312
313 void RAS_OpenGLRasterizer::SetDrawingMode(int drawingmode)
314 {
315         m_drawingmode = drawingmode;
316
317         if(m_drawingmode == KX_WIREFRAME)
318                 glDisable(GL_CULL_FACE);
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::FlushDebugLines()
352 {
353         if(!m_debugLines.size())
354                 return;
355
356         // DrawDebugLines
357         GLboolean light, tex;
358
359         light= glIsEnabled(GL_LIGHTING);
360         tex= glIsEnabled(GL_TEXTURE_2D);
361
362         if(light) glDisable(GL_LIGHTING);
363         if(tex) glDisable(GL_TEXTURE_2D);
364
365         glBegin(GL_LINES);
366         for (unsigned int i=0;i<m_debugLines.size();i++)
367         {
368                 glColor4f(m_debugLines[i].m_color[0],m_debugLines[i].m_color[1],m_debugLines[i].m_color[2],1.f);
369                 const MT_Scalar* fromPtr = &m_debugLines[i].m_from.x();
370                 const MT_Scalar* toPtr= &m_debugLines[i].m_to.x();
371
372                 glVertex3dv(fromPtr);
373                 glVertex3dv(toPtr);
374         }
375         glEnd();
376
377         if(light) glEnable(GL_LIGHTING);
378         if(tex) glEnable(GL_TEXTURE_2D);
379
380         m_debugLines.clear();
381 }
382
383 void RAS_OpenGLRasterizer::EndFrame()
384 {
385         
386
387         FlushDebugLines();
388
389         glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
390         m_2DCanvas->EndFrame();
391 }       
392
393 void RAS_OpenGLRasterizer::SetRenderArea()
394 {
395         RAS_Rect area;
396         // only above/below stereo method needs viewport adjustment
397         switch (m_stereomode)
398         {
399                 case RAS_STEREO_ABOVEBELOW:
400                         switch(m_curreye)
401                         {
402                                 case RAS_STEREO_LEFTEYE:
403                                         // upper half of window
404                                         area.SetLeft(0);
405                                         area.SetBottom(m_2DCanvas->GetHeight() -
406                                                 int(m_2DCanvas->GetHeight() - m_noOfScanlines) / 2);
407         
408                                         area.SetRight(int(m_2DCanvas->GetWidth()));
409                                         area.SetTop(int(m_2DCanvas->GetHeight()));
410                                         m_2DCanvas->SetDisplayArea(&area);
411                                         break;
412                                 case RAS_STEREO_RIGHTEYE:
413                                         // lower half of window
414                                         area.SetLeft(0);
415                                         area.SetBottom(0);
416                                         area.SetRight(int(m_2DCanvas->GetWidth()));
417                                         area.SetTop(int(m_2DCanvas->GetHeight() - m_noOfScanlines) / 2);
418                                         m_2DCanvas->SetDisplayArea(&area);
419                                         break;
420                         }
421                         break;
422                 case RAS_STEREO_SIDEBYSIDE:
423                         switch (m_curreye)
424                         {
425                                 case RAS_STEREO_LEFTEYE:
426                                         // Left half of window
427                                         area.SetLeft(0);
428                                         area.SetBottom(0);
429                                         area.SetRight(m_2DCanvas->GetWidth()/2);
430                                         area.SetTop(m_2DCanvas->GetHeight());
431                                         m_2DCanvas->SetDisplayArea(&area);
432                                         break;
433                                 case RAS_STEREO_RIGHTEYE:
434                                         // Right half of window
435                                         area.SetLeft(m_2DCanvas->GetWidth()/2);
436                                         area.SetBottom(0);
437                                         area.SetRight(m_2DCanvas->GetWidth());
438                                         area.SetTop(m_2DCanvas->GetHeight());
439                                         m_2DCanvas->SetDisplayArea(&area);
440                                         break;
441                         }
442                         break;
443                 default:
444                         // every available pixel
445                         area.SetLeft(0);
446                         area.SetBottom(0);
447                         area.SetRight(int(m_2DCanvas->GetWidth()));
448                         area.SetTop(int(m_2DCanvas->GetHeight()));
449                         m_2DCanvas->SetDisplayArea(&area);
450                         break;
451         }
452 }
453         
454 void RAS_OpenGLRasterizer::SetStereoMode(const StereoMode stereomode)
455 {
456         m_stereomode = stereomode;
457 }
458
459 RAS_IRasterizer::StereoMode RAS_OpenGLRasterizer::GetStereoMode()
460 {
461         return m_stereomode;
462 }
463
464 bool RAS_OpenGLRasterizer::Stereo()
465 {
466         if(m_stereomode > RAS_STEREO_NOSTEREO) // > 0
467                 return true;
468         else
469                 return false;
470 }
471
472 bool RAS_OpenGLRasterizer::InterlacedStereo()
473 {
474         return m_stereomode == RAS_STEREO_VINTERLACE || m_stereomode == RAS_STEREO_INTERLACED;
475 }
476
477 void RAS_OpenGLRasterizer::SetEye(const StereoEye eye)
478 {
479         m_curreye = eye;
480         switch (m_stereomode)
481         {
482                 case RAS_STEREO_QUADBUFFERED:
483                         glDrawBuffer(m_curreye == RAS_STEREO_LEFTEYE ? GL_BACK_LEFT : GL_BACK_RIGHT);
484                         break;
485                 case RAS_STEREO_ANAGLYPH:
486                         if (m_curreye == RAS_STEREO_LEFTEYE)
487                         {
488                                 glColorMask(GL_FALSE, GL_TRUE, GL_TRUE, GL_FALSE);
489                         } else {
490                                 //glAccum(GL_LOAD, 1.0);
491                                 glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_FALSE);
492                                 ClearDepthBuffer();
493                         }
494                         break;
495                 case RAS_STEREO_VINTERLACE:
496                 {
497                         glEnable(GL_POLYGON_STIPPLE);
498                         glPolygonStipple((const GLubyte*) ((m_curreye == RAS_STEREO_LEFTEYE) ? left_eye_vinterlace_mask : right_eye_vinterlace_mask));
499                         if (m_curreye == RAS_STEREO_RIGHTEYE)
500                                 ClearDepthBuffer();
501                         break;
502                 }
503                 case RAS_STEREO_INTERLACED:
504                 {
505                         glEnable(GL_POLYGON_STIPPLE);
506                         glPolygonStipple((const GLubyte*) &hinterlace_mask[m_curreye == RAS_STEREO_LEFTEYE?0:1]);
507                         if (m_curreye == RAS_STEREO_RIGHTEYE)
508                                 ClearDepthBuffer();
509                         break;
510                 }
511                 default:
512                         break;
513         }
514 }
515
516 RAS_IRasterizer::StereoEye RAS_OpenGLRasterizer::GetEye()
517 {
518         return m_curreye;
519 }
520
521
522 void RAS_OpenGLRasterizer::SetEyeSeparation(const float eyeseparation)
523 {
524         m_eyeseparation = eyeseparation;
525 }
526
527 float RAS_OpenGLRasterizer::GetEyeSeparation()
528 {
529         return m_eyeseparation;
530 }
531
532 void RAS_OpenGLRasterizer::SetFocalLength(const float focallength)
533 {
534         m_focallength = focallength;
535         m_setfocallength = true;
536 }
537
538 float RAS_OpenGLRasterizer::GetFocalLength()
539 {
540         return m_focallength;
541 }
542
543
544 void RAS_OpenGLRasterizer::SwapBuffers()
545 {
546         m_2DCanvas->SwapBuffers();
547 }
548
549
550
551 const MT_Matrix4x4& RAS_OpenGLRasterizer::GetViewMatrix() const
552 {
553         return m_viewmatrix;
554 }
555
556 const MT_Matrix4x4& RAS_OpenGLRasterizer::GetViewInvMatrix() const
557 {
558         return m_viewinvmatrix;
559 }
560
561 void RAS_OpenGLRasterizer::IndexPrimitives_3DText(RAS_MeshSlot& ms,
562                                                                         class RAS_IPolyMaterial* polymat,
563                                                                         class RAS_IRenderTools* rendertools)
564
565         bool obcolor = ms.m_bObjectColor;
566         MT_Vector4& rgba = ms.m_RGBAcolor;
567         RAS_MeshSlot::iterator it;
568
569         // handle object color
570         if (obcolor) {
571                 glDisableClientState(GL_COLOR_ARRAY);
572                 glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]);
573         }
574         else
575                 glEnableClientState(GL_COLOR_ARRAY);
576
577         for(ms.begin(it); !ms.end(it); ms.next(it)) {
578                 RAS_TexVert *vertex;
579                 size_t i, j, numvert;
580                 
581                 numvert = it.array->m_type;
582
583                 if(it.array->m_type == RAS_DisplayArray::LINE) {
584                         // line drawing, no text
585                         glBegin(GL_LINES);
586
587                         for(i=0; i<it.totindex; i+=2)
588                         {
589                                 vertex = &it.vertex[it.index[i]];
590                                 glVertex3fv(vertex->getXYZ());
591
592                                 vertex = &it.vertex[it.index[i+1]];
593                                 glVertex3fv(vertex->getXYZ());
594                         }
595
596                         glEnd();
597                 }
598                 else {
599                         // triangle and quad text drawing
600                         for(i=0; i<it.totindex; i+=numvert)
601                         {
602                                 float v[4][3];
603                                 int glattrib, unit;
604
605                                 for(j=0; j<numvert; j++) {
606                                         vertex = &it.vertex[it.index[i+j]];
607
608                                         v[j][0] = vertex->getXYZ()[0];
609                                         v[j][1] = vertex->getXYZ()[1];
610                                         v[j][2] = vertex->getXYZ()[2];
611                                 }
612
613                                 // find the right opengl attribute
614                                 glattrib = -1;
615                                 if(GLEW_ARB_vertex_program)
616                                         for(unit=0; unit<m_attrib_num; unit++)
617                                                 if(m_attrib[unit] == RAS_TEXCO_UV1)
618                                                         glattrib = unit;
619                                 
620                                 rendertools->RenderText(polymat->GetDrawingMode(), polymat,
621                                         v[0], v[1], v[2], (numvert == 4)? v[3]: NULL, glattrib);
622
623                                 ClearCachingInfo();
624                         }
625                 }
626         }
627
628         glDisableClientState(GL_COLOR_ARRAY);
629 }
630
631 void RAS_OpenGLRasterizer::SetTexCoordNum(int num)
632 {
633         m_texco_num = num;
634         if(m_texco_num > RAS_MAX_TEXCO)
635                 m_texco_num = RAS_MAX_TEXCO;
636 }
637
638 void RAS_OpenGLRasterizer::SetAttribNum(int num)
639 {
640         m_attrib_num = num;
641         if(m_attrib_num > RAS_MAX_ATTRIB)
642                 m_attrib_num = RAS_MAX_ATTRIB;
643 }
644
645 void RAS_OpenGLRasterizer::SetTexCoord(TexCoGen coords, int unit)
646 {
647         // this changes from material to material
648         if(unit < RAS_MAX_TEXCO)
649                 m_texco[unit] = coords;
650 }
651
652 void RAS_OpenGLRasterizer::SetAttrib(TexCoGen coords, int unit)
653 {
654         // this changes from material to material
655         if(unit < RAS_MAX_ATTRIB)
656                 m_attrib[unit] = coords;
657 }
658
659 void RAS_OpenGLRasterizer::TexCoord(const RAS_TexVert &tv)
660 {
661         int unit;
662
663         if(GLEW_ARB_multitexture) {
664                 for(unit=0; unit<m_texco_num; unit++) {
665                         if(tv.getFlag() & RAS_TexVert::SECOND_UV && (int)tv.getUnit() == unit) {
666                                 glMultiTexCoord2fvARB(GL_TEXTURE0_ARB+unit, tv.getUV2());
667                                 continue;
668                         }
669                         switch(m_texco[unit]) {
670                         case RAS_TEXCO_ORCO:
671                         case RAS_TEXCO_GLOB:
672                                 glMultiTexCoord3fvARB(GL_TEXTURE0_ARB+unit, tv.getXYZ());
673                                 break;
674                         case RAS_TEXCO_UV1:
675                                 glMultiTexCoord2fvARB(GL_TEXTURE0_ARB+unit, tv.getUV1());
676                                 break;
677                         case RAS_TEXCO_NORM:
678                                 glMultiTexCoord3fvARB(GL_TEXTURE0_ARB+unit, tv.getNormal());
679                                 break;
680                         case RAS_TEXTANGENT:
681                                 glMultiTexCoord4fvARB(GL_TEXTURE0_ARB+unit, tv.getTangent());
682                                 break;
683                         case RAS_TEXCO_UV2:
684                                 glMultiTexCoord2fvARB(GL_TEXTURE0_ARB+unit, tv.getUV2());
685                                 break;
686                         default:
687                                 break;
688                         }
689                 }
690         }
691
692         if(GLEW_ARB_vertex_program) {
693                 for(unit=0; unit<m_attrib_num; unit++) {
694                         switch(m_attrib[unit]) {
695                         case RAS_TEXCO_ORCO:
696                         case RAS_TEXCO_GLOB:
697                                 glVertexAttrib3fvARB(unit, tv.getXYZ());
698                                 break;
699                         case RAS_TEXCO_UV1:
700                                 glVertexAttrib2fvARB(unit, tv.getUV1());
701                                 break;
702                         case RAS_TEXCO_NORM:
703                                 glVertexAttrib3fvARB(unit, tv.getNormal());
704                                 break;
705                         case RAS_TEXTANGENT:
706                                 glVertexAttrib4fvARB(unit, tv.getTangent());
707                                 break;
708                         case RAS_TEXCO_UV2:
709                                 glVertexAttrib2fvARB(unit, tv.getUV2());
710                                 break;
711                         case RAS_TEXCO_VCOL:
712                                 glVertexAttrib4ubvARB(unit, tv.getRGBA());
713                                 break;
714                         default:
715                                 break;
716                         }
717                 }
718         }
719
720 }
721
722 void RAS_OpenGLRasterizer::IndexPrimitives(RAS_MeshSlot& ms)
723 {
724         IndexPrimitivesInternal(ms, false);
725 }
726
727 void RAS_OpenGLRasterizer::IndexPrimitivesMulti(RAS_MeshSlot& ms)
728 {
729         IndexPrimitivesInternal(ms, true);
730 }
731
732 static bool current_wireframe;
733 static RAS_MaterialBucket *current_bucket;
734 static RAS_IPolyMaterial *current_polymat;
735 static RAS_MeshSlot *current_ms;
736 static RAS_MeshObject *current_mesh;
737 static int current_blmat_nr;
738 static GPUVertexAttribs current_gpu_attribs;
739 static Image *current_image;
740 static int CheckMaterialDM(int matnr, void *attribs)
741 {
742         // only draw the current material
743         if (matnr != current_blmat_nr)
744                 return 0;
745         GPUVertexAttribs *gattribs = (GPUVertexAttribs *)attribs;
746         if (gattribs)
747                 memcpy(gattribs, &current_gpu_attribs, sizeof(GPUVertexAttribs));
748         return 1;
749 }
750
751 /*
752 static int CheckTexfaceDM(void *mcol, int index)
753 {
754
755         // index is the original face index, retrieve the polygon
756         RAS_Polygon* polygon = (index >= 0 && index < current_mesh->NumPolygons()) ?
757                 current_mesh->GetPolygon(index) : NULL;
758         if (polygon && polygon->GetMaterial() == current_bucket) {
759                 // must handle color.
760                 if (current_wireframe)
761                         return 2;
762                 if (current_ms->m_bObjectColor) {
763                         MT_Vector4& rgba = current_ms->m_RGBAcolor;
764                         glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]);
765                         // don't use mcol
766                         return 2;
767                 }
768                 if (!mcol) {
769                         // we have to set the color from the material
770                         unsigned char rgba[4];
771                         current_polymat->GetMaterialRGBAColor(rgba);
772                         glColor4ubv((const GLubyte *)rgba);
773                         return 2;
774                 }
775                 return 1;
776         }
777         return 0;
778 }
779 */
780
781 static int CheckTexDM(MTFace *tface, MCol *mcol, int matnr)
782 {
783
784         // index is the original face index, retrieve the polygon
785         if (matnr == current_blmat_nr &&
786                 (tface == NULL || tface->tpage == current_image)) {
787                 // must handle color.
788                 if (current_wireframe)
789                         return 2;
790                 if (current_ms->m_bObjectColor) {
791                         MT_Vector4& rgba = current_ms->m_RGBAcolor;
792                         glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]);
793                         // don't use mcol
794                         return 2;
795                 }
796                 if (!mcol) {
797                         // we have to set the color from the material
798                         unsigned char rgba[4];
799                         current_polymat->GetMaterialRGBAColor(rgba);
800                         glColor4ubv((const GLubyte *)rgba);
801                         return 2;
802                 }
803                 return 1;
804         }
805         return 0;
806 }
807
808 void RAS_OpenGLRasterizer::IndexPrimitivesInternal(RAS_MeshSlot& ms, bool multi)
809
810         bool obcolor = ms.m_bObjectColor;
811         bool wireframe = m_drawingmode <= KX_WIREFRAME;
812         MT_Vector4& rgba = ms.m_RGBAcolor;
813         RAS_MeshSlot::iterator it;
814
815         if (ms.m_pDerivedMesh) {
816                 // mesh data is in derived mesh, 
817                 current_bucket = ms.m_bucket;
818                 current_polymat = current_bucket->GetPolyMaterial();
819                 current_ms = &ms;
820                 current_mesh = ms.m_mesh;
821                 current_wireframe = wireframe;
822                 // MCol *mcol = (MCol*)ms.m_pDerivedMesh->getFaceDataArray(ms.m_pDerivedMesh, CD_MCOL); /* UNUSED */
823
824                 // handle two-side
825                 if (current_polymat->GetDrawingMode() & RAS_IRasterizer::KX_TWOSIDE)
826                         this->SetCullFace(false);
827                 else
828                         this->SetCullFace(true);
829
830                 if (current_polymat->GetFlag() & RAS_BLENDERGLSL) {
831                         // GetMaterialIndex return the original mface material index, 
832                         // increment by 1 to match what derived mesh is doing
833                         current_blmat_nr = current_polymat->GetMaterialIndex()+1;
834                         // For GLSL we need to retrieve the GPU material attribute
835                         Material* blmat = current_polymat->GetBlenderMaterial();
836                         Scene* blscene = current_polymat->GetBlenderScene();
837                         if (!wireframe && blscene && blmat)
838                                 GPU_material_vertex_attributes(GPU_material_from_blender(blscene, blmat), &current_gpu_attribs);
839                         else
840                                 memset(&current_gpu_attribs, 0, sizeof(current_gpu_attribs));
841                         // DM draw can mess up blending mode, restore at the end
842                         int current_blend_mode = GPU_get_material_blend_mode();
843                         ms.m_pDerivedMesh->drawFacesGLSL(ms.m_pDerivedMesh, CheckMaterialDM);
844                         GPU_set_material_blend_mode(current_blend_mode);
845                 } else {
846                         //ms.m_pDerivedMesh->drawMappedFacesTex(ms.m_pDerivedMesh, CheckTexfaceDM, mcol);
847                         current_blmat_nr = current_polymat->GetMaterialIndex();
848                         current_image = current_polymat->GetBlenderImage();
849                         ms.m_pDerivedMesh->drawFacesTex(ms.m_pDerivedMesh, CheckTexDM);
850                 }
851                 return;
852         }
853         // iterate over display arrays, each containing an index + vertex array
854         for(ms.begin(it); !ms.end(it); ms.next(it)) {
855                 RAS_TexVert *vertex;
856                 size_t i, j, numvert;
857                 
858                 numvert = it.array->m_type;
859
860                 if(it.array->m_type == RAS_DisplayArray::LINE) {
861                         // line drawing
862                         glBegin(GL_LINES);
863
864                         for(i=0; i<it.totindex; i+=2)
865                         {
866                                 vertex = &it.vertex[it.index[i]];
867                                 glVertex3fv(vertex->getXYZ());
868
869                                 vertex = &it.vertex[it.index[i+1]];
870                                 glVertex3fv(vertex->getXYZ());
871                         }
872
873                         glEnd();
874                 }
875                 else {
876                         // triangle and quad drawing
877                         if(it.array->m_type == RAS_DisplayArray::TRIANGLE)
878                                 glBegin(GL_TRIANGLES);
879                         else
880                                 glBegin(GL_QUADS);
881
882                         for(i=0; i<it.totindex; i+=numvert)
883                         {
884                                 if(obcolor)
885                                         glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]);
886
887                                 for(j=0; j<numvert; j++) {
888                                         vertex = &it.vertex[it.index[i+j]];
889
890                                         if(!wireframe) {
891                                                 if(!obcolor)
892                                                         glColor4ubv((const GLubyte *)(vertex->getRGBA()));
893
894                                                 glNormal3fv(vertex->getNormal());
895
896                                                 if(multi)
897                                                         TexCoord(*vertex);
898                                                 else
899                                                         glTexCoord2fv(vertex->getUV1());
900                                         }
901
902                                         glVertex3fv(vertex->getXYZ());
903                                 }
904                         }
905
906                         glEnd();
907                 }
908         }
909 }
910
911 void RAS_OpenGLRasterizer::SetProjectionMatrix(MT_CmMatrix4x4 &mat)
912 {
913         glMatrixMode(GL_PROJECTION);
914         double* matrix = &mat(0,0);
915         glLoadMatrixd(matrix);
916
917         m_camortho= (mat(3, 3) != 0.0f);
918 }
919
920 void RAS_OpenGLRasterizer::SetProjectionMatrix(const MT_Matrix4x4 & mat)
921 {
922         glMatrixMode(GL_PROJECTION);
923         double matrix[16];
924         /* Get into argument. Looks a bit dodgy, but it's ok. */
925         mat.getValue(matrix);
926         /* Internally, MT_Matrix4x4 uses doubles (MT_Scalar). */
927         glLoadMatrixd(matrix);  
928
929         m_camortho= (mat[3][3] != 0.0f);
930 }
931
932 MT_Matrix4x4 RAS_OpenGLRasterizer::GetFrustumMatrix(
933         float left,
934         float right,
935         float bottom,
936         float top,
937         float frustnear,
938         float frustfar,
939         float focallength,
940         bool 
941 ){
942         MT_Matrix4x4 result;
943         double mat[16];
944
945         // correction for stereo
946         if(Stereo())
947         {
948                         float near_div_focallength;
949                         float offset;
950
951                         // if Rasterizer.setFocalLength is not called we use the camera focallength
952                         if (!m_setfocallength)
953                                 // if focallength is null we use a value known to be reasonable
954                                 m_focallength = (focallength == 0.f) ? m_eyeseparation * 30.0
955                                         : focallength;
956
957                         near_div_focallength = frustnear / m_focallength;
958                         offset = 0.5 * m_eyeseparation * near_div_focallength;
959                         switch(m_curreye)
960                         {
961                                 case RAS_STEREO_LEFTEYE:
962                                                 left += offset;
963                                                 right += offset;
964                                                 break;
965                                 case RAS_STEREO_RIGHTEYE:
966                                                 left -= offset;
967                                                 right -= offset;
968                                                 break;
969                         }
970                         // leave bottom and top untouched
971         }
972         
973         glMatrixMode(GL_PROJECTION);
974         glLoadIdentity();
975         glFrustum(left, right, bottom, top, frustnear, frustfar);
976                 
977         glGetDoublev(GL_PROJECTION_MATRIX, mat);
978         result.setValue(mat);
979
980         return result;
981 }
982
983 MT_Matrix4x4 RAS_OpenGLRasterizer::GetOrthoMatrix(
984         float left,
985         float right,
986         float bottom,
987         float top,
988         float frustnear,
989         float frustfar
990 ){
991         MT_Matrix4x4 result;
992         double mat[16];
993
994         // stereo is meaning less for orthographic, disable it
995         glMatrixMode(GL_PROJECTION);
996         glLoadIdentity();
997         glOrtho(left, right, bottom, top, frustnear, frustfar);
998                 
999         glGetDoublev(GL_PROJECTION_MATRIX, mat);
1000         result.setValue(mat);
1001
1002         return result;
1003 }
1004
1005
1006 // next arguments probably contain redundant info, for later...
1007 void RAS_OpenGLRasterizer::SetViewMatrix(const MT_Matrix4x4 &mat, 
1008                                                                                  const MT_Matrix3x3 & camOrientMat3x3,
1009                                                                                  const MT_Point3 & pos,
1010                                                                                  bool perspective)
1011 {
1012         m_viewmatrix = mat;
1013
1014         // correction for stereo
1015         if(Stereo() && perspective)
1016         {
1017                 MT_Vector3 unitViewDir(0.0, -1.0, 0.0);  // minus y direction, Blender convention
1018                 MT_Vector3 unitViewupVec(0.0, 0.0, 1.0);
1019                 MT_Vector3 viewDir, viewupVec;
1020                 MT_Vector3 eyeline;
1021
1022                 // actual viewDir
1023                 viewDir = camOrientMat3x3 * unitViewDir;  // this is the moto convention, vector on right hand side
1024                 // actual viewup vec
1025                 viewupVec = camOrientMat3x3 * unitViewupVec;
1026
1027                 // vector between eyes
1028                 eyeline = viewDir.cross(viewupVec);
1029
1030                 switch(m_curreye)
1031                 {
1032                         case RAS_STEREO_LEFTEYE:
1033                                 {
1034                                 // translate to left by half the eye distance
1035                                 MT_Transform transform;
1036                                 transform.setIdentity();
1037                                 transform.translate(-(eyeline * m_eyeseparation / 2.0));
1038                                 m_viewmatrix *= transform;
1039                                 }
1040                                 break;
1041                         case RAS_STEREO_RIGHTEYE:
1042                                 {
1043                                 // translate to right by half the eye distance
1044                                 MT_Transform transform;
1045                                 transform.setIdentity();
1046                                 transform.translate(eyeline * m_eyeseparation / 2.0);
1047                                 m_viewmatrix *= transform;
1048                                 }
1049                                 break;
1050                 }
1051         }
1052
1053         m_viewinvmatrix = m_viewmatrix;
1054         m_viewinvmatrix.invert();
1055
1056         // note: getValue gives back column major as needed by OpenGL
1057         MT_Scalar glviewmat[16];
1058         m_viewmatrix.getValue(glviewmat);
1059
1060         glMatrixMode(GL_MODELVIEW);
1061         glLoadMatrixd(glviewmat);
1062         m_campos = pos;
1063 }
1064
1065
1066 const MT_Point3& RAS_OpenGLRasterizer::GetCameraPosition()
1067 {
1068         return m_campos;
1069 }
1070
1071 bool RAS_OpenGLRasterizer::GetCameraOrtho()
1072 {
1073         return m_camortho;
1074 }
1075
1076 void RAS_OpenGLRasterizer::SetCullFace(bool enable)
1077 {
1078         if (enable)
1079                 glEnable(GL_CULL_FACE);
1080         else
1081                 glDisable(GL_CULL_FACE);
1082 }
1083
1084 void RAS_OpenGLRasterizer::SetLines(bool enable)
1085 {
1086         if (enable)
1087                 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
1088         else
1089                 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1090 }
1091
1092 void RAS_OpenGLRasterizer::SetSpecularity(float specX,
1093                                                                                   float specY,
1094                                                                                   float specZ,
1095                                                                                   float specval)
1096 {
1097         GLfloat mat_specular[] = {specX, specY, specZ, specval};
1098         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
1099 }
1100
1101
1102
1103 void RAS_OpenGLRasterizer::SetShinyness(float shiny)
1104 {
1105         GLfloat mat_shininess[] = {     shiny };
1106         glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess);
1107 }
1108
1109
1110
1111 void RAS_OpenGLRasterizer::SetDiffuse(float difX,float difY,float difZ,float diffuse)
1112 {
1113         GLfloat mat_diffuse [] = {difX, difY,difZ, diffuse};
1114         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diffuse);
1115 }
1116
1117 void RAS_OpenGLRasterizer::SetEmissive(float eX, float eY, float eZ, float e)
1118 {
1119         GLfloat mat_emit [] = {eX,eY,eZ,e};
1120         glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, mat_emit);
1121 }
1122
1123
1124 double RAS_OpenGLRasterizer::GetTime()
1125 {
1126         return m_time;
1127 }
1128
1129 void RAS_OpenGLRasterizer::SetPolygonOffset(float mult, float add)
1130 {
1131         glPolygonOffset(mult, add);
1132         GLint mode = GL_POLYGON_OFFSET_FILL;
1133         if (m_drawingmode < KX_SHADED)
1134                 mode = GL_POLYGON_OFFSET_LINE;
1135         if (mult != 0.0f || add != 0.0f)
1136                 glEnable(mode);
1137         else
1138                 glDisable(mode);
1139 }
1140
1141 void RAS_OpenGLRasterizer::EnableMotionBlur(float motionblurvalue)
1142 {
1143         /* don't just set m_motionblur to 1, but check if it is 0 so
1144          * we don't reset a motion blur that is already enabled */
1145         if(m_motionblur == 0)
1146                 m_motionblur = 1;
1147         m_motionblurvalue = motionblurvalue;
1148 }
1149
1150 void RAS_OpenGLRasterizer::DisableMotionBlur()
1151 {
1152         m_motionblur = 0;
1153         m_motionblurvalue = -1.0;
1154 }
1155
1156 void RAS_OpenGLRasterizer::SetBlendingMode(int blendmode)
1157 {
1158         GPU_set_material_blend_mode(blendmode);
1159 /*
1160         if(blendmode == m_last_blendmode)
1161                 return;
1162
1163         if(blendmode == GPU_BLEND_SOLID) {
1164                 glDisable(GL_BLEND);
1165                 glDisable(GL_ALPHA_TEST);
1166                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1167         }
1168         else if(blendmode == GPU_BLEND_ADD) {
1169                 glBlendFunc(GL_ONE, GL_ONE);
1170                 glEnable(GL_BLEND);
1171                 glDisable(GL_ALPHA_TEST);
1172         }
1173         else if(blendmode == GPU_BLEND_ALPHA) {
1174                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1175                 glEnable(GL_BLEND);
1176                 glEnable(GL_ALPHA_TEST);
1177                 glAlphaFunc(GL_GREATER, 0.0f);
1178         }
1179         else if(blendmode == GPU_BLEND_CLIP) {
1180                 glDisable(GL_BLEND); 
1181                 glEnable(GL_ALPHA_TEST);
1182                 glAlphaFunc(GL_GREATER, 0.5f);
1183         }
1184
1185         m_last_blendmode = blendmode;
1186 */
1187 }
1188
1189 void RAS_OpenGLRasterizer::SetFrontFace(bool ccw)
1190 {
1191         if(m_last_frontface == ccw)
1192                 return;
1193
1194         if(ccw)
1195                 glFrontFace(GL_CCW);
1196         else
1197                 glFrontFace(GL_CW);
1198         
1199         m_last_frontface = ccw;
1200 }
1201