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