Warning Fixes - const correctness in unicode encoding, unused variables in blenlib...
[blender.git] / source / gameengine / Converter / BL_BlenderDataConversion.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  * Convert blender data to ketsji
27  */
28
29 /** \file gameengine/Converter/BL_BlenderDataConversion.cpp
30  *  \ingroup bgeconv
31  */
32
33
34 #if defined(WIN32) && !defined(FREE_WINDOWS)
35 #pragma warning (disable : 4786)
36 #endif
37
38 #include <math.h>
39
40 #include "BL_BlenderDataConversion.h"
41 #include "KX_BlenderGL.h"
42 #include "KX_BlenderScalarInterpolator.h"
43
44 #include "RAS_IPolygonMaterial.h"
45 #include "KX_PolygonMaterial.h"
46
47 // Expressions
48 #include "ListValue.h"
49 #include "IntValue.h"
50 // Collision & Fuzzics LTD
51
52 #include "PHY_Pro.h"
53
54
55 #include "KX_Scene.h"
56 #include "KX_GameObject.h"
57 #include "RAS_FramingManager.h"
58 #include "RAS_MeshObject.h"
59
60 #include "KX_ConvertActuators.h"
61 #include "KX_ConvertControllers.h"
62 #include "KX_ConvertSensors.h"
63
64 #include "SCA_LogicManager.h"
65 #include "SCA_EventManager.h"
66 #include "SCA_TimeEventManager.h"
67 #include "KX_Light.h"
68 #include "KX_Camera.h"
69 #include "KX_EmptyObject.h"
70 #include "KX_FontObject.h"
71 #include "MT_Point3.h"
72 #include "MT_Transform.h"
73 #include "MT_MinMax.h"
74 #include "SCA_IInputDevice.h"
75 #include "RAS_TexMatrix.h"
76 #include "RAS_ICanvas.h"
77 #include "RAS_MaterialBucket.h"
78 //#include "KX_BlenderPolyMaterial.h"
79 #include "RAS_Polygon.h"
80 #include "RAS_TexVert.h"
81 #include "RAS_BucketManager.h"
82 #include "RAS_IRenderTools.h"
83 #include "BL_Material.h"
84 #include "KX_BlenderMaterial.h"
85 #include "BL_Texture.h"
86
87 #include "DNA_action_types.h"
88 #include "BKE_main.h"
89 #include "BKE_global.h"
90 #include "BKE_object.h"
91 #include "BL_ModifierDeformer.h"
92 #include "BL_ShapeDeformer.h"
93 #include "BL_SkinDeformer.h"
94 #include "BL_MeshDeformer.h"
95 #include "KX_SoftBodyDeformer.h"
96 //#include "BL_ArmatureController.h"
97 #include "BLI_utildefines.h"
98 #include "BlenderWorldInfo.h"
99
100 #include "KX_KetsjiEngine.h"
101 #include "KX_BlenderSceneConverter.h"
102
103 /* This little block needed for linking to Blender... */
104 #ifdef WIN32
105 #include "BLI_winstuff.h"
106 #endif
107
108 /* This list includes only data type definitions */
109 #include "DNA_object_types.h"
110 #include "DNA_material_types.h"
111 #include "DNA_texture_types.h"
112 #include "DNA_image_types.h"
113 #include "DNA_lamp_types.h"
114 #include "DNA_group_types.h"
115 #include "DNA_scene_types.h"
116 #include "DNA_camera_types.h"
117 #include "DNA_property_types.h"
118 #include "DNA_text_types.h"
119 #include "DNA_sensor_types.h"
120 #include "DNA_controller_types.h"
121 #include "DNA_actuator_types.h"
122 #include "DNA_mesh_types.h"
123 #include "DNA_meshdata_types.h"
124 #include "DNA_view3d_types.h"
125 #include "DNA_world_types.h"
126 #include "DNA_sound_types.h"
127 #include "DNA_key_types.h"
128 #include "DNA_armature_types.h"
129 #include "DNA_object_force.h"
130
131 #include "MEM_guardedalloc.h"
132
133 #include "BKE_key.h"
134 #include "BKE_mesh.h"
135 #include "MT_Point3.h"
136
137 #include "BLI_math.h"
138
139 extern "C" {
140 #include "BKE_scene.h"
141 #include "BKE_customdata.h"
142 #include "BKE_cdderivedmesh.h"
143 #include "BKE_DerivedMesh.h"
144 #include "BKE_material.h" /* give_current_material */
145 #include "BKE_image.h"
146 #include "IMB_imbuf_types.h"
147
148 extern Material defmaterial;    /* material.c */
149 }
150
151 /* end of blender include block */
152
153 #include "KX_BlenderInputDevice.h"
154 #include "KX_ConvertProperties.h"
155 #include "KX_HashedPtr.h"
156
157
158 #include "KX_ScalarInterpolator.h"
159
160 #include "KX_IpoConvert.h"
161 #include "BL_System.h"
162
163 #include "SG_Node.h"
164 #include "SG_BBox.h"
165 #include "SG_Tree.h"
166
167 #include "KX_ConvertPhysicsObject.h"
168 #ifdef USE_BULLET
169 #include "CcdPhysicsEnvironment.h"
170 #include "CcdGraphicController.h"
171 #endif
172 #include "KX_MotionState.h"
173
174 // This file defines relationships between parents and children
175 // in the game engine.
176
177 #include "KX_SG_NodeRelationships.h"
178 #include "KX_SG_BoneParentNodeRelationship.h"
179
180 #include "BL_ArmatureObject.h"
181 #include "BL_DeformableGameObject.h"
182
183 #include "KX_NavMeshObject.h"
184 #include "KX_ObstacleSimulation.h"
185
186 #ifdef __cplusplus
187 extern "C" {
188 #endif
189 //XXX #include "BSE_headerbuttons.h"
190 //XXX void update_for_newframe();
191 //void scene_update_for_newframe(struct Scene *sce, unsigned int lay);
192 //#include "BKE_ipo.h"
193 //void do_all_data_ipos(void);
194 #ifdef __cplusplus
195 }
196 #endif
197
198 static bool default_light_mode = 0;
199
200 static std::map<int, SCA_IInputDevice::KX_EnumInputs> create_translate_table()
201 {
202         std::map<int, SCA_IInputDevice::KX_EnumInputs> m;
203                 
204         /* The reverse table. In order to not confuse ourselves, we      */
205         /* immediately convert all events that come in to KX codes.      */
206         m[LEFTMOUSE                     ] =     SCA_IInputDevice::KX_LEFTMOUSE;
207         m[MIDDLEMOUSE           ] =     SCA_IInputDevice::KX_MIDDLEMOUSE;
208         m[RIGHTMOUSE            ] =     SCA_IInputDevice::KX_RIGHTMOUSE;
209         m[WHEELUPMOUSE          ] =     SCA_IInputDevice::KX_WHEELUPMOUSE;
210         m[WHEELDOWNMOUSE        ] =     SCA_IInputDevice::KX_WHEELDOWNMOUSE;
211         m[MOUSEX                        ] = SCA_IInputDevice::KX_MOUSEX;
212         m[MOUSEY                        ] =     SCA_IInputDevice::KX_MOUSEY;
213                 
214         // TIMERS                                                                                                  
215                 
216         m[TIMER0                        ] = SCA_IInputDevice::KX_TIMER0;                  
217         m[TIMER1                        ] = SCA_IInputDevice::KX_TIMER1;                  
218         m[TIMER2                        ] = SCA_IInputDevice::KX_TIMER2;                  
219                 
220         // SYSTEM                                                                                                  
221                 
222 #if 0                   
223         /* **** XXX **** */
224         m[KEYBD                         ] = SCA_IInputDevice::KX_KEYBD;                  
225         m[RAWKEYBD                      ] = SCA_IInputDevice::KX_RAWKEYBD;                  
226         m[REDRAW                        ] = SCA_IInputDevice::KX_REDRAW;                  
227         m[INPUTCHANGE           ] = SCA_IInputDevice::KX_INPUTCHANGE;                  
228         m[QFULL                         ] = SCA_IInputDevice::KX_QFULL;                  
229         m[WINFREEZE                     ] = SCA_IInputDevice::KX_WINFREEZE;                  
230         m[WINTHAW                       ] = SCA_IInputDevice::KX_WINTHAW;                  
231         m[WINCLOSE                      ] = SCA_IInputDevice::KX_WINCLOSE;                  
232         m[WINQUIT                       ] = SCA_IInputDevice::KX_WINQUIT;                  
233         m[Q_FIRSTTIME           ] = SCA_IInputDevice::KX_Q_FIRSTTIME;                  
234         /* **** XXX **** */
235 #endif  
236                 
237         // standard keyboard                                                                                       
238                 
239         m[AKEY                          ] = SCA_IInputDevice::KX_AKEY;                  
240         m[BKEY                          ] = SCA_IInputDevice::KX_BKEY;                  
241         m[CKEY                          ] = SCA_IInputDevice::KX_CKEY;                  
242         m[DKEY                          ] = SCA_IInputDevice::KX_DKEY;                  
243         m[EKEY                          ] = SCA_IInputDevice::KX_EKEY;                  
244         m[FKEY                          ] = SCA_IInputDevice::KX_FKEY;                  
245         m[GKEY                          ] = SCA_IInputDevice::KX_GKEY;                  
246
247 //XXX clean up
248 #ifdef WIN32
249 #define HKEY    'h'
250 #endif
251         m[HKEY                          ] = SCA_IInputDevice::KX_HKEY;                  
252 //XXX clean up
253 #ifdef WIN32
254 #undef HKEY
255 #endif
256
257         m[IKEY                          ] = SCA_IInputDevice::KX_IKEY;                  
258         m[JKEY                          ] = SCA_IInputDevice::KX_JKEY;                  
259         m[KKEY                          ] = SCA_IInputDevice::KX_KKEY;                  
260         m[LKEY                          ] = SCA_IInputDevice::KX_LKEY;                  
261         m[MKEY                          ] = SCA_IInputDevice::KX_MKEY;                  
262         m[NKEY                          ] = SCA_IInputDevice::KX_NKEY;                  
263         m[OKEY                          ] = SCA_IInputDevice::KX_OKEY;                  
264         m[PKEY                          ] = SCA_IInputDevice::KX_PKEY;                  
265         m[QKEY                          ] = SCA_IInputDevice::KX_QKEY;                  
266         m[RKEY                          ] = SCA_IInputDevice::KX_RKEY;                  
267         m[SKEY                          ] = SCA_IInputDevice::KX_SKEY;                  
268         m[TKEY                          ] = SCA_IInputDevice::KX_TKEY;                  
269         m[UKEY                          ] = SCA_IInputDevice::KX_UKEY;                  
270         m[VKEY                          ] = SCA_IInputDevice::KX_VKEY;                  
271         m[WKEY                          ] = SCA_IInputDevice::KX_WKEY;                  
272         m[XKEY                          ] = SCA_IInputDevice::KX_XKEY;                  
273         m[YKEY                          ] = SCA_IInputDevice::KX_YKEY;                  
274         m[ZKEY                          ] = SCA_IInputDevice::KX_ZKEY;                  
275                 
276         m[ZEROKEY                       ] = SCA_IInputDevice::KX_ZEROKEY;                  
277         m[ONEKEY                        ] = SCA_IInputDevice::KX_ONEKEY;                  
278         m[TWOKEY                        ] = SCA_IInputDevice::KX_TWOKEY;                  
279         m[THREEKEY                      ] = SCA_IInputDevice::KX_THREEKEY;                  
280         m[FOURKEY                       ] = SCA_IInputDevice::KX_FOURKEY;                  
281         m[FIVEKEY                       ] = SCA_IInputDevice::KX_FIVEKEY;                  
282         m[SIXKEY                        ] = SCA_IInputDevice::KX_SIXKEY;                  
283         m[SEVENKEY                      ] = SCA_IInputDevice::KX_SEVENKEY;                  
284         m[EIGHTKEY                      ] = SCA_IInputDevice::KX_EIGHTKEY;                  
285         m[NINEKEY                       ] = SCA_IInputDevice::KX_NINEKEY;                  
286                 
287         m[CAPSLOCKKEY           ] = SCA_IInputDevice::KX_CAPSLOCKKEY;                  
288                 
289         m[LEFTCTRLKEY           ] = SCA_IInputDevice::KX_LEFTCTRLKEY;                  
290         m[LEFTALTKEY            ] = SCA_IInputDevice::KX_LEFTALTKEY;                  
291         m[RIGHTALTKEY           ] = SCA_IInputDevice::KX_RIGHTALTKEY;                  
292         m[RIGHTCTRLKEY          ] = SCA_IInputDevice::KX_RIGHTCTRLKEY;                  
293         m[RIGHTSHIFTKEY         ] = SCA_IInputDevice::KX_RIGHTSHIFTKEY;                  
294         m[LEFTSHIFTKEY          ] = SCA_IInputDevice::KX_LEFTSHIFTKEY;                  
295                 
296         m[ESCKEY                        ] = SCA_IInputDevice::KX_ESCKEY;                  
297         m[TABKEY                        ] = SCA_IInputDevice::KX_TABKEY;                  
298         m[RETKEY                        ] = SCA_IInputDevice::KX_RETKEY;                  
299         m[SPACEKEY                      ] = SCA_IInputDevice::KX_SPACEKEY;                  
300         m[LINEFEEDKEY           ] = SCA_IInputDevice::KX_LINEFEEDKEY;                  
301         m[BACKSPACEKEY          ] = SCA_IInputDevice::KX_BACKSPACEKEY;                  
302         m[DELKEY                        ] = SCA_IInputDevice::KX_DELKEY;                  
303         m[SEMICOLONKEY          ] = SCA_IInputDevice::KX_SEMICOLONKEY;                  
304         m[PERIODKEY                     ] = SCA_IInputDevice::KX_PERIODKEY;                  
305         m[COMMAKEY                      ] = SCA_IInputDevice::KX_COMMAKEY;                  
306         m[QUOTEKEY                      ] = SCA_IInputDevice::KX_QUOTEKEY;                  
307         m[ACCENTGRAVEKEY        ] = SCA_IInputDevice::KX_ACCENTGRAVEKEY;                  
308         m[MINUSKEY                      ] = SCA_IInputDevice::KX_MINUSKEY;                  
309         m[SLASHKEY                      ] = SCA_IInputDevice::KX_SLASHKEY;                  
310         m[BACKSLASHKEY          ] = SCA_IInputDevice::KX_BACKSLASHKEY;                  
311         m[EQUALKEY                      ] = SCA_IInputDevice::KX_EQUALKEY;                  
312         m[LEFTBRACKETKEY        ] = SCA_IInputDevice::KX_LEFTBRACKETKEY;                  
313         m[RIGHTBRACKETKEY       ] = SCA_IInputDevice::KX_RIGHTBRACKETKEY;                  
314                 
315         m[LEFTARROWKEY          ] = SCA_IInputDevice::KX_LEFTARROWKEY;                  
316         m[DOWNARROWKEY          ] = SCA_IInputDevice::KX_DOWNARROWKEY;                  
317         m[RIGHTARROWKEY         ] = SCA_IInputDevice::KX_RIGHTARROWKEY;                  
318         m[UPARROWKEY            ] = SCA_IInputDevice::KX_UPARROWKEY;                  
319                 
320         m[PAD2                          ] = SCA_IInputDevice::KX_PAD2;                  
321         m[PAD4                          ] = SCA_IInputDevice::KX_PAD4;                  
322         m[PAD6                          ] = SCA_IInputDevice::KX_PAD6;                  
323         m[PAD8                          ] = SCA_IInputDevice::KX_PAD8;                  
324                 
325         m[PAD1                          ] = SCA_IInputDevice::KX_PAD1;                  
326         m[PAD3                          ] = SCA_IInputDevice::KX_PAD3;                  
327         m[PAD5                          ] = SCA_IInputDevice::KX_PAD5;                  
328         m[PAD7                          ] = SCA_IInputDevice::KX_PAD7;                  
329         m[PAD9                          ] = SCA_IInputDevice::KX_PAD9;                  
330                 
331         m[PADPERIOD                     ] = SCA_IInputDevice::KX_PADPERIOD;                  
332         m[PADSLASHKEY           ] = SCA_IInputDevice::KX_PADSLASHKEY;                  
333         m[PADASTERKEY           ] = SCA_IInputDevice::KX_PADASTERKEY;                  
334                 
335         m[PAD0                          ] = SCA_IInputDevice::KX_PAD0;                  
336         m[PADMINUS                      ] = SCA_IInputDevice::KX_PADMINUS;                  
337         m[PADENTER                      ] = SCA_IInputDevice::KX_PADENTER;                  
338         m[PADPLUSKEY            ] = SCA_IInputDevice::KX_PADPLUSKEY;                  
339                 
340                 
341         m[F1KEY                         ] = SCA_IInputDevice::KX_F1KEY;                  
342         m[F2KEY                         ] = SCA_IInputDevice::KX_F2KEY;                  
343         m[F3KEY                         ] = SCA_IInputDevice::KX_F3KEY;                  
344         m[F4KEY                         ] = SCA_IInputDevice::KX_F4KEY;                  
345         m[F5KEY                         ] = SCA_IInputDevice::KX_F5KEY;                  
346         m[F6KEY                         ] = SCA_IInputDevice::KX_F6KEY;                  
347         m[F7KEY                         ] = SCA_IInputDevice::KX_F7KEY;                  
348         m[F8KEY                         ] = SCA_IInputDevice::KX_F8KEY;                  
349         m[F9KEY                         ] = SCA_IInputDevice::KX_F9KEY;                  
350         m[F10KEY                        ] = SCA_IInputDevice::KX_F10KEY;                  
351         m[F11KEY                        ] = SCA_IInputDevice::KX_F11KEY;                  
352         m[F12KEY                        ] = SCA_IInputDevice::KX_F12KEY;
353         m[F13KEY                        ] = SCA_IInputDevice::KX_F13KEY;
354         m[F14KEY                        ] = SCA_IInputDevice::KX_F14KEY;
355         m[F15KEY                        ] = SCA_IInputDevice::KX_F15KEY;
356         m[F16KEY                        ] = SCA_IInputDevice::KX_F16KEY;
357         m[F17KEY                        ] = SCA_IInputDevice::KX_F17KEY;
358         m[F18KEY                        ] = SCA_IInputDevice::KX_F18KEY;
359         m[F19KEY                        ] = SCA_IInputDevice::KX_F19KEY;
360                 
361                 
362         m[PAUSEKEY                      ] = SCA_IInputDevice::KX_PAUSEKEY;                  
363         m[INSERTKEY                     ] = SCA_IInputDevice::KX_INSERTKEY;                  
364         m[HOMEKEY                       ] = SCA_IInputDevice::KX_HOMEKEY;                  
365         m[PAGEUPKEY                     ] = SCA_IInputDevice::KX_PAGEUPKEY;                  
366         m[PAGEDOWNKEY           ] = SCA_IInputDevice::KX_PAGEDOWNKEY;                  
367         m[ENDKEY                        ] = SCA_IInputDevice::KX_ENDKEY;
368
369         return m;
370 }
371
372 static std::map<int, SCA_IInputDevice::KX_EnumInputs> gReverseKeyTranslateTable = create_translate_table();
373
374 static unsigned int KX_rgbaint2uint_new(unsigned int icol)
375 {
376         union
377         {
378                 unsigned int integer;
379                 unsigned char cp[4];
380         } out_color, in_color;
381         
382         in_color.integer = icol;
383         out_color.cp[0] = in_color.cp[3]; // red
384         out_color.cp[1] = in_color.cp[2]; // green
385         out_color.cp[2] = in_color.cp[1]; // blue
386         out_color.cp[3] = in_color.cp[0]; // alpha
387         
388         return out_color.integer;
389 }
390
391 /* Now the real converting starts... */
392 static unsigned int KX_Mcol2uint_new(MCol col)
393 {
394         /* color has to be converted without endian sensitivity. So no shifting! */
395         union
396         {
397                 MCol col;
398                 unsigned int integer;
399                 unsigned char cp[4];
400         } out_color, in_color;
401
402         in_color.col = col;
403         out_color.cp[0] = in_color.cp[3]; // red
404         out_color.cp[1] = in_color.cp[2]; // green
405         out_color.cp[2] = in_color.cp[1]; // blue
406         out_color.cp[3] = in_color.cp[0]; // alpha
407         
408         return out_color.integer;
409 }
410
411 static void SetDefaultLightMode(Scene* scene)
412 {
413         default_light_mode = false;
414         Scene *sce_iter;
415         Base *base;
416
417         for (SETLOOPER(scene, sce_iter, base))
418         {
419                 if (base->object->type == OB_LAMP)
420                 {
421                         default_light_mode = true;
422                         return;
423                 }
424         }
425 }
426
427
428 // --
429 static void GetRGB(short type,
430         MFace* mface,
431         MCol* mmcol,
432         Material *mat,
433         unsigned int &c0, 
434         unsigned int &c1, 
435         unsigned int &c2, 
436         unsigned int &c3)
437 {
438         unsigned int color = 0xFFFFFFFFL;
439         switch(type)
440         {
441                 case 0: // vertex colors
442                 {
443                         if (mmcol) {
444                                 c0 = KX_Mcol2uint_new(mmcol[0]);
445                                 c1 = KX_Mcol2uint_new(mmcol[1]);
446                                 c2 = KX_Mcol2uint_new(mmcol[2]);
447                                 if (mface->v4)
448                                         c3 = KX_Mcol2uint_new(mmcol[3]);
449                         }else // backup white
450                         {
451                                 c0 = KX_rgbaint2uint_new(color);
452                                 c1 = KX_rgbaint2uint_new(color);
453                                 c2 = KX_rgbaint2uint_new(color);        
454                                 if (mface->v4)
455                                         c3 = KX_rgbaint2uint_new( color );
456                         }
457                 } break;
458                 
459         
460                 case 1: // material rgba
461                 {
462                         if (mat) {
463                                 union {
464                                         unsigned char cp[4];
465                                         unsigned int integer;
466                                 } col_converter;
467                                 col_converter.cp[3] = (unsigned char) (mat->r*255.0);
468                                 col_converter.cp[2] = (unsigned char) (mat->g*255.0);
469                                 col_converter.cp[1] = (unsigned char) (mat->b*255.0);
470                                 col_converter.cp[0] = (unsigned char) (mat->alpha*255.0);
471                                 color = col_converter.integer;
472                         }
473                         c0 = KX_rgbaint2uint_new(color);
474                         c1 = KX_rgbaint2uint_new(color);
475                         c2 = KX_rgbaint2uint_new(color);        
476                         if (mface->v4)
477                                 c3 = KX_rgbaint2uint_new(color);
478                 } break;
479                 
480                 default: // white
481                 {
482                         c0 = KX_rgbaint2uint_new(color);
483                         c1 = KX_rgbaint2uint_new(color);
484                         c2 = KX_rgbaint2uint_new(color);        
485                         if (mface->v4)
486                                 c3 = KX_rgbaint2uint_new(color);
487                 } break;
488         }
489 }
490
491 typedef struct MTF_localLayer
492 {
493         MTFace *face;
494         const char *name;
495 }MTF_localLayer;
496
497 // ------------------------------------
498 bool ConvertMaterial(
499         BL_Material *material,
500         Material *mat, 
501         MTFace* tface,  
502         const char *tfaceName,
503         MFace* mface, 
504         MCol* mmcol,
505         MTF_localLayer *layers,
506         bool glslmat)
507 {
508         material->Initialize();
509         int numchan =   -1, texalpha = 0;
510         bool validmat   = (mat!=0);
511         bool validface  = (tface!=0);
512         
513         short type = 0;
514         if ( validmat )
515                 type = 1; // material color 
516         
517         material->IdMode = DEFAULT_BLENDER;
518         material->glslmat = (validmat)? glslmat: false;
519         material->materialindex = mface->mat_nr;
520
521         // --------------------------------
522         if (validmat) {
523
524                 // use vertex colors by explicitly setting
525                 if (mat->mode &MA_VERTEXCOLP || glslmat)
526                         type = 0;
527
528                 // use lighting?
529                 material->ras_mode |= ( mat->mode & MA_SHLESS )?0:USE_LIGHT;
530                 material->ras_mode |= ( mat->game.flag & GEMAT_BACKCULL )?0:TWOSIDED;
531
532                 // cast shadows?
533                 material->ras_mode |= ( mat->mode & MA_SHADBUF )?CAST_SHADOW:0;
534                 MTex *mttmp = 0;
535                 numchan = getNumTexChannels(mat);
536                 int valid_index = 0;
537                 
538                 /* In Multitexture use the face texture if and only if
539                  * it is set in the buttons
540                  * In GLSL is not working yet :/ 3.2011 */
541                 bool facetex = false;
542                 if (validface && mat->mode &MA_FACETEXTURE) 
543                         facetex = true;
544
545                 numchan = numchan>MAXTEX?MAXTEX:numchan;
546                 if (facetex && numchan == 0) numchan = 1;
547         
548                 // foreach MTex
549                 for (int i=0; i<numchan; i++) {
550                         // use face tex
551
552                         if (i==0 && facetex ) {
553                                 facetex = false;
554                                 Image*tmp = (Image*)(tface->tpage);
555
556                                 if (tmp) {
557                                         material->img[i] = tmp;
558                                         material->texname[i] = material->img[i]->id.name;
559                                         material->flag[i] |= MIPMAP;
560
561                                         material->flag[i] |= ( mat->game.alpha_blend & GEMAT_ALPHA_SORT )?USEALPHA:0;
562                                         material->flag[i] |= ( mat->game.alpha_blend & GEMAT_ALPHA )?USEALPHA:0;
563                                         material->flag[i] |= ( mat->game.alpha_blend & GEMAT_ADD )?CALCALPHA:0;
564
565                                         if (material->img[i]->flag & IMA_REFLECT)
566                                                 material->mapping[i].mapping |= USEREFL;
567                                         else
568                                         {
569                                                 mttmp = getImageFromMaterial( mat, i );
570                                                 if (mttmp && mttmp->texco &TEXCO_UV)
571                                                 {
572                                                         STR_String uvName = mttmp->uvname;
573
574                                                         if (!uvName.IsEmpty())
575                                                                 material->mapping[i].uvCoName = mttmp->uvname;
576                                                         else
577                                                                 material->mapping[i].uvCoName = "";
578                                                 }
579                                                 material->mapping[i].mapping |= USEUV;
580                                         }
581
582                                         valid_index++;
583                                 }
584                                 else {
585                                         material->img[i] = 0;
586                                         material->texname[i] = "";
587                                 }
588                                 continue;
589                         }
590
591                         mttmp = getImageFromMaterial( mat, i );
592                         if ( mttmp ) {
593                                 if ( mttmp->tex ) {
594                                         if ( mttmp->tex->type == TEX_IMAGE ) {
595                                                 material->mtexname[i] = mttmp->tex->id.name;
596                                                 material->img[i] = mttmp->tex->ima;
597                                                 if ( material->img[i] ) {
598
599                                                         material->texname[i] = material->img[i]->id.name;
600                                                         material->flag[i] |= ( mttmp->tex->imaflag &TEX_MIPMAP )?MIPMAP:0;
601                                                         // -----------------------
602                                                         if ( mttmp->tex->imaflag &TEX_USEALPHA ) {
603                                                                 material->flag[i]       |= USEALPHA;
604                                                         }
605                                                         // -----------------------
606                                                         else if ( mttmp->tex->imaflag &TEX_CALCALPHA ) {
607                                                                 material->flag[i]       |= CALCALPHA;
608                                                         }
609                                                         else if (mttmp->tex->flag &TEX_NEGALPHA) {
610                                                                 material->flag[i]       |= USENEGALPHA;
611                                                         }
612
613                                                         material->color_blend[i] = mttmp->colfac;
614                                                         material->flag[i] |= ( mttmp->mapto  & MAP_ALPHA                )?TEXALPHA:0;
615                                                         material->flag[i] |= ( mttmp->texflag& MTEX_NEGATIVE    )?TEXNEG:0;
616
617                                                         if (!glslmat && (material->flag[i] & TEXALPHA))
618                                                                 texalpha = 1;
619                                                 }
620                                         }
621                                         else if (mttmp->tex->type == TEX_ENVMAP) {
622                                                 if ( mttmp->tex->env->stype == ENV_LOAD ) {
623                                         
624                                                         material->mtexname[i]     = mttmp->tex->id.name;
625                                                         EnvMap *env = mttmp->tex->env;
626                                                         env->ima = mttmp->tex->ima;
627                                                         material->cubemap[i] = env;
628
629                                                         if (material->cubemap[i])
630                                                         {
631                                                                 if (!material->cubemap[i]->cube[0])
632                                                                         BL_Texture::SplitEnvMap(material->cubemap[i]);
633
634                                                                 material->texname[i]= material->cubemap[i]->ima->id.name;
635                                                                 material->mapping[i].mapping |= USEENV;
636                                                         }
637                                                 }
638                                         }
639 #if 0                           /* this flag isn't used anymore */
640                                         material->flag[i] |= (BKE_animdata_from_id(mat->id) != NULL) ? HASIPO : 0;
641 #endif
642                                         /// --------------------------------
643                                         // mapping methods
644                                         material->mapping[i].mapping |= ( mttmp->texco  & TEXCO_REFL    )?USEREFL:0;
645                                         
646                                         if (mttmp->texco & TEXCO_OBJECT) {
647                                                 material->mapping[i].mapping |= USEOBJ;
648                                                 if (mttmp->object)
649                                                         material->mapping[i].objconame = mttmp->object->id.name;
650                                         }
651                                         else if (mttmp->texco &TEXCO_REFL)
652                                                 material->mapping[i].mapping |= USEREFL;
653                                         else if (mttmp->texco &(TEXCO_ORCO|TEXCO_GLOB))
654                                                 material->mapping[i].mapping |= USEORCO;
655                                         else if (mttmp->texco &TEXCO_UV)
656                                         {
657                                                 STR_String uvName = mttmp->uvname;
658
659                                                 if (!uvName.IsEmpty())
660                                                         material->mapping[i].uvCoName = mttmp->uvname;
661                                                 else
662                                                         material->mapping[i].uvCoName = "";
663                                                 material->mapping[i].mapping |= USEUV;
664                                         }
665                                         else if (mttmp->texco &TEXCO_NORM)
666                                                 material->mapping[i].mapping |= USENORM;
667                                         else if (mttmp->texco &TEXCO_TANGENT)
668                                                 material->mapping[i].mapping |= USETANG;
669                                         else
670                                                 material->mapping[i].mapping |= DISABLE;
671                                         
672                                         material->mapping[i].scale[0] = mttmp->size[0];
673                                         material->mapping[i].scale[1] = mttmp->size[1];
674                                         material->mapping[i].scale[2] = mttmp->size[2];
675                                         material->mapping[i].offsets[0] = mttmp->ofs[0];
676                                         material->mapping[i].offsets[1] = mttmp->ofs[1];
677                                         material->mapping[i].offsets[2] = mttmp->ofs[2];
678
679                                         material->mapping[i].projplane[0] = mttmp->projx;
680                                         material->mapping[i].projplane[1] = mttmp->projy;
681                                         material->mapping[i].projplane[2] = mttmp->projz;
682                                         /// --------------------------------
683                                         
684                                         switch( mttmp->blendtype ) {
685                                         case MTEX_BLEND:
686                                                 material->blend_mode[i] = BLEND_MIX;
687                                                 break;
688                                         case MTEX_MUL:
689                                                 material->blend_mode[i] = BLEND_MUL;
690                                                 break;
691                                         case MTEX_ADD:
692                                                 material->blend_mode[i] = BLEND_ADD;
693                                                 break;
694                                         case MTEX_SUB:
695                                                 material->blend_mode[i] = BLEND_SUB;
696                                                 break;
697                                         case MTEX_SCREEN:
698                                                 material->blend_mode[i] = BLEND_SCR;
699                                                 break;
700                                         }
701                                         valid_index++;
702                                 }
703                         }
704                 }
705
706                 // above one tex the switches here
707                 // are not used
708                 switch(valid_index) {
709                 case 0:
710                         material->IdMode = DEFAULT_BLENDER;
711                         break;
712                 case 1:
713                         material->IdMode = ONETEX;
714                         break;
715                 default:
716                         material->IdMode = GREATERTHAN2;
717                         break;
718                 }
719                 material->SetUsers(mat->id.us);
720
721                 material->num_enabled = valid_index;
722
723                 material->speccolor[0]  = mat->specr;
724                 material->speccolor[1]  = mat->specg;
725                 material->speccolor[2]  = mat->specb;
726                 material->hard                  = (float)mat->har/4.0f;
727                 material->matcolor[0]   = mat->r;
728                 material->matcolor[1]   = mat->g;
729                 material->matcolor[2]   = mat->b;
730                 material->matcolor[3]   = mat->alpha;
731                 material->alpha                 = mat->alpha;
732                 material->emit                  = mat->emit;
733                 material->spec_f                = mat->spec;
734                 material->ref                   = mat->ref;
735                 material->amb                   = mat->amb;
736
737                 material->ras_mode |= (mat->material_type == MA_TYPE_WIRE)? WIRE: 0;
738         }
739         else { // No Material
740                 int valid = 0;
741
742                 // check for tface tex to fallback on
743                 if ( validface ) {
744                         material->img[0] = (Image*)(tface->tpage);
745                         // ------------------------
746                         if (material->img[0]) {
747                                 material->texname[0] = material->img[0]->id.name;
748                                 material->mapping[0].mapping |= ( (material->img[0]->flag & IMA_REFLECT)!=0 )?USEREFL:0;
749
750                                 /* see if depth of the image is 32bits */
751                                 if (BKE_image_has_alpha(material->img[0])) {
752                                         material->flag[0] |= USEALPHA;
753                                         material->alphablend = GEMAT_ALPHA;
754                                 }
755                                 else
756                                         material->alphablend = GEMAT_SOLID;
757
758                                 valid++;
759                         }
760                 }
761                 else
762                         material->alphablend = GEMAT_SOLID;
763
764                 material->SetUsers(-1);
765                 material->num_enabled   = valid;
766                 material->IdMode                = TEXFACE;
767                 material->speccolor[0]  = 1.f;
768                 material->speccolor[1]  = 1.f;
769                 material->speccolor[2]  = 1.f;
770                 material->hard                  = 35.f;
771                 material->matcolor[0]   = 0.5f;
772                 material->matcolor[1]   = 0.5f;
773                 material->matcolor[2]   = 0.5f;
774                 material->spec_f                = 0.5f;
775                 material->ref                   = 0.8f;
776
777                 // No material - old default TexFace properties
778                 material->ras_mode |= USE_LIGHT;
779         }
780         MT_Point2 uv[4];
781         MT_Point2 uv2[4];
782         const char *uvName = "", *uv2Name = "";
783
784         
785         uv2[0]= uv2[1]= uv2[2]= uv2[3]= MT_Point2(0.0f, 0.0f);
786
787         /* No material, what to do? let's see what is in the UV and set the material accordingly
788          * light and visible is always on */
789         if ( validface ) {
790                 material->tile  = tface->tile;
791                         
792                 uv[0].setValue(tface->uv[0]);
793                 uv[1].setValue(tface->uv[1]);
794                 uv[2].setValue(tface->uv[2]);
795
796                 if (mface->v4) 
797                         uv[3].setValue(tface->uv[3]);
798
799                 uvName = tfaceName;
800         } 
801         else {
802                 // nothing at all
803                 material->alphablend    = GEMAT_SOLID;
804                 material->tile          = 0;
805                 
806                 uv[0]= uv[1]= uv[2]= uv[3]= MT_Point2(0.0f, 0.0f);
807         }
808
809         if (validmat && validface) {
810                 material->alphablend = mat->game.alpha_blend;
811         }
812
813         // with ztransp enabled, enforce alpha blending mode
814         if (validmat && (mat->mode & MA_TRANSP) && (mat->mode & MA_ZTRANSP) && (material->alphablend == GEMAT_SOLID))
815                 material->alphablend = GEMAT_ALPHA;
816
817         // always zsort alpha + add
818         if ((ELEM3(material->alphablend, GEMAT_ALPHA, GEMAT_ALPHA_SORT, GEMAT_ADD) || texalpha) && (material->alphablend != GEMAT_CLIP )) {
819                 material->ras_mode |= ALPHA;
820                 material->ras_mode |= (mat && (mat->game.alpha_blend & GEMAT_ALPHA_SORT))? ZSORT: 0;
821         }
822
823         // get uv sets
824         if (validmat) 
825         {
826                 bool isFirstSet = true;
827
828                 // only two sets implemented, but any of the eight 
829                 // sets can make up the two layers
830                 for (int vind = 0; vind<material->num_enabled; vind++)
831                 {
832                         BL_Mapping &map = material->mapping[vind];
833
834                         if (map.uvCoName.IsEmpty())
835                                 isFirstSet = false;
836                         else
837                         {
838                                 for (int lay=0; lay<MAX_MTFACE; lay++)
839                                 {
840                                         MTF_localLayer& layer = layers[lay];
841                                         if (layer.face == 0) break;
842
843                                         if (strcmp(map.uvCoName.ReadPtr(), layer.name)==0)
844                                         {
845                                                 MT_Point2 uvSet[4];
846
847                                                 uvSet[0].setValue(layer.face->uv[0]);
848                                                 uvSet[1].setValue(layer.face->uv[1]);
849                                                 uvSet[2].setValue(layer.face->uv[2]);
850
851                                                 if (mface->v4) 
852                                                         uvSet[3].setValue(layer.face->uv[3]);
853                                                 else
854                                                         uvSet[3].setValue(0.0f, 0.0f);
855
856                                                 if (isFirstSet)
857                                                 {
858                                                         uv[0] = uvSet[0]; uv[1] = uvSet[1];
859                                                         uv[2] = uvSet[2]; uv[3] = uvSet[3];
860                                                         isFirstSet = false;
861                                                         uvName = layer.name;
862                                                 }
863                                                 else if (strcmp(layer.name, uvName) != 0)
864                                                 {
865                                                         uv2[0] = uvSet[0]; uv2[1] = uvSet[1];
866                                                         uv2[2] = uvSet[2]; uv2[3] = uvSet[3];
867                                                         map.mapping |= USECUSTOMUV;
868                                                         uv2Name = layer.name;
869                                                 }
870                                         }
871                                 }
872                         }
873                 }
874         }
875
876         unsigned int rgb[4];
877         GetRGB(type,mface,mmcol,mat,rgb[0],rgb[1],rgb[2], rgb[3]);
878
879         // swap the material color, so MCol on bitmap font works
880         if (validmat && type==1 && (mat->game.flag & GEMAT_TEXT))
881         {
882                 rgb[0] = KX_rgbaint2uint_new(rgb[0]);
883                 rgb[1] = KX_rgbaint2uint_new(rgb[1]);
884                 rgb[2] = KX_rgbaint2uint_new(rgb[2]);
885                 rgb[3] = KX_rgbaint2uint_new(rgb[3]);
886         }
887
888         material->SetConversionRGB(rgb);
889         material->SetConversionUV(uvName, uv);
890         material->SetConversionUV2(uv2Name, uv2);
891
892         if (validmat)
893                 material->matname       =(mat->id.name);
894
895         material->tface         = tface;
896         material->material      = mat;
897         return true;
898 }
899
900 /* blenderobj can be NULL, make sure its checked for */
901 RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, KX_Scene* scene, KX_BlenderSceneConverter *converter)
902 {
903         RAS_MeshObject *meshobj;
904         int lightlayer = blenderobj ? blenderobj->lay:(1<<20)-1; // all layers if no object.
905
906         if ((meshobj = converter->FindGameMesh(mesh/*, ob->lay*/)) != NULL)
907                 return meshobj;
908         // Get DerivedMesh data
909         DerivedMesh *dm = CDDM_from_mesh(mesh, blenderobj);
910         DM_ensure_tessface(dm);
911
912         MVert *mvert = dm->getVertArray(dm);
913         int totvert = dm->getNumVerts(dm);
914
915         MFace *mface = dm->getTessFaceArray(dm);
916         MTFace *tface = static_cast<MTFace*>(dm->getTessFaceDataArray(dm, CD_MTFACE));
917         MCol *mcol = static_cast<MCol*>(dm->getTessFaceDataArray(dm, CD_MCOL));
918         float (*tangent)[4] = NULL;
919         int totface = dm->getNumTessFaces(dm);
920         const char *tfaceName = "";
921
922         if (tface) {
923                 DM_add_tangent_layer(dm);
924                 tangent = (float(*)[4])dm->getTessFaceDataArray(dm, CD_TANGENT);
925         }
926
927         meshobj = new RAS_MeshObject(mesh);
928
929         // Extract avaiable layers
930         MTF_localLayer *layers =  new MTF_localLayer[MAX_MTFACE];
931         for (int lay=0; lay<MAX_MTFACE; lay++) {
932                 layers[lay].face = 0;
933                 layers[lay].name = "";
934         }
935
936         int validLayers = 0;
937         for (int i=0; i<dm->faceData.totlayer; i++)
938         {
939                 if (dm->faceData.layers[i].type == CD_MTFACE)
940                 {
941                         assert(validLayers <= 8);
942
943                         layers[validLayers].face = (MTFace*)(dm->faceData.layers[i].data);
944                         layers[validLayers].name = dm->faceData.layers[i].name;
945                         if (tface == layers[validLayers].face)
946                                 tfaceName = layers[validLayers].name;
947                         validLayers++;
948                 }
949         }
950
951         meshobj->SetName(mesh->id.name + 2);
952         meshobj->m_sharedvertex_map.resize(totvert);
953         RAS_IPolyMaterial* polymat = NULL;
954         STR_String imastr;
955         // These pointers will hold persistent material structure during the conversion
956         // to avoid countless allocation/deallocation of memory.
957         BL_Material* bl_mat = NULL;
958         KX_BlenderMaterial* kx_blmat = NULL;
959         KX_PolygonMaterial* kx_polymat = NULL;
960
961         for (int f=0;f<totface;f++,mface++)
962         {
963                 Material* ma = 0;
964                 bool collider = true;
965                 MT_Point2 uv0(0.0,0.0),uv1(0.0,0.0),uv2(0.0,0.0),uv3(0.0,0.0);
966                 MT_Point2 uv20(0.0,0.0),uv21(0.0,0.0),uv22(0.0,0.0),uv23(0.0,0.0);
967                 unsigned int rgb0,rgb1,rgb2,rgb3 = 0;
968
969                 MT_Point3 pt0, pt1, pt2, pt3;
970                 MT_Vector3 no0(0,0,0), no1(0,0,0), no2(0,0,0), no3(0,0,0);
971                 MT_Vector4 tan0(0,0,0,0), tan1(0,0,0,0), tan2(0,0,0,0), tan3(0,0,0,0);
972
973                 /* get coordinates, normals and tangents */
974                 pt0.setValue(mvert[mface->v1].co);
975                 pt1.setValue(mvert[mface->v2].co);
976                 pt2.setValue(mvert[mface->v3].co);
977                 if (mface->v4) pt3.setValue(mvert[mface->v4].co);
978
979                 if (mface->flag & ME_SMOOTH) {
980                         float n0[3], n1[3], n2[3], n3[3];
981
982                         normal_short_to_float_v3(n0, mvert[mface->v1].no);
983                         normal_short_to_float_v3(n1, mvert[mface->v2].no);
984                         normal_short_to_float_v3(n2, mvert[mface->v3].no);
985                         no0 = n0;
986                         no1 = n1;
987                         no2 = n2;
988
989                         if (mface->v4) {
990                                 normal_short_to_float_v3(n3, mvert[mface->v4].no);
991                                 no3 = n3;
992                         }
993                 }
994                 else {
995                         float fno[3];
996
997                         if (mface->v4)
998                                 normal_quad_v3( fno,mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co, mvert[mface->v4].co);
999                         else
1000                                 normal_tri_v3( fno,mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co);
1001
1002                         no0 = no1 = no2 = no3 = MT_Vector3(fno);
1003                 }
1004
1005                 if (tangent) {
1006                         tan0 = tangent[f*4 + 0];
1007                         tan1 = tangent[f*4 + 1];
1008                         tan2 = tangent[f*4 + 2];
1009
1010                         if (mface->v4)
1011                                 tan3 = tangent[f*4 + 3];
1012                 }
1013                 if (blenderobj)
1014                         ma = give_current_material(blenderobj, mface->mat_nr+1);
1015                 else
1016                         ma = mesh->mat ? mesh->mat[mface->mat_nr]:NULL;
1017
1018                 /* ckeck for texface since texface _only_ is used as a fallback */
1019                 if (ma == NULL && tface == NULL) {
1020                         ma= &defmaterial;
1021                 }
1022
1023                 {
1024                         bool visible = true;
1025                         bool twoside = false;
1026
1027                         if (converter->GetMaterials()) {
1028                                 /* do Blender Multitexture and Blender GLSL materials */
1029                                 unsigned int rgb[4];
1030                                 MT_Point2 uv[4];
1031
1032                                 /* first is the BL_Material */
1033                                 if (!bl_mat)
1034                                         bl_mat = new BL_Material();
1035                                 ConvertMaterial(bl_mat, ma, tface, tfaceName, mface, mcol,
1036                                         layers, converter->GetGLSLMaterials());
1037
1038                                 /* vertex colors and uv's were stored in bl_mat temporarily */
1039                                 bl_mat->GetConversionRGB(rgb);
1040                                 rgb0 = rgb[0]; rgb1 = rgb[1];
1041                                 rgb2 = rgb[2]; rgb3 = rgb[3];
1042
1043                                 bl_mat->GetConversionUV(uv);
1044                                 uv0 = uv[0]; uv1 = uv[1];
1045                                 uv2 = uv[2]; uv3 = uv[3];
1046
1047                                 bl_mat->GetConversionUV2(uv);
1048                                 uv20 = uv[0]; uv21 = uv[1];
1049                                 uv22 = uv[2]; uv23 = uv[3];
1050                                 
1051                                 /* then the KX_BlenderMaterial */
1052                                 if (kx_blmat == NULL)
1053                                         kx_blmat = new KX_BlenderMaterial();
1054
1055                                 kx_blmat->Initialize(scene, bl_mat, (ma?&ma->game:NULL));
1056                                 polymat = static_cast<RAS_IPolyMaterial*>(kx_blmat);
1057                         }
1058                         else {
1059                                 /* do Texture Face materials */
1060                                 Image* bima = (tface)? (Image*)tface->tpage: NULL;
1061                                 imastr =  (tface)? (bima? (bima)->id.name : "" ) : "";
1062                 
1063                                 char alpha_blend=0;
1064                                 short tile=0;
1065                                 int     tilexrep=4,tileyrep = 4;
1066
1067                                 /* set material properties - old TexFace */
1068                                 if (ma) {
1069                                         alpha_blend = ma->game.alpha_blend;
1070                                         /* Commented out for now. If we ever get rid of
1071                                          * "Texture Face/Singletexture" we can then think about it */
1072
1073                                         /* Texture Face mode ignores texture but requires "Face Textures to be True "*/
1074 #if 0
1075                                         if ((ma->mode &MA_FACETEXTURE)==0 && (ma->game.flag &GEMAT_TEXT)==0) {
1076                                                 bima = NULL;
1077                                                 imastr = "";
1078                                                 alpha_blend = GEMAT_SOLID;       
1079                                         }
1080                                         else {
1081                                                 alpha_blend = ma->game.alpha_blend;
1082                                         }
1083 #endif
1084                                 }
1085                                 /* check for tface tex to fallback on */
1086                                 else {
1087                                         if (bima) {
1088                                                 /* see if depth of the image is 32 */
1089                                                 if (BKE_image_has_alpha(bima))
1090                                                         alpha_blend = GEMAT_ALPHA;
1091                                                 else
1092                                                         alpha_blend = GEMAT_SOLID;
1093                                         }
1094                                         else {
1095                                                 alpha_blend = GEMAT_SOLID;
1096                                         }
1097                                 }
1098
1099                                 if (bima) {
1100                                         tilexrep = bima->xrep;
1101                                         tileyrep = bima->yrep;
1102                                 }
1103
1104                                 /* set UV properties */
1105                                 if (tface) {
1106                                         uv0.setValue(tface->uv[0]);
1107                                         uv1.setValue(tface->uv[1]);
1108                                         uv2.setValue(tface->uv[2]);
1109         
1110                                         if (mface->v4)
1111                                                 uv3.setValue(tface->uv[3]);
1112
1113                                         tile = tface->tile;
1114                                 } 
1115                                 else {
1116                                         /* no texfaces */
1117                                         tile = 0;
1118                                 }
1119
1120                                 /* get vertex colors */
1121                                 if (mcol) {
1122                                         /* we have vertex colors */
1123                                         rgb0 = KX_Mcol2uint_new(mcol[0]);
1124                                         rgb1 = KX_Mcol2uint_new(mcol[1]);
1125                                         rgb2 = KX_Mcol2uint_new(mcol[2]);
1126                                         
1127                                         if (mface->v4)
1128                                                 rgb3 = KX_Mcol2uint_new(mcol[3]);
1129                                 }
1130                                 else {
1131                                         /* no vertex colors, take from material, otherwise white */
1132                                         unsigned int color = 0xFFFFFFFFL;
1133
1134                                         if (ma)
1135                                         {
1136                                                 union
1137                                                 {
1138                                                         unsigned char cp[4];
1139                                                         unsigned int integer;
1140                                                 } col_converter;
1141                                                 
1142                                                 col_converter.cp[3] = (unsigned char) (ma->r*255.0);
1143                                                 col_converter.cp[2] = (unsigned char) (ma->g*255.0);
1144                                                 col_converter.cp[1] = (unsigned char) (ma->b*255.0);
1145                                                 col_converter.cp[0] = (unsigned char) (ma->alpha*255.0);
1146                                                 
1147                                                 color = col_converter.integer;
1148                                         }
1149
1150                                         rgb0 = KX_rgbaint2uint_new(color);
1151                                         rgb1 = KX_rgbaint2uint_new(color);
1152                                         rgb2 = KX_rgbaint2uint_new(color);      
1153                                         
1154                                         if (mface->v4)
1155                                                 rgb3 = KX_rgbaint2uint_new(color);
1156                                 }
1157
1158                                 // only zsort alpha + add
1159                                 bool alpha = ELEM3(alpha_blend, GEMAT_ALPHA, GEMAT_ADD, GEMAT_ALPHA_SORT);
1160                                 bool zsort = (alpha_blend == GEMAT_ALPHA_SORT);
1161                                 bool light = (ma)?(ma->mode & MA_SHLESS)==0:default_light_mode;
1162
1163                                 // don't need zort anymore, deal as if it it's alpha blend
1164                                 if (alpha_blend == GEMAT_ALPHA_SORT) alpha_blend = GEMAT_ALPHA;
1165
1166                                 if (kx_polymat == NULL)
1167                                         kx_polymat = new KX_PolygonMaterial();
1168                                 kx_polymat->Initialize(imastr, ma, (int)mface->mat_nr,
1169                                         tile, tilexrep, tileyrep, 
1170                                         alpha_blend, alpha, zsort, light, lightlayer, tface, (unsigned int*)mcol);
1171                                 polymat = static_cast<RAS_IPolyMaterial*>(kx_polymat);
1172         
1173                                 if (ma) {
1174                                         polymat->m_specular = MT_Vector3(ma->specr, ma->specg, ma->specb)*ma->spec;
1175                                         polymat->m_shininess = (float)ma->har/4.0f; // 0 < ma->har <= 512
1176                                         polymat->m_diffuse = MT_Vector3(ma->r, ma->g, ma->b)*(ma->emit + ma->ref);
1177                                 }
1178                                 else {
1179                                         polymat->m_specular.setValue(0.0f,0.0f,0.0f);
1180                                         polymat->m_shininess = 35.0;
1181                                 }
1182                         }
1183
1184                         // set render flags
1185                         if (ma)
1186                         {
1187                                 visible = ((ma->game.flag & GEMAT_INVISIBLE)==0);
1188                                 twoside = ((ma->game.flag  & GEMAT_BACKCULL)==0);
1189                                 collider = ((ma->game.flag & GEMAT_NOPHYSICS)==0);
1190                         }
1191                         else{
1192                                 visible = true;
1193                                 twoside = false;
1194                                 collider = true;
1195                         }
1196
1197                         /* mark face as flat, so vertices are split */
1198                         bool flat = (mface->flag & ME_SMOOTH) == 0;
1199
1200                         // see if a bucket was reused or a new one was created
1201                         // this way only one KX_BlenderMaterial object has to exist per bucket
1202                         bool bucketCreated; 
1203                         RAS_MaterialBucket* bucket = scene->FindBucket(polymat, bucketCreated);
1204                         if (bucketCreated) {
1205                                 // this is needed to free up memory afterwards
1206                                 converter->RegisterPolyMaterial(polymat);
1207                                 if (converter->GetMaterials()) {
1208                                         converter->RegisterBlenderMaterial(bl_mat);
1209                                         // the poly material has been stored in the bucket, next time we must create a new one
1210                                         bl_mat = NULL;
1211                                         kx_blmat = NULL;
1212                                 } else {
1213                                         // the poly material has been stored in the bucket, next time we must create a new one
1214                                         kx_polymat = NULL;
1215                                 }
1216                         } else {
1217                                 // from now on, use the polygon material from the material bucket
1218                                 polymat = bucket->GetPolyMaterial();
1219                                 // keep the material pointers, they will be reused for next face
1220                         }
1221                                                  
1222                         int nverts = (mface->v4)? 4: 3;
1223                         RAS_Polygon *poly = meshobj->AddPolygon(bucket, nverts);
1224
1225                         poly->SetVisible(visible);
1226                         poly->SetCollider(collider);
1227                         poly->SetTwoside(twoside);
1228                         //poly->SetEdgeCode(mface->edcode);
1229
1230                         meshobj->AddVertex(poly,0,pt0,uv0,uv20,tan0,rgb0,no0,flat,mface->v1);
1231                         meshobj->AddVertex(poly,1,pt1,uv1,uv21,tan1,rgb1,no1,flat,mface->v2);
1232                         meshobj->AddVertex(poly,2,pt2,uv2,uv22,tan2,rgb2,no2,flat,mface->v3);
1233
1234                         if (nverts==4)
1235                                 meshobj->AddVertex(poly,3,pt3,uv3,uv23,tan3,rgb3,no3,flat,mface->v4);
1236                 }
1237
1238                 if (tface) 
1239                         tface++;
1240                 if (mcol)
1241                         mcol+=4;
1242
1243                 for (int lay=0; lay<MAX_MTFACE; lay++)
1244                 {
1245                         MTF_localLayer &layer = layers[lay];
1246                         if (layer.face == 0) break;
1247
1248                         layer.face++;
1249                 }
1250         }
1251         // keep meshobj->m_sharedvertex_map for reinstance phys mesh.
1252         // 2.49a and before it did: meshobj->m_sharedvertex_map.clear();
1253         // but this didnt save much ram. - Campbell
1254         meshobj->EndConversion();
1255
1256         // pre calculate texture generation
1257         for (list<RAS_MeshMaterial>::iterator mit = meshobj->GetFirstMaterial();
1258                 mit != meshobj->GetLastMaterial(); ++ mit) {
1259                 mit->m_bucket->GetPolyMaterial()->OnConstruction(lightlayer);
1260         }
1261
1262         if (layers)
1263                 delete []layers;
1264         
1265         dm->release(dm);
1266         // cleanup material
1267         if (bl_mat)
1268                 delete bl_mat;
1269         if (kx_blmat)
1270                 delete kx_blmat;
1271         if (kx_polymat)
1272                 delete kx_polymat;
1273         converter->RegisterGameMesh(meshobj, mesh);
1274         return meshobj;
1275 }
1276
1277         
1278         
1279 static PHY_MaterialProps *CreateMaterialFromBlenderObject(struct Object* blenderobject)
1280 {
1281         PHY_MaterialProps *materialProps = new PHY_MaterialProps;
1282         
1283         MT_assert(materialProps && "Create physics material properties failed");
1284                 
1285         Material* blendermat = give_current_material(blenderobject, 0);
1286                 
1287         if (blendermat)
1288         {
1289                 MT_assert(0.0f <= blendermat->reflect && blendermat->reflect <= 1.0f);
1290         
1291                 materialProps->m_restitution = blendermat->reflect;
1292                 materialProps->m_friction = blendermat->friction;
1293                 materialProps->m_fh_spring = blendermat->fh;
1294                 materialProps->m_fh_damping = blendermat->xyfrict;
1295                 materialProps->m_fh_distance = blendermat->fhdist;
1296                 materialProps->m_fh_normal = (blendermat->dynamode & MA_FH_NOR) != 0;
1297         }
1298         else {
1299                 //give some defaults
1300                 materialProps->m_restitution = 0.f;
1301                 materialProps->m_friction = 0.5;
1302                 materialProps->m_fh_spring = 0.f;
1303                 materialProps->m_fh_damping = 0.f;
1304                 materialProps->m_fh_distance = 0.f;
1305                 materialProps->m_fh_normal = false;
1306
1307         }
1308         
1309         return materialProps;
1310 }
1311
1312 static PHY_ShapeProps *CreateShapePropsFromBlenderObject(struct Object* blenderobject)
1313 {
1314         PHY_ShapeProps *shapeProps = new PHY_ShapeProps;
1315         
1316         MT_assert(shapeProps);
1317                 
1318         shapeProps->m_mass = blenderobject->mass;
1319         
1320 //  This needs to be fixed in blender. For now, we use:
1321         
1322 // in Blender, inertia stands for the size value which is equivalent to
1323 // the sphere radius
1324         shapeProps->m_inertia = blenderobject->formfactor;
1325         
1326         MT_assert(0.0f <= blenderobject->damping && blenderobject->damping <= 1.0f);
1327         MT_assert(0.0f <= blenderobject->rdamping && blenderobject->rdamping <= 1.0f);
1328         
1329         shapeProps->m_lin_drag = 1.0 - blenderobject->damping;
1330         shapeProps->m_ang_drag = 1.0 - blenderobject->rdamping;
1331         
1332         shapeProps->m_friction_scaling[0] = blenderobject->anisotropicFriction[0]; 
1333         shapeProps->m_friction_scaling[1] = blenderobject->anisotropicFriction[1];
1334         shapeProps->m_friction_scaling[2] = blenderobject->anisotropicFriction[2];
1335         shapeProps->m_do_anisotropic = ((blenderobject->gameflag & OB_ANISOTROPIC_FRICTION) != 0);
1336         
1337         shapeProps->m_do_fh     = (blenderobject->gameflag & OB_DO_FH) != 0; 
1338         shapeProps->m_do_rot_fh = (blenderobject->gameflag & OB_ROT_FH) != 0;
1339         
1340 //      velocity clamping XXX
1341         shapeProps->m_clamp_vel_min = blenderobject->min_vel;
1342         shapeProps->m_clamp_vel_max = blenderobject->max_vel;
1343         
1344         return shapeProps;
1345 }
1346
1347         
1348         
1349         
1350                 
1351 //////////////////////////////////////////////////////////
1352         
1353
1354
1355 static float my_boundbox_mesh(Mesh *me, float *loc, float *size)
1356 {
1357         MVert *mvert;
1358         BoundBox *bb;
1359         float min[3], max[3];
1360         float mloc[3], msize[3];
1361         float radius=0.0f, vert_radius, *co;
1362         int a;
1363         
1364         if (me->bb==0) me->bb= (struct BoundBox *)MEM_callocN(sizeof(BoundBox), "boundbox");
1365         bb= me->bb;
1366         
1367         INIT_MINMAX(min, max);
1368
1369         if (!loc) loc= mloc;
1370         if (!size) size= msize;
1371         
1372         mvert= me->mvert;
1373         for (a=0; a<me->totvert; a++, mvert++) {
1374                 co= mvert->co;
1375                 
1376                 /* bounds */
1377                 DO_MINMAX(co, min, max);
1378                 
1379                 /* radius */
1380                 vert_radius= co[0]*co[0] + co[1]*co[1] + co[2]*co[2];
1381                 if (vert_radius > radius)
1382                         radius= vert_radius;
1383         }
1384                 
1385         if (me->totvert) {
1386                 loc[0]= (min[0]+max[0])/2.0f;
1387                 loc[1]= (min[1]+max[1])/2.0f;
1388                 loc[2]= (min[2]+max[2])/2.0f;
1389                 
1390                 size[0]= (max[0]-min[0])/2.0f;
1391                 size[1]= (max[1]-min[1])/2.0f;
1392                 size[2]= (max[2]-min[2])/2.0f;
1393         }
1394         else {
1395                 loc[0]= loc[1]= loc[2]= 0.0f;
1396                 size[0]= size[1]= size[2]= 0.0f;
1397         }
1398                 
1399         bb->vec[0][0]=bb->vec[1][0]=bb->vec[2][0]=bb->vec[3][0]= loc[0]-size[0];
1400         bb->vec[4][0]=bb->vec[5][0]=bb->vec[6][0]=bb->vec[7][0]= loc[0]+size[0];
1401                 
1402         bb->vec[0][1]=bb->vec[1][1]=bb->vec[4][1]=bb->vec[5][1]= loc[1]-size[1];
1403         bb->vec[2][1]=bb->vec[3][1]=bb->vec[6][1]=bb->vec[7][1]= loc[1]+size[1];
1404
1405         bb->vec[0][2]=bb->vec[3][2]=bb->vec[4][2]=bb->vec[7][2]= loc[2]-size[2];
1406         bb->vec[1][2]=bb->vec[2][2]=bb->vec[5][2]=bb->vec[6][2]= loc[2]+size[2];
1407
1408         return sqrt(radius);
1409 }
1410                 
1411
1412
1413
1414 static void my_tex_space_mesh(Mesh *me)
1415 {
1416         KeyBlock *kb;
1417         float *fp, loc[3], size[3], min[3], max[3];
1418         int a;
1419
1420         my_boundbox_mesh(me, loc, size);
1421         
1422         if (me->texflag & ME_AUTOSPACE) {
1423                 if (me->key) {
1424                         kb= me->key->refkey;
1425                         if (kb) {
1426
1427                                 INIT_MINMAX(min, max);
1428
1429                                 fp= (float *)kb->data;
1430                                 for (a=0; a<kb->totelem; a++, fp+=3) {
1431                                         DO_MINMAX(fp, min, max);
1432                                 }
1433                                 if (kb->totelem) {
1434                                         loc[0]= (min[0]+max[0])/2.0f; loc[1]= (min[1]+max[1])/2.0f; loc[2]= (min[2]+max[2])/2.0f;
1435                                         size[0]= (max[0]-min[0])/2.0f; size[1]= (max[1]-min[1])/2.0f; size[2]= (max[2]-min[2])/2.0f;
1436                                 }
1437                                 else {
1438                                         loc[0]= loc[1]= loc[2]= 0.0;
1439                                         size[0]= size[1]= size[2]= 0.0;
1440                                 }
1441                                 
1442                         }
1443                 }
1444
1445                 copy_v3_v3(me->loc, loc);
1446                 copy_v3_v3(me->size, size);
1447                 me->rot[0]= me->rot[1]= me->rot[2]= 0.0f;
1448
1449                 if (me->size[0]==0.0) me->size[0]= 1.0f;
1450                 else if (me->size[0]>0.0 && me->size[0]< 0.00001f) me->size[0]= 0.00001f;
1451                 else if (me->size[0]<0.0 && me->size[0]> -0.00001f) me->size[0]= -0.00001f;
1452
1453                 if (me->size[1]==0.0) me->size[1]= 1.0f;
1454                 else if (me->size[1]>0.0 && me->size[1]< 0.00001f) me->size[1]= 0.00001f;
1455                 else if (me->size[1]<0.0 && me->size[1]> -0.00001f) me->size[1]= -0.00001f;
1456
1457                 if (me->size[2]==0.0) me->size[2]= 1.0f;
1458                 else if (me->size[2]>0.0 && me->size[2]< 0.00001f) me->size[2]= 0.00001f;
1459                 else if (me->size[2]<0.0 && me->size[2]> -0.00001f) me->size[2]= -0.00001f;
1460         }
1461         
1462 }
1463
1464 static void my_get_local_bounds(Object *ob, DerivedMesh *dm, float *center, float *size)
1465 {
1466         BoundBox *bb= NULL;
1467         /* uses boundbox, function used by Ketsji */
1468         switch (ob->type)
1469         {
1470                 case OB_MESH:
1471                         if (dm)
1472                         {
1473                                 float min_r[3], max_r[3];
1474                                 INIT_MINMAX(min_r, max_r);
1475                                 dm->getMinMax(dm, min_r, max_r);
1476                                 size[0]= 0.5f*fabsf(max_r[0] - min_r[0]);
1477                                 size[1]= 0.5f*fabsf(max_r[1] - min_r[1]);
1478                                 size[2]= 0.5f*fabsf(max_r[2] - min_r[2]);
1479                                         
1480                                 center[0]= 0.5f*(max_r[0] + min_r[0]);
1481                                 center[1]= 0.5f*(max_r[1] + min_r[1]);
1482                                 center[2]= 0.5f*(max_r[2] + min_r[2]);
1483                                 return;
1484                         } else
1485                         {
1486                                 bb= ( (Mesh *)ob->data )->bb;
1487                                 if (bb==0) 
1488                                 {
1489                                         my_tex_space_mesh((struct Mesh *)ob->data);
1490                                         bb= ( (Mesh *)ob->data )->bb;
1491                                 }
1492                         }
1493                         break;
1494                 case OB_CURVE:
1495                 case OB_SURF:
1496                         center[0]= center[1]= center[2]= 0.0;
1497                         size[0]  = size[1]=size[2]=0.0;
1498                         break;
1499                 case OB_FONT:
1500                         center[0]= center[1]= center[2]= 0.0;
1501                         size[0]  = size[1]=size[2]=1.0;
1502                         break;
1503                 case OB_MBALL:
1504                         bb= ob->bb;
1505                         break;
1506         }
1507         
1508         if (bb==NULL) 
1509         {
1510                 center[0]= center[1]= center[2]= 0.0;
1511                 size[0] = size[1]=size[2]=1.0;
1512         }
1513         else 
1514         {
1515                 size[0]= 0.5f*fabs(bb->vec[0][0] - bb->vec[4][0]);
1516                 size[1]= 0.5f*fabs(bb->vec[0][1] - bb->vec[2][1]);
1517                 size[2]= 0.5f*fabs(bb->vec[0][2] - bb->vec[1][2]);
1518                                         
1519                 center[0]= 0.5f*(bb->vec[0][0] + bb->vec[4][0]);
1520                 center[1]= 0.5f*(bb->vec[0][1] + bb->vec[2][1]);
1521                 center[2]= 0.5f*(bb->vec[0][2] + bb->vec[1][2]);
1522         }
1523 }
1524         
1525
1526
1527
1528 //////////////////////////////////////////////////////
1529
1530
1531 void BL_CreateGraphicObjectNew(KX_GameObject* gameobj,
1532                                                            const MT_Point3& localAabbMin,
1533                                                            const MT_Point3& localAabbMax,
1534                                                            KX_Scene* kxscene,
1535                                                            bool isActive,
1536                                                            e_PhysicsEngine physics_engine)
1537 {
1538         if (gameobj->GetMeshCount() > 0) 
1539         {
1540                 switch (physics_engine)
1541                 {
1542 #ifdef USE_BULLET
1543                 case UseBullet:
1544                         {
1545                                 CcdPhysicsEnvironment* env = (CcdPhysicsEnvironment*)kxscene->GetPhysicsEnvironment();
1546                                 assert(env);
1547                                 PHY_IMotionState* motionstate = new KX_MotionState(gameobj->GetSGNode());
1548                                 CcdGraphicController* ctrl = new CcdGraphicController(env, motionstate);
1549                                 gameobj->SetGraphicController(ctrl);
1550                                 ctrl->setNewClientInfo(gameobj->getClientInfo());
1551                                 ctrl->setLocalAabb(localAabbMin, localAabbMax);
1552                                 if (isActive) {
1553                                         // add first, this will create the proxy handle, only if the object is visible
1554                                         if (gameobj->GetVisible())
1555                                                 env->addCcdGraphicController(ctrl);
1556                                         // update the mesh if there is a deformer, this will also update the bounding box for modifiers
1557                                         RAS_Deformer* deformer = gameobj->GetDeformer();
1558                                         if (deformer)
1559                                                 deformer->UpdateBuckets();
1560                                 }
1561                         }
1562                         break;
1563 #endif
1564                 default:
1565                         break;
1566                 }
1567         }
1568 }
1569
1570 void BL_CreatePhysicsObjectNew(KX_GameObject* gameobj,
1571                                                  struct Object* blenderobject,
1572                                                  RAS_MeshObject* meshobj,
1573                                                  KX_Scene* kxscene,
1574                                                  int activeLayerBitInfo,
1575                                                  e_PhysicsEngine        physics_engine,
1576                                                  KX_BlenderSceneConverter *converter,
1577                                                  bool processCompoundChildren
1578                                                  )
1579                                         
1580 {
1581         //SYS_SystemHandle syshandle = SYS_GetSystem(); /*unused*/
1582         //int userigidbody = SYS_GetCommandLineInt(syshandle,"norigidbody",0);
1583         //bool bRigidBody = (userigidbody == 0);
1584
1585         // object has physics representation?
1586         if (!(blenderobject->gameflag & OB_COLLISION))
1587                 return;
1588
1589         // get Root Parent of blenderobject
1590         struct Object* parent= blenderobject->parent;
1591         while(parent && parent->parent) {
1592                 parent= parent->parent;
1593         }
1594
1595         bool isCompoundChild = false;
1596         bool hasCompoundChildren = !parent && (blenderobject->gameflag & OB_CHILD);
1597
1598         /* When the parent is not OB_DYNAMIC and has no OB_COLLISION then it gets no bullet controller
1599          * and cant be apart of the parents compound shape */
1600         if (parent && (parent->gameflag & (OB_DYNAMIC | OB_COLLISION))) {
1601                 
1602                 if ((parent->gameflag & OB_CHILD) != 0 && (blenderobject->gameflag & OB_CHILD))
1603                 {
1604                         isCompoundChild = true;
1605                 } 
1606         }
1607         if (processCompoundChildren != isCompoundChild)
1608                 return;
1609
1610
1611         PHY_ShapeProps* shapeprops =
1612                         CreateShapePropsFromBlenderObject(blenderobject);
1613
1614         
1615         PHY_MaterialProps* smmaterial = 
1616                 CreateMaterialFromBlenderObject(blenderobject);
1617                                         
1618         KX_ObjectProperties objprop;
1619         objprop.m_lockXaxis = (blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_X_AXIS) !=0;
1620         objprop.m_lockYaxis = (blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_Y_AXIS) !=0;
1621         objprop.m_lockZaxis = (blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_Z_AXIS) !=0;
1622         objprop.m_lockXRotaxis = (blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_X_ROT_AXIS) !=0;
1623         objprop.m_lockYRotaxis = (blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_Y_ROT_AXIS) !=0;
1624         objprop.m_lockZRotaxis = (blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_Z_ROT_AXIS) !=0;
1625
1626         objprop.m_isCompoundChild = isCompoundChild;
1627         objprop.m_hasCompoundChildren = hasCompoundChildren;
1628         objprop.m_margin = blenderobject->margin;
1629         
1630         // ACTOR is now a separate feature
1631         objprop.m_isactor = (blenderobject->gameflag & OB_ACTOR)!=0;
1632         objprop.m_dyna = (blenderobject->gameflag & OB_DYNAMIC) != 0;
1633         objprop.m_softbody = (blenderobject->gameflag & OB_SOFT_BODY) != 0;
1634         objprop.m_angular_rigidbody = (blenderobject->gameflag & OB_RIGID_BODY) != 0;
1635         
1636         ///contact processing threshold is only for rigid bodies and static geometry, not 'dynamic'
1637         if (objprop.m_angular_rigidbody || !objprop.m_dyna )
1638         {
1639                 objprop.m_contactProcessingThreshold = blenderobject->m_contactProcessingThreshold;
1640         } else
1641         {
1642                 objprop.m_contactProcessingThreshold = 0.f;
1643         }
1644
1645         objprop.m_sensor = (blenderobject->gameflag & OB_SENSOR) != 0;
1646         
1647         if (objprop.m_softbody)
1648         {
1649                 ///for game soft bodies
1650                 if (blenderobject->bsoft)
1651                 {
1652                         objprop.m_gamesoftFlag = blenderobject->bsoft->flag;
1653                                         ///////////////////
1654                         objprop.m_soft_linStiff = blenderobject->bsoft->linStiff;
1655                         objprop.m_soft_angStiff = blenderobject->bsoft->angStiff;               /* angular stiffness 0..1 */
1656                         objprop.m_soft_volume= blenderobject->bsoft->volume;                    /* volume preservation 0..1 */
1657
1658                         objprop.m_soft_viterations= blenderobject->bsoft->viterations;          /* Velocities solver iterations */
1659                         objprop.m_soft_piterations= blenderobject->bsoft->piterations;          /* Positions solver iterations */
1660                         objprop.m_soft_diterations= blenderobject->bsoft->diterations;          /* Drift solver iterations */
1661                         objprop.m_soft_citerations= blenderobject->bsoft->citerations;          /* Cluster solver iterations */
1662
1663                         objprop.m_soft_kSRHR_CL= blenderobject->bsoft->kSRHR_CL;                /* Soft vs rigid hardness [0,1] (cluster only) */
1664                         objprop.m_soft_kSKHR_CL= blenderobject->bsoft->kSKHR_CL;                /* Soft vs kinetic hardness [0,1] (cluster only) */
1665                         objprop.m_soft_kSSHR_CL= blenderobject->bsoft->kSSHR_CL;                /* Soft vs soft hardness [0,1] (cluster only) */
1666                         objprop.m_soft_kSR_SPLT_CL= blenderobject->bsoft->kSR_SPLT_CL;  /* Soft vs rigid impulse split [0,1] (cluster only) */
1667
1668                         objprop.m_soft_kSK_SPLT_CL= blenderobject->bsoft->kSK_SPLT_CL;  /* Soft vs rigid impulse split [0,1] (cluster only) */
1669                         objprop.m_soft_kSS_SPLT_CL= blenderobject->bsoft->kSS_SPLT_CL;  /* Soft vs rigid impulse split [0,1] (cluster only) */
1670                         objprop.m_soft_kVCF= blenderobject->bsoft->kVCF;                        /* Velocities correction factor (Baumgarte) */
1671                         objprop.m_soft_kDP= blenderobject->bsoft->kDP;                  /* Damping coefficient [0,1] */
1672
1673                         objprop.m_soft_kDG= blenderobject->bsoft->kDG;                  /* Drag coefficient [0,+inf] */
1674                         objprop.m_soft_kLF= blenderobject->bsoft->kLF;                  /* Lift coefficient [0,+inf] */
1675                         objprop.m_soft_kPR= blenderobject->bsoft->kPR;                  /* Pressure coefficient [-inf,+inf] */
1676                         objprop.m_soft_kVC= blenderobject->bsoft->kVC;                  /* Volume conversation coefficient [0,+inf] */
1677
1678                         objprop.m_soft_kDF= blenderobject->bsoft->kDF;                  /* Dynamic friction coefficient [0,1] */
1679                         objprop.m_soft_kMT= blenderobject->bsoft->kMT;                  /* Pose matching coefficient [0,1] */
1680                         objprop.m_soft_kCHR= blenderobject->bsoft->kCHR;                        /* Rigid contacts hardness [0,1] */
1681                         objprop.m_soft_kKHR= blenderobject->bsoft->kKHR;                        /* Kinetic contacts hardness [0,1] */
1682
1683                         objprop.m_soft_kSHR= blenderobject->bsoft->kSHR;                        /* Soft contacts hardness [0,1] */
1684                         objprop.m_soft_kAHR= blenderobject->bsoft->kAHR;                        /* Anchors hardness [0,1] */
1685                         objprop.m_soft_collisionflags= blenderobject->bsoft->collisionflags;    /* Vertex/Face or Signed Distance Field(SDF) or Clusters, Soft versus Soft or Rigid */
1686                         objprop.m_soft_numclusteriterations= blenderobject->bsoft->numclusteriterations;        /* number of iterations to refine collision clusters*/
1687                         //objprop.m_soft_welding = blenderobject->bsoft->welding;               /* welding */
1688                         /* disable welding: it doesn't bring any additional stability and it breaks the relation between soft body collision shape and graphic mesh */
1689                         objprop.m_soft_welding = 0.f;           
1690                         objprop.m_margin = blenderobject->bsoft->margin;
1691                         objprop.m_contactProcessingThreshold = 0.f;
1692                 } else
1693                 {
1694                         objprop.m_gamesoftFlag = OB_BSB_BENDING_CONSTRAINTS | OB_BSB_SHAPE_MATCHING | OB_BSB_AERO_VPOINT;
1695                         
1696                         objprop.m_soft_linStiff = 0.5;
1697                         objprop.m_soft_angStiff = 1.f;          /* angular stiffness 0..1 */
1698                         objprop.m_soft_volume= 1.f;                     /* volume preservation 0..1 */
1699
1700
1701                         objprop.m_soft_viterations= 0;
1702                         objprop.m_soft_piterations= 1;
1703                         objprop.m_soft_diterations= 0;
1704                         objprop.m_soft_citerations= 4;
1705
1706                         objprop.m_soft_kSRHR_CL= 0.1f;
1707                         objprop.m_soft_kSKHR_CL= 1.f;
1708                         objprop.m_soft_kSSHR_CL= 0.5;
1709                         objprop.m_soft_kSR_SPLT_CL= 0.5f;
1710
1711                         objprop.m_soft_kSK_SPLT_CL= 0.5f;
1712                         objprop.m_soft_kSS_SPLT_CL= 0.5f;
1713                         objprop.m_soft_kVCF=  1;
1714                         objprop.m_soft_kDP= 0;
1715
1716                         objprop.m_soft_kDG= 0;
1717                         objprop.m_soft_kLF= 0;
1718                         objprop.m_soft_kPR= 0;
1719                         objprop.m_soft_kVC= 0;
1720
1721                         objprop.m_soft_kDF= 0.2f;
1722                         objprop.m_soft_kMT= 0.05f;
1723                         objprop.m_soft_kCHR= 1.0f;
1724                         objprop.m_soft_kKHR= 0.1f;
1725
1726                         objprop.m_soft_kSHR= 1.f;
1727                         objprop.m_soft_kAHR= 0.7f;
1728                         objprop.m_soft_collisionflags= OB_BSB_COL_SDF_RS + OB_BSB_COL_VF_SS;
1729                         objprop.m_soft_numclusteriterations= 16;
1730                         objprop.m_soft_welding = 0.f;
1731                         objprop.m_margin = 0.f;
1732                         objprop.m_contactProcessingThreshold = 0.f;
1733                 }
1734         }
1735
1736         objprop.m_ghost = (blenderobject->gameflag & OB_GHOST) != 0;
1737         objprop.m_disableSleeping = (blenderobject->gameflag & OB_COLLISION_RESPONSE) != 0;//abuse the OB_COLLISION_RESPONSE flag
1738         //mmm, for now, taks this for the size of the dynamicobject
1739         // Blender uses inertia for radius of dynamic object
1740         objprop.m_radius = blenderobject->inertia;
1741         objprop.m_in_active_layer = (blenderobject->lay & activeLayerBitInfo) != 0;
1742         objprop.m_dynamic_parent=NULL;
1743         objprop.m_isdeformable = ((blenderobject->gameflag2 & 2)) != 0;
1744         objprop.m_boundclass = objprop.m_dyna?KX_BOUNDSPHERE:KX_BOUNDMESH;
1745         
1746         if ((blenderobject->gameflag & OB_SOFT_BODY) && !(blenderobject->gameflag & OB_BOUNDS))
1747         {
1748                 objprop.m_boundclass = KX_BOUNDMESH;
1749         }
1750
1751         KX_BoxBounds bb;
1752         DerivedMesh* dm = NULL;
1753         if (gameobj->GetDeformer())
1754                 dm = gameobj->GetDeformer()->GetPhysicsMesh();
1755         my_get_local_bounds(blenderobject,dm,objprop.m_boundobject.box.m_center,bb.m_extends);
1756         if (blenderobject->gameflag & OB_BOUNDS)
1757         {
1758                 switch (blenderobject->collision_boundtype)
1759                 {
1760                         case OB_BOUND_BOX:
1761                                 objprop.m_boundclass = KX_BOUNDBOX;
1762                                 //mmm, has to be divided by 2 to be proper extends
1763                                 objprop.m_boundobject.box.m_extends[0]=2.f*bb.m_extends[0];
1764                                 objprop.m_boundobject.box.m_extends[1]=2.f*bb.m_extends[1];
1765                                 objprop.m_boundobject.box.m_extends[2]=2.f*bb.m_extends[2];
1766                                 break;
1767                         case OB_BOUND_CONVEX_HULL:
1768                                 if (blenderobject->type == OB_MESH)
1769                                 {
1770                                         objprop.m_boundclass = KX_BOUNDPOLYTOPE;
1771                                         break;
1772                                 }
1773                                 // Object is not a mesh... fall through OB_BOUND_TRIANGLE_MESH to
1774                                 // OB_BOUND_SPHERE
1775                         case OB_BOUND_TRIANGLE_MESH:
1776                                 if (blenderobject->type == OB_MESH)
1777                                 {
1778                                         objprop.m_boundclass = KX_BOUNDMESH;
1779                                         break;
1780                                 }
1781                                 // Object is not a mesh... can't use polyhedron.
1782                                 // Fall through and become a sphere.
1783                         case OB_BOUND_SPHERE:
1784                         {
1785                                 objprop.m_boundclass = KX_BOUNDSPHERE;
1786                                 objprop.m_boundobject.c.m_radius = MT_max(bb.m_extends[0], MT_max(bb.m_extends[1], bb.m_extends[2]));
1787                                 break;
1788                         }
1789                         case OB_BOUND_CYLINDER:
1790                         {
1791                                 objprop.m_boundclass = KX_BOUNDCYLINDER;
1792                                 objprop.m_boundobject.c.m_radius = MT_max(bb.m_extends[0], bb.m_extends[1]);
1793                                 objprop.m_boundobject.c.m_height = 2.f*bb.m_extends[2];
1794                                 break;
1795                         }
1796                         case OB_BOUND_CONE:
1797                         {
1798                                 objprop.m_boundclass = KX_BOUNDCONE;
1799                                 objprop.m_boundobject.c.m_radius = MT_max(bb.m_extends[0], bb.m_extends[1]);
1800                                 objprop.m_boundobject.c.m_height = 2.f*bb.m_extends[2];
1801                                 break;
1802                         }
1803                         case OB_BOUND_CAPSULE:
1804                         {
1805                                 objprop.m_boundclass = KX_BOUNDCAPSULE;
1806                                 objprop.m_boundobject.c.m_radius = MT_max(bb.m_extends[0], bb.m_extends[1]);
1807                                 objprop.m_boundobject.c.m_height = 2.f*(bb.m_extends[2]-objprop.m_boundobject.c.m_radius);
1808                                 if (objprop.m_boundobject.c.m_height < 0.f)
1809                                         objprop.m_boundobject.c.m_height = 0.f;
1810                                 break;
1811                         }
1812                 }
1813         }
1814
1815         
1816         if (parent/* && (parent->gameflag & OB_DYNAMIC)*/) {
1817                 // parented object cannot be dynamic
1818                 KX_GameObject *parentgameobject = converter->FindGameObject(parent);
1819                 objprop.m_dynamic_parent = parentgameobject;
1820                 //cannot be dynamic:
1821                 objprop.m_dyna = false;
1822                 objprop.m_softbody = false;
1823                 shapeprops->m_mass = 0.f;
1824         }
1825
1826         
1827         objprop.m_concave = (blenderobject->collision_boundtype == OB_BOUND_TRIANGLE_MESH);
1828         
1829         switch (physics_engine)
1830         {
1831 #ifdef USE_BULLET
1832                 case UseBullet:
1833                         KX_ConvertBulletObject(gameobj, meshobj, dm, kxscene, shapeprops, smmaterial, &objprop);
1834                         break;
1835
1836 #endif
1837                 case UseDynamo:
1838                         //KX_ConvertDynamoObject(gameobj,meshobj,kxscene,shapeprops,    smmaterial,     &objprop);
1839                         break;
1840                         
1841                 case UseNone:
1842                 default:
1843                         break;
1844         }
1845         delete shapeprops;
1846         delete smmaterial;
1847         if (dm) {
1848                 dm->needsFree = 1;
1849                 dm->release(dm);
1850         }
1851 }
1852
1853
1854
1855
1856
1857 static KX_LightObject *gamelight_from_blamp(Object *ob, Lamp *la, unsigned int layerflag, KX_Scene *kxscene, RAS_IRenderTools *rendertools, KX_BlenderSceneConverter *converter)
1858 {
1859         RAS_LightObject lightobj;
1860         KX_LightObject *gamelight;
1861         
1862         lightobj.m_att1 = la->att1;
1863         lightobj.m_att2 = (la->mode & LA_QUAD) ? la->att2 : 0.0f;
1864         lightobj.m_red = la->r;
1865         lightobj.m_green = la->g;
1866         lightobj.m_blue = la->b;
1867         lightobj.m_distance = la->dist;
1868         lightobj.m_energy = la->energy;
1869         lightobj.m_layer = layerflag;
1870         lightobj.m_spotblend = la->spotblend;
1871         lightobj.m_spotsize = la->spotsize;
1872         
1873         lightobj.m_nodiffuse = (la->mode & LA_NO_DIFF) != 0;
1874         lightobj.m_nospecular = (la->mode & LA_NO_SPEC) != 0;
1875         
1876         bool glslmat = converter->GetGLSLMaterials();
1877
1878         // in GLSL NEGATIVE LAMP is handled inside the lamp update function
1879         if (glslmat==0) {
1880                 if (la->mode & LA_NEG)
1881                 {
1882                         lightobj.m_red = -lightobj.m_red;
1883                         lightobj.m_green = -lightobj.m_green;
1884                         lightobj.m_blue = -lightobj.m_blue;
1885                 }
1886         }
1887                 
1888         if (la->type==LA_SUN) {
1889                 lightobj.m_type = RAS_LightObject::LIGHT_SUN;
1890         } else if (la->type==LA_SPOT) {
1891                 lightobj.m_type = RAS_LightObject::LIGHT_SPOT;
1892         } else {
1893                 lightobj.m_type = RAS_LightObject::LIGHT_NORMAL;
1894         }
1895
1896         gamelight = new KX_LightObject(kxscene, KX_Scene::m_callbacks, rendertools,
1897                 lightobj, glslmat);
1898         
1899         return gamelight;
1900 }
1901
1902 static KX_Camera *gamecamera_from_bcamera(Object *ob, KX_Scene *kxscene, KX_BlenderSceneConverter *converter)
1903 {
1904         Camera* ca = static_cast<Camera*>(ob->data);
1905         RAS_CameraData camdata(ca->lens, ca->ortho_scale, ca->sensor_x, ca->sensor_y, ca->sensor_fit, ca->clipsta, ca->clipend, ca->type == CAM_PERSP, ca->YF_dofdist);
1906         KX_Camera *gamecamera;
1907         
1908         gamecamera= new KX_Camera(kxscene, KX_Scene::m_callbacks, camdata);
1909         gamecamera->SetName(ca->id.name + 2);
1910         
1911         return gamecamera;
1912 }
1913
1914 static KX_GameObject *gameobject_from_blenderobject(
1915                                                                 Object *ob, 
1916                                                                 KX_Scene *kxscene, 
1917                                                                 RAS_IRenderTools *rendertools, 
1918                                                                 KX_BlenderSceneConverter *converter) 
1919 {
1920         KX_GameObject *gameobj = NULL;
1921         Scene *blenderscene = kxscene->GetBlenderScene();
1922         
1923         switch(ob->type)
1924         {
1925         case OB_LAMP:
1926         {
1927                 KX_LightObject* gamelight = gamelight_from_blamp(ob, static_cast<Lamp*>(ob->data), ob->lay, kxscene, rendertools, converter);
1928                 gameobj = gamelight;
1929                 
1930                 if (blenderscene->lay & ob->lay)
1931                 {
1932                         gamelight->AddRef();
1933                         kxscene->GetLightList()->Add(gamelight);
1934                 }
1935
1936                 break;
1937         }
1938         
1939         case OB_CAMERA:
1940         {
1941                 KX_Camera* gamecamera = gamecamera_from_bcamera(ob, kxscene, converter);
1942                 gameobj = gamecamera;
1943                 
1944                 //don't add a reference: the camera list in kxscene->m_cameras is not released at the end
1945                 //gamecamera->AddRef();
1946                 kxscene->AddCamera(gamecamera);
1947                 
1948                 break;
1949         }
1950         
1951         case OB_MESH:
1952         {
1953                 Mesh* mesh = static_cast<Mesh*>(ob->data);
1954                 float center[3], extents[3];
1955                 float radius = my_boundbox_mesh((Mesh*) ob->data, center, extents);
1956                 RAS_MeshObject* meshobj = BL_ConvertMesh(mesh,ob,kxscene,converter);
1957                 
1958                 // needed for python scripting
1959                 kxscene->GetLogicManager()->RegisterMeshName(meshobj->GetName(),meshobj);
1960
1961                 if (ob->gameflag & OB_NAVMESH)
1962                 {
1963                         gameobj = new KX_NavMeshObject(kxscene,KX_Scene::m_callbacks);
1964                         gameobj->AddMesh(meshobj);
1965                         break;
1966                 }
1967
1968                 gameobj = new BL_DeformableGameObject(ob,kxscene,KX_Scene::m_callbacks);
1969         
1970                 // set transformation
1971                 gameobj->AddMesh(meshobj);
1972         
1973                 // for all objects: check whether they want to
1974                 // respond to updates
1975                 bool ignoreActivityCulling =  
1976                         ((ob->gameflag2 & OB_NEVER_DO_ACTIVITY_CULLING)!=0);
1977                 gameobj->SetIgnoreActivityCulling(ignoreActivityCulling);
1978                 gameobj->SetOccluder((ob->gameflag & OB_OCCLUDER) != 0, false);
1979         
1980                 // two options exists for deform: shape keys and armature
1981                 // only support relative shape key
1982                 bool bHasShapeKey = mesh->key != NULL && mesh->key->type==KEY_RELATIVE;
1983                 bool bHasDvert = mesh->dvert != NULL && ob->defbase.first;
1984                 bool bHasArmature = (BL_ModifierDeformer::HasArmatureDeformer(ob) && ob->parent && ob->parent->type == OB_ARMATURE && bHasDvert);
1985                 bool bHasModifier = BL_ModifierDeformer::HasCompatibleDeformer(ob);
1986 #ifdef USE_BULLET
1987                 bool bHasSoftBody = (!ob->parent && (ob->gameflag & OB_SOFT_BODY));
1988 #endif
1989                 if (bHasModifier) {
1990                         BL_ModifierDeformer *dcont = new BL_ModifierDeformer((BL_DeformableGameObject *)gameobj,
1991                                                                                                                                 kxscene->GetBlenderScene(), ob, meshobj);
1992                         ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
1993                         if (bHasShapeKey && bHasArmature)
1994                                 dcont->LoadShapeDrivers(ob->parent);
1995                 } else if (bHasShapeKey) {
1996                         // not that we can have shape keys without dvert! 
1997                         BL_ShapeDeformer *dcont = new BL_ShapeDeformer((BL_DeformableGameObject*)gameobj, 
1998                                                                                                                         ob, meshobj);
1999                         ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
2000                         if (bHasArmature)
2001                                 dcont->LoadShapeDrivers(ob->parent);
2002                 } else if (bHasArmature) {
2003                         BL_SkinDeformer *dcont = new BL_SkinDeformer((BL_DeformableGameObject*)gameobj,
2004                                                                                                                         ob, meshobj);
2005                         ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
2006                 } else if (bHasDvert) {
2007                         // this case correspond to a mesh that can potentially deform but not with the
2008                         // object to which it is attached for the moment. A skin mesh was created in
2009                         // BL_ConvertMesh() so must create a deformer too!
2010                         BL_MeshDeformer *dcont = new BL_MeshDeformer((BL_DeformableGameObject*)gameobj,
2011                                                                                                                   ob, meshobj);
2012                         ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
2013 #ifdef USE_BULLET
2014                 } else if (bHasSoftBody) {
2015                         KX_SoftBodyDeformer *dcont = new KX_SoftBodyDeformer(meshobj, (BL_DeformableGameObject*)gameobj);
2016                         ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
2017 #endif
2018                 }
2019                 
2020                 MT_Point3 min = MT_Point3(center) - MT_Vector3(extents);
2021                 MT_Point3 max = MT_Point3(center) + MT_Vector3(extents);
2022                 SG_BBox bbox = SG_BBox(min, max);
2023                 gameobj->GetSGNode()->SetBBox(bbox);
2024                 gameobj->GetSGNode()->SetRadius(radius);
2025         
2026                 break;
2027         }
2028         
2029         case OB_ARMATURE:
2030         {
2031                 bArmature *arm = (bArmature*)ob->data;
2032                 gameobj = new BL_ArmatureObject(
2033                         kxscene,
2034                         KX_Scene::m_callbacks,
2035                         ob,
2036                         kxscene->GetBlenderScene(), // handle
2037                         arm->gevertdeformer
2038                 );
2039                 /* Get the current pose from the armature object and apply it as the rest pose */
2040                 break;
2041         }
2042         
2043         case OB_EMPTY:
2044         {
2045                 gameobj = new KX_EmptyObject(kxscene,KX_Scene::m_callbacks);
2046                 // set transformation
2047                 break;
2048         }
2049
2050         case OB_FONT:
2051         {
2052                 /* font objects have no bounding box */
2053                 gameobj = new KX_FontObject(kxscene,KX_Scene::m_callbacks, rendertools, ob);
2054
2055                 /* add to the list only the visible fonts */
2056                 if ((ob->lay & kxscene->GetBlenderScene()->lay) != 0)
2057                         kxscene->AddFont(static_cast<KX_FontObject*>(gameobj));
2058                 break;
2059         }
2060
2061         }
2062         if (gameobj) 
2063         {
2064                 gameobj->SetLayer(ob->lay);
2065                 gameobj->SetBlenderObject(ob);
2066                 /* set the visibility state based on the objects render option in the outliner */
2067                 if (ob->restrictflag & OB_RESTRICT_RENDER) gameobj->SetVisible(0, 0);
2068         }
2069         return gameobj;
2070 }
2071
2072 struct parentChildLink {
2073         struct Object* m_blenderchild;
2074         SG_Node* m_gamechildnode;
2075 };
2076
2077 #include "DNA_constraint_types.h"
2078 //XXX #include "BIF_editconstraint.h"
2079
2080 bPoseChannel *get_active_posechannel2 (Object *ob)
2081 {
2082         bArmature *arm= (bArmature*)ob->data;
2083         bPoseChannel *pchan;
2084         
2085         /* find active */
2086         for (pchan= (bPoseChannel *)ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2087                 if (pchan->bone && (pchan->bone == arm->act_bone) && (pchan->bone->layer & arm->layer))
2088                         return pchan;
2089         }
2090         
2091         return NULL;
2092 }
2093
2094 ListBase *get_active_constraints2(Object *ob)
2095 {
2096         if (!ob)
2097                 return NULL;
2098
2099   // XXX - shouldnt we care about the pose data and not the mode???
2100         if (ob->mode & OB_MODE_POSE) { 
2101                 bPoseChannel *pchan;
2102
2103                 pchan = get_active_posechannel2(ob);
2104                 if (pchan)
2105                         return &pchan->constraints;
2106         }
2107         else 
2108                 return &ob->constraints;
2109
2110         return NULL;
2111 }
2112
2113
2114 void RBJconstraints(Object *ob)//not used
2115 {
2116         ListBase *conlist;
2117         bConstraint *curcon;
2118
2119         conlist = get_active_constraints2(ob);
2120
2121         if (conlist) {
2122                 for (curcon = (bConstraint *)conlist->first; curcon; curcon=(bConstraint *)curcon->next) {
2123
2124                         printf("%i\n",curcon->type);
2125                 }
2126
2127
2128         }
2129 }
2130
2131 #include "PHY_IPhysicsEnvironment.h"
2132 #include "KX_IPhysicsController.h"
2133 #include "PHY_DynamicTypes.h"
2134
2135 KX_IPhysicsController* getPhId(CListValue* sumolist,STR_String busc) {//not used
2136
2137         for (int j=0;j<sumolist->GetCount();j++)
2138         {
2139                 KX_GameObject* gameobje = (KX_GameObject*) sumolist->GetValue(j);
2140                 if (gameobje->GetName()==busc)
2141                         return gameobje->GetPhysicsController();
2142         }
2143
2144         return 0;
2145
2146 }
2147
2148 KX_GameObject* getGameOb(STR_String busc,CListValue* sumolist)
2149 {
2150
2151         for (int j=0;j<sumolist->GetCount();j++)
2152         {
2153                 KX_GameObject* gameobje = (KX_GameObject*) sumolist->GetValue(j);
2154                 if (gameobje->GetName()==busc)
2155                         return gameobje;
2156         }
2157         
2158         return 0;
2159
2160 }
2161
2162 /* helper for BL_ConvertBlenderObjects, avoids code duplication
2163  * note: all var names match args are passed from the caller */
2164 static void bl_ConvertBlenderObject_Single(
2165         KX_BlenderSceneConverter *converter,
2166         Scene *blenderscene, Object *blenderobject,
2167         vector<MT_Vector3> &inivel, vector<MT_Vector3> &iniang,
2168         vector<parentChildLink> &vec_parent_child,
2169         CListValue* logicbrick_conversionlist,
2170         CListValue* objectlist, CListValue* inactivelist, CListValue*   sumolist,
2171         KX_Scene* kxscene, KX_GameObject* gameobj,
2172         SCA_LogicManager* logicmgr, SCA_TimeEventManager* timemgr,
2173         bool isInActiveLayer
2174         )
2175 {
2176         MT_Point3 posPrev;
2177         MT_Matrix3x3 angor;
2178         if (converter->addInitFromFrame) blenderscene->r.cfra=blenderscene->r.sfra;
2179
2180         MT_Point3 pos(
2181                 blenderobject->loc[0]+blenderobject->dloc[0],
2182                 blenderobject->loc[1]+blenderobject->dloc[1],
2183                 blenderobject->loc[2]+blenderobject->dloc[2]
2184         );
2185         MT_Vector3 eulxyz(blenderobject->rot);
2186         MT_Vector3 scale(blenderobject->size);
2187         if (converter->addInitFromFrame) {//rcruiz
2188                 float eulxyzPrev[3];
2189                 blenderscene->r.cfra=blenderscene->r.sfra-1;
2190                 //XXX update_for_newframe();
2191                 MT_Vector3 tmp=pos-MT_Point3(blenderobject->loc[0]+blenderobject->dloc[0],
2192                                              blenderobject->loc[1]+blenderobject->dloc[1],
2193                                              blenderobject->loc[2]+blenderobject->dloc[2]
2194                                              );
2195                 eulxyzPrev[0]=blenderobject->rot[0];
2196                 eulxyzPrev[1]=blenderobject->rot[1];
2197                 eulxyzPrev[2]=blenderobject->rot[2];
2198
2199                 double fps = (double) blenderscene->r.frs_sec/
2200                         (double) blenderscene->r.frs_sec_base;
2201
2202                 tmp.scale(fps, fps, fps);
2203                 inivel.push_back(tmp);
2204                 tmp=eulxyz-eulxyzPrev;
2205                 tmp.scale(fps, fps, fps);
2206                 iniang.push_back(tmp);
2207                 blenderscene->r.cfra=blenderscene->r.sfra;
2208                 //XXX update_for_newframe();
2209         }
2210
2211         gameobj->NodeSetLocalPosition(pos);
2212         gameobj->NodeSetLocalOrientation(MT_Matrix3x3(eulxyz));
2213         gameobj->NodeSetLocalScale(scale);
2214         gameobj->NodeUpdateGS(0);
2215
2216         BL_ConvertMaterialIpos(blenderobject, gameobj, converter);
2217
2218         sumolist->Add(gameobj->AddRef());
2219
2220         BL_ConvertProperties(blenderobject,gameobj,timemgr,kxscene,isInActiveLayer);
2221
2222         gameobj->SetName(blenderobject->id.name + 2);
2223
2224         // update children/parent hierarchy
2225         if ((blenderobject->parent != 0)&&(!converter->addInitFromFrame))
2226         {
2227                 // blender has an additional 'parentinverse' offset in each object
2228                 SG_Callbacks callback(NULL,NULL,NULL,KX_Scene::KX_ScenegraphUpdateFunc,KX_Scene::KX_ScenegraphRescheduleFunc);
2229                 SG_Node* parentinversenode = new SG_Node(NULL,kxscene,callback);
2230
2231                 // define a normal parent relationship for this node.
2232                 KX_NormalParentRelation * parent_relation = KX_NormalParentRelation::New();
2233                 parentinversenode->SetParentRelation(parent_relation);
2234
2235                 parentChildLink pclink;
2236                 pclink.m_blenderchild = blenderobject;
2237                 pclink.m_gamechildnode = parentinversenode;
2238                 vec_parent_child.push_back(pclink);
2239
2240                 float* fl = (float*) blenderobject->parentinv;
2241                 MT_Transform parinvtrans(fl);
2242                 parentinversenode->SetLocalPosition(parinvtrans.getOrigin());
2243                 // problem here: the parent inverse transform combines scaling and rotation
2244                 // in the basis but the scenegraph needs separate rotation and scaling.
2245                 // This is not important for OpenGL (it uses 4x4 matrix) but it is important
2246                 // for the physic engine that needs a separate scaling
2247                 //parentinversenode->SetLocalOrientation(parinvtrans.getBasis());
2248
2249                 // Extract the rotation and the scaling from the basis
2250                 MT_Matrix3x3 ori(parinvtrans.getBasis());
2251                 MT_Vector3 x(ori.getColumn(0));
2252                 MT_Vector3 y(ori.getColumn(1));
2253                 MT_Vector3 z(ori.getColumn(2));
2254                 MT_Vector3 parscale(x.length(), y.length(), z.length());
2255                 if (!MT_fuzzyZero(parscale[0]))
2256                         x /= parscale[0];
2257                 if (!MT_fuzzyZero(parscale[1]))
2258                         y /= parscale[1];
2259                 if (!MT_fuzzyZero(parscale[2]))
2260                         z /= parscale[2];
2261                 ori.setColumn(0, x);
2262                 ori.setColumn(1, y);
2263                 ori.setColumn(2, z);
2264                 parentinversenode->SetLocalOrientation(ori);
2265                 parentinversenode->SetLocalScale(parscale);
2266
2267                 parentinversenode->AddChild(gameobj->GetSGNode());
2268         }
2269
2270         // needed for python scripting
2271         logicmgr->RegisterGameObjectName(gameobj->GetName(),gameobj);
2272
2273         // needed for group duplication
2274         logicmgr->RegisterGameObj(blenderobject, gameobj);
2275         for (int i = 0; i < gameobj->GetMeshCount(); i++)
2276                 logicmgr->RegisterGameMeshName(gameobj->GetMesh(i)->GetName(), blenderobject);
2277
2278         converter->RegisterGameObject(gameobj, blenderobject);
2279         // this was put in rapidly, needs to be looked at more closely
2280         // only draw/use objects in active 'blender' layers
2281
2282         logicbrick_conversionlist->Add(gameobj->AddRef());
2283
2284         if (converter->addInitFromFrame) {
2285                 posPrev=gameobj->NodeGetWorldPosition();
2286                 angor=gameobj->NodeGetWorldOrientation();
2287         }
2288         if (isInActiveLayer)
2289         {
2290                 objectlist->Add(gameobj->AddRef());
2291                 //tf.Add(gameobj->GetSGNode());
2292
2293                 gameobj->NodeUpdateGS(0);
2294                 gameobj->AddMeshUser();
2295
2296         }
2297         else
2298         {
2299                 //we must store this object otherwise it will be deleted
2300                 //at the end of this function if it is not a root object
2301                 inactivelist->Add(gameobj->AddRef());
2302         }
2303
2304         if (converter->addInitFromFrame) {
2305                 gameobj->NodeSetLocalPosition(posPrev);
2306                 gameobj->NodeSetLocalOrientation(angor);
2307         }
2308 }
2309
2310
2311 // convert blender objects into ketsji gameobjects
2312 void BL_ConvertBlenderObjects(struct Main* maggie,
2313                                                           KX_Scene* kxscene,
2314                                                           KX_KetsjiEngine* ketsjiEngine,
2315                                                           e_PhysicsEngine       physics_engine,
2316                                                           RAS_IRenderTools* rendertools,
2317                                                           RAS_ICanvas* canvas,
2318                                                           KX_BlenderSceneConverter* converter,
2319                                                           bool alwaysUseExpandFraming
2320                                                           )
2321 {
2322
2323 #define BL_CONVERTBLENDEROBJECT_SINGLE                                 \
2324         bl_ConvertBlenderObject_Single(converter,                          \
2325                                        blenderscene, blenderobject,        \
2326                                        inivel, iniang,                     \
2327                                        vec_parent_child,                   \
2328                                        logicbrick_conversionlist,          \
2329                                        objectlist, inactivelist, sumolist, \
2330                                        kxscene, gameobj,                   \
2331                                        logicmgr, timemgr,                  \
2332                                        isInActiveLayer                     \
2333                                        )
2334
2335
2336
2337         Scene *blenderscene = kxscene->GetBlenderScene();
2338         // for SETLOOPER
2339         Scene *sce_iter;
2340         Base *base;
2341
2342         // Get the frame settings of the canvas.
2343         // Get the aspect ratio of the canvas as designed by the user.
2344
2345         RAS_FrameSettings::RAS_FrameType frame_type;
2346         int aspect_width;
2347         int aspect_height;
2348         vector<MT_Vector3> inivel,iniang;
2349         set<Group*> grouplist;  // list of groups to be converted
2350         set<Object*> allblobj;  // all objects converted
2351         set<Object*> groupobj;  // objects from groups (never in active layer)
2352
2353         if (alwaysUseExpandFraming) {
2354                 frame_type = RAS_FrameSettings::e_frame_extend;
2355                 aspect_width = canvas->GetWidth();
2356                 aspect_height = canvas->GetHeight();
2357         } else {
2358                 if (blenderscene->gm.framing.type == SCE_GAMEFRAMING_BARS) {
2359                         frame_type = RAS_FrameSettings::e_frame_bars;
2360                 } else if (blenderscene->gm.framing.type == SCE_GAMEFRAMING_EXTEND) {
2361                         frame_type = RAS_FrameSettings::e_frame_extend;
2362                 } else {
2363                         frame_type = RAS_FrameSettings::e_frame_scale;
2364                 }
2365                 
2366                 aspect_width  = (int)(blenderscene->r.xsch * blenderscene->r.xasp);
2367                 aspect_height = (int)(blenderscene->r.ysch * blenderscene->r.yasp);
2368         }
2369         
2370         RAS_FrameSettings frame_settings(
2371                 frame_type,
2372                 blenderscene->gm.framing.col[0],
2373                 blenderscene->gm.framing.col[1],
2374                 blenderscene->gm.framing.col[2],
2375                 aspect_width,
2376                 aspect_height
2377         );
2378         kxscene->SetFramingType(frame_settings);
2379
2380         kxscene->SetGravity(MT_Vector3(0,0, -blenderscene->gm.gravity));
2381         
2382         /* set activity culling parameters */
2383         kxscene->SetActivityCulling( (blenderscene->gm.mode & WO_ACTIVITY_CULLING) != 0);
2384         kxscene->SetActivityCullingRadius(blenderscene->gm.activityBoxRadius);
2385         kxscene->SetDbvtCulling((blenderscene->gm.mode & WO_DBVT_CULLING) != 0);
2386         
2387         // no occlusion culling by default
2388         kxscene->SetDbvtOcclusionRes(0);
2389
2390         int activeLayerBitInfo = blenderscene->lay;
2391         
2392         // list of all object converted, active and inactive
2393         CListValue*     sumolist = new CListValue();
2394         
2395         vector<parentChildLink> vec_parent_child;
2396         
2397         CListValue* objectlist = kxscene->GetObjectList();
2398         CListValue* inactivelist = kxscene->GetInactiveList();
2399         CListValue* parentlist = kxscene->GetRootParentList();
2400         
2401         SCA_LogicManager* logicmgr = kxscene->GetLogicManager();
2402         SCA_TimeEventManager* timemgr = kxscene->GetTimeEventManager();
2403         
2404         CListValue* logicbrick_conversionlist = new CListValue();
2405         
2406         //SG_TreeFactory tf;
2407         
2408         // Convert actions to actionmap
2409         bAction *curAct;
2410         for (curAct = (bAction*)maggie->action.first; curAct; curAct=(bAction*)curAct->id.next)
2411         {
2412                 logicmgr->RegisterActionName(curAct->id.name + 2, curAct);
2413         }
2414
2415         SetDefaultLightMode(blenderscene);
2416         // Let's support scene set.
2417         // Beware of name conflict in linked data, it will not crash but will create confusion
2418         // in Python scripting and in certain actuators (replace mesh). Linked scene *should* have
2419         // no conflicting name for Object, Object data and Action.
2420         for (SETLOOPER(blenderscene, sce_iter, base))
2421         {
2422                 Object* blenderobject = base->object;
2423                 allblobj.insert(blenderobject);
2424
2425                 KX_GameObject* gameobj = gameobject_from_blenderobject(
2426                                                                                 base->object, 
2427                                                                                 kxscene, 
2428                                                                                 rendertools, 
2429                                                                                 converter);
2430                                                                                 
2431                 bool isInActiveLayer = (blenderobject->lay & activeLayerBitInfo) !=0;
2432                 bool addobj=true;
2433                 
2434                 if (converter->addInitFromFrame)
2435                         if (!isInActiveLayer)
2436                                 addobj=false;
2437
2438                 if (gameobj)
2439                 {
2440                         if (addobj)
2441                         {       /* macro calls object conversion funcs */
2442                                 BL_CONVERTBLENDEROBJECT_SINGLE;
2443
2444                                 if (gameobj->IsDupliGroup()) {
2445                                         grouplist.insert(blenderobject->dup_group);
2446                                 }
2447                         }
2448
2449                         /* Note about memory leak issues:
2450                          * When a CValue derived class is created, m_refcount is initialized to 1
2451                          * so the class must be released after being used to make sure that it won't
2452                          * hang in memory. If the object needs to be stored for a long time,
2453                          * use AddRef() so that this Release() does not free the object.
2454                          * Make sure that for any AddRef() there is a Release()!!!!
2455                          * Do the same for any object derived from CValue, CExpression and NG_NetworkMessage
2456                          */
2457                         gameobj->Release();
2458                 }
2459         }
2460
2461         if (!grouplist.empty())
2462         {
2463                 // now convert the group referenced by dupli group object
2464                 // keep track of all groups already converted
2465                 set<Group*> allgrouplist = grouplist;
2466                 set<Group*> tempglist;
2467                 // recurse
2468                 while (!grouplist.empty())
2469                 {
2470                         set<Group*>::iterator git;
2471                         tempglist.clear();
2472                         tempglist.swap(grouplist);
2473                         for (git=tempglist.begin(); git!=tempglist.end(); git++)
2474                         {
2475                                 Group* group = *git;
2476                                 GroupObject* go;
2477                                 for (go=(GroupObject*)group->gobject.first; go; go=(GroupObject*)go->next)
2478                                 {
2479                                         Object* blenderobject = go->ob;
2480                                         if (converter->FindGameObject(blenderobject) == NULL)
2481                                         {
2482                                                 allblobj.insert(blenderobject);
2483                                                 groupobj.insert(blenderobject);
2484                                                 KX_GameObject* gameobj = gameobject_from_blenderobject(
2485                                                                                                                 blenderobject, 
2486                                                                                                                 kxscene, 
2487                                                                                                                 rendertools, 
2488                                                                                                                 converter);
2489                                                                                 
2490                                                 // this code is copied from above except that
2491                                                 // object from groups are never in active layer
2492                                                 bool isInActiveLayer = false;
2493                                                 bool addobj=true;
2494                                                 
2495                                                 if (converter->addInitFromFrame)
2496                                                         if (!isInActiveLayer)
2497                                                                 addobj=false;
2498
2499                                                 if (gameobj)
2500                                                 {
2501                                                         if (addobj)
2502                                                         {       /* macro calls object conversion funcs */
2503                                                                 BL_CONVERTBLENDEROBJECT_SINGLE;
2504                                                         }
2505
2506                                                         if (gameobj->IsDupliGroup())
2507                                                         {
2508                                                                 if (allgrouplist.insert(blenderobject->dup_group).second)
2509                                                                 {
2510                                                                         grouplist.insert(blenderobject->dup_group);
2511                                                                 }
2512                                                         }
2513
2514
2515                                                         /* see comment above re: mem leaks */
2516                                                         gameobj->Release();
2517                                                 }
2518                                         }
2519                                 }
2520                         }
2521                 }
2522         }
2523
2524         // non-camera objects not supported as camera currently
2525         if (blenderscene->camera && blenderscene->camera->type == OB_CAMERA) {
2526                 KX_Camera *gamecamera= (KX_Camera*) converter->FindGameObject(blenderscene->camera);
2527                 
2528                 if (gamecamera)
2529                         kxscene->SetActiveCamera(gamecamera);
2530         }
2531
2532         //      Set up armatures
2533         set<Object*>::iterator oit;
2534         for (oit=allblobj.begin(); oit!=allblobj.end(); oit++)
2535         {
2536                 Object* blenderobj = *oit;
2537                 if (blenderobj->type==OB_MESH) {
2538                         Mesh *me = (Mesh*)blenderobj->data;
2539         
2540                         if (me->dvert) {
2541                                 BL_DeformableGameObject *obj = (BL_DeformableGameObject*)converter->FindGameObject(blenderobj);
2542
2543                                 if (obj && BL_ModifierDeformer::HasArmatureDeformer(blenderobj) && blenderobj->parent && blenderobj->parent->type==OB_ARMATURE) {
2544                                         KX_GameObject *par = converter->FindGameObject(blenderobj->parent);
2545                                         if (par && obj->GetDeformer())
2546                                                 ((BL_SkinDeformer*)obj->GetDeformer())->SetArmature((BL_ArmatureObject*) par);
2547                                 }
2548                         }
2549                 }
2550         }
2551         
2552         // create hierarchy information
2553         int i;
2554         vector<parentChildLink>::iterator pcit;
2555         
2556         for (pcit = vec_parent_child.begin();!(pcit==vec_parent_child.end());++pcit)
2557         {
2558         
2559                 struct Object* blenderchild = pcit->m_blenderchild;
2560                 struct Object* blenderparent = blenderchild->parent;
2561                 KX_GameObject* parentobj = converter->FindGameObject(blenderparent);
2562                 KX_GameObject* childobj = converter->FindGameObject(blenderchild);
2563
2564                 assert(childobj);
2565
2566                 if (!parentobj || objectlist->SearchValue(childobj) != objectlist->SearchValue(parentobj))
2567                 {
2568                         // special case: the parent and child object are not in the same layer. 
2569                         // This weird situation is used in Apricot for test purposes.
2570                         // Resolve it by not converting the child
2571                         childobj->GetSGNode()->DisconnectFromParent();
2572                         delete pcit->m_gamechildnode;
2573                         // Now destroy the child object but also all its descendent that may already be linked
2574                         // Remove the child reference in the local list!
2575                         // Note: there may be descendents already if the children of the child were processed
2576                         //       by this loop before the child. In that case, we must remove the children also
2577                         CListValue* childrenlist = childobj->GetChildrenRecursive();
2578                         childrenlist->Add(childobj->AddRef());
2579                         for ( i=0;i<childrenlist->GetCount();i++)
2580                         {
2581                                 KX_GameObject* obj = static_cast<KX_GameObject*>(childrenlist->GetValue(i));
2582                                 if (sumolist->RemoveValue(obj))
2583                                         obj->Release();
2584                                 if (logicbrick_conversionlist->RemoveValue(obj))
2585                                         obj->Release();
2586                         }
2587                         childrenlist->Release();
2588                         
2589                         // now destroy recursively
2590                         converter->UnregisterGameObject(childobj); // removing objects during conversion make sure this runs too
2591                         kxscene->RemoveObject(childobj);
2592                         
2593                         continue;
2594                 }
2595
2596                 switch (blenderchild->partype)
2597                 {
2598                         case PARVERT1:
2599                         {
2600                                 // creat a new vertex parent relationship for this node.
2601                                 KX_VertexParentRelation * vertex_parent_relation = KX_VertexParentRelation::New();
2602                                 pcit->m_gamechildnode->SetParentRelation(vertex_parent_relation);
2603                                 break;
2604                         }
2605                         case PARSLOW:
2606                         {
2607                                 // creat a new slow parent relationship for this node.
2608                                 KX_SlowParentRelation * slow_parent_relation = KX_SlowParentRelation::New(blenderchild->sf);
2609                                 pcit->m_gamechildnode->SetParentRelation(slow_parent_relation);
2610                                 break;
2611                         }       
2612                         case PARBONE:
2613                         {
2614                                 // parent this to a bone
2615                                 Bone *parent_bone = get_named_bone( (bArmature *)(blenderchild->parent)->data, blenderchild->parsubstr);
2616
2617                                 if (parent_bone) {
2618                                         KX_BoneParentRelation *bone_parent_relation = KX_BoneParentRelation::New(parent_bone);
2619                                         pcit->m_gamechildnode->SetParentRelation(bone_parent_relation);
2620                                 }
2621                         
2622                                 break;
2623                         }
2624                         case PARSKEL: // skinned - ignore
2625                                 break;
2626                         case PAROBJECT:
2627                         case PARCURVE:
2628                         case PARKEY:
2629                         case PARVERT3:
2630                         default:
2631                                 // unhandled
2632                                 break;
2633                 }
2634         
2635                 parentobj->     GetSGNode()->AddChild(pcit->m_gamechildnode);
2636         }
2637         vec_parent_child.clear();
2638         
2639         // find 'root' parents (object that has not parents in SceneGraph)
2640         for (i=0;i<sumolist->GetCount();++i)
2641         {
2642                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2643                 if (gameobj->GetSGNode()->GetSGParent() == 0)
2644                 {
2645                         parentlist->Add(gameobj->AddRef());
2646                         gameobj->NodeUpdateGS(0);
2647                 }
2648         }
2649
2650         // create graphic controller for culling
2651         if (kxscene->GetDbvtCulling())
2652         {
2653                 bool occlusion = false;
2654                 for (i=0; i<sumolist->GetCount();i++)
2655                 {
2656                         KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2657                         if (gameobj->GetMeshCount() > 0) 
2658                         {
2659                                 MT_Point3 box[2];
2660                                 gameobj->GetSGNode()->BBox().getmm(box, MT_Transform::Identity());
2661                                 // box[0] is the min, box[1] is the max
2662                                 bool isactive = objectlist->SearchValue(gameobj);
2663                                 BL_CreateGraphicObjectNew(gameobj,box[0],box[1],kxscene,isactive,physics_engine);
2664                                 if (gameobj->GetOccluder())
2665                                         occlusion = true;
2666                         }
2667                 }
2668                 if (occlusion)
2669                         kxscene->SetDbvtOcclusionRes(blenderscene->gm.occlusionRes);
2670         }
2671         if (blenderscene->world)
2672                 kxscene->GetPhysicsEnvironment()->setNumTimeSubSteps(blenderscene->gm.physubstep);
2673
2674         // now that the scenegraph is complete, let's instantiate the deformers.
2675         // We need that to create reusable derived mesh and physic shapes
2676         for (i=0;i<sumolist->GetCount();++i)
2677         {
2678                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2679                 if (gameobj->GetDeformer())
2680                         gameobj->GetDeformer()->UpdateBuckets();
2681         }
2682
2683         // Set up armature constraints
2684         for (i=0;i<sumolist->GetCount();++i)
2685         {
2686                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2687                 if (gameobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE)
2688                         ((BL_ArmatureObject*)gameobj)->LoadConstraints(converter);
2689         }
2690
2691         bool processCompoundChildren = false;
2692
2693         // create physics information
2694         for (i=0;i<sumolist->GetCount();i++)
2695         {
2696                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2697                 struct Object* blenderobject = gameobj->GetBlenderObject();
2698                 int nummeshes = gameobj->GetMeshCount();
2699                 RAS_MeshObject* meshobj = 0;
2700                 if (nummeshes > 0)
2701                 {
2702                         meshobj = gameobj->GetMesh(0);
2703                 }
2704                 int layerMask = (groupobj.find(blenderobject