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