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