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