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