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