BGE: ray casting works on soft body, the hit polygon is also returned. The modificati...
[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_ModifierDeformer.h"
93 #include "BL_ShapeDeformer.h"
94 #include "BL_SkinDeformer.h"
95 #include "BL_MeshDeformer.h"
96 #include "KX_SoftBodyDeformer.h"
97 //#include "BL_ArmatureController.h"
98
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_math.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         int lightlayer = blenderobj ? blenderobj->lay:(1<<20)-1; // all layers if no object.
724
725         if ((meshobj = converter->FindGameMesh(mesh/*, ob->lay*/)) != NULL)
726                 return meshobj;
727         // Get DerivedMesh data
728         DerivedMesh *dm = CDDM_from_mesh(mesh, blenderobj);
729
730         MVert *mvert = dm->getVertArray(dm);
731         int totvert = dm->getNumVerts(dm);
732
733         MFace *mface = dm->getFaceArray(dm);
734         MTFace *tface = static_cast<MTFace*>(dm->getFaceDataArray(dm, CD_MTFACE));
735         MCol *mcol = static_cast<MCol*>(dm->getFaceDataArray(dm, CD_MCOL));
736         float (*tangent)[3] = NULL;
737         int totface = dm->getNumFaces(dm);
738         const char *tfaceName = "";
739
740         if(tface) {
741                 DM_add_tangent_layer(dm);
742                 tangent = (float(*)[3])dm->getFaceDataArray(dm, CD_TANGENT);
743         }
744
745         meshobj = new RAS_MeshObject(mesh);
746
747         // Extract avaiable layers
748         MTF_localLayer *layers =  new MTF_localLayer[MAX_MTFACE];
749         for (int lay=0; lay<MAX_MTFACE; lay++) {
750                 layers[lay].face = 0;
751                 layers[lay].name = "";
752         }
753
754         int validLayers = 0;
755         for (int i=0; i<dm->faceData.totlayer; i++)
756         {
757                 if (dm->faceData.layers[i].type == CD_MTFACE)
758                 {
759                         assert(validLayers <= 8);
760
761                         layers[validLayers].face = (MTFace*)(dm->faceData.layers[i].data);
762                         layers[validLayers].name = dm->faceData.layers[i].name;
763                         if(tface == layers[validLayers].face)
764                                 tfaceName = layers[validLayers].name;
765                         validLayers++;
766                 }
767         }
768
769         meshobj->SetName(mesh->id.name + 2);
770         meshobj->m_sharedvertex_map.resize(totvert);
771         RAS_IPolyMaterial* polymat = NULL;
772         STR_String imastr;
773         // These pointers will hold persistent material structure during the conversion
774         // to avoid countless allocation/deallocation of memory.
775         BL_Material* bl_mat = NULL;
776         KX_BlenderMaterial* kx_blmat = NULL;
777         KX_PolygonMaterial* kx_polymat = NULL;
778
779         for (int f=0;f<totface;f++,mface++)
780         {
781                 Material* ma = 0;
782                 bool collider = true;
783                 MT_Point2 uv0(0.0,0.0),uv1(0.0,0.0),uv2(0.0,0.0),uv3(0.0,0.0);
784                 MT_Point2 uv20(0.0,0.0),uv21(0.0,0.0),uv22(0.0,0.0),uv23(0.0,0.0);
785                 unsigned int rgb0,rgb1,rgb2,rgb3 = 0;
786
787                 MT_Point3 pt0, pt1, pt2, pt3;
788                 MT_Vector3 no0(0,0,0), no1(0,0,0), no2(0,0,0), no3(0,0,0);
789                 MT_Vector4 tan0(0,0,0,0), tan1(0,0,0,0), tan2(0,0,0,0), tan3(0,0,0,0);
790
791                 /* get coordinates, normals and tangents */
792                 pt0.setValue(mvert[mface->v1].co);
793                 pt1.setValue(mvert[mface->v2].co);
794                 pt2.setValue(mvert[mface->v3].co);
795                 if (mface->v4) pt3.setValue(mvert[mface->v4].co);
796
797                 if(mface->flag & ME_SMOOTH) {
798                         float n0[3], n1[3], n2[3], n3[3];
799
800                         normal_short_to_float_v3(n0, mvert[mface->v1].no);
801                         normal_short_to_float_v3(n1, mvert[mface->v2].no);
802                         normal_short_to_float_v3(n2, mvert[mface->v3].no);
803                         no0 = n0;
804                         no1 = n1;
805                         no2 = n2;
806
807                         if(mface->v4) {
808                                 normal_short_to_float_v3(n3, mvert[mface->v4].no);
809                                 no3 = n3;
810                         }
811                 }
812                 else {
813                         float fno[3];
814
815                         if(mface->v4)
816                                 normal_quad_v3( fno,mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co, mvert[mface->v4].co);
817                         else
818                                 normal_tri_v3( fno,mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co);
819
820                         no0 = no1 = no2 = no3 = MT_Vector3(fno);
821                 }
822
823                 if(tangent) {
824                         tan0 = tangent[f*4 + 0];
825                         tan1 = tangent[f*4 + 1];
826                         tan2 = tangent[f*4 + 2];
827
828                         if (mface->v4)
829                                 tan3 = tangent[f*4 + 3];
830                 }
831                 if(blenderobj)
832                         ma = give_current_material(blenderobj, mface->mat_nr+1);
833                 else
834                         ma = mesh->mat ? mesh->mat[mface->mat_nr]:NULL;
835
836                 {
837                         bool visible = true;
838                         bool twoside = false;
839
840                         if(converter->GetMaterials()) {
841                                 /* do Blender Multitexture and Blender GLSL materials */
842                                 unsigned int rgb[4];
843                                 MT_Point2 uv[4];
844
845                                 /* first is the BL_Material */
846                                 if (!bl_mat)
847                                         bl_mat = new BL_Material();
848                                 ConvertMaterial(bl_mat, ma, tface, tfaceName, mface, mcol,
849                                         layers, converter->GetGLSLMaterials());
850
851                                 visible = ((bl_mat->ras_mode & POLY_VIS)!=0);
852                                 collider = ((bl_mat->ras_mode & COLLIDER)!=0);
853                                 twoside = ((bl_mat->mode & TF_TWOSIDE)!=0);
854
855                                 /* vertex colors and uv's were stored in bl_mat temporarily */
856                                 bl_mat->GetConversionRGB(rgb);
857                                 rgb0 = rgb[0]; rgb1 = rgb[1];
858                                 rgb2 = rgb[2]; rgb3 = rgb[3];
859
860                                 bl_mat->GetConversionUV(uv);
861                                 uv0 = uv[0]; uv1 = uv[1];
862                                 uv2 = uv[2]; uv3 = uv[3];
863
864                                 bl_mat->GetConversionUV2(uv);
865                                 uv20 = uv[0]; uv21 = uv[1];
866                                 uv22 = uv[2]; uv23 = uv[3];
867                                 
868                                 /* then the KX_BlenderMaterial */
869                                 if (kx_blmat == NULL)
870                                         kx_blmat = new KX_BlenderMaterial();
871
872                                 kx_blmat->Initialize(scene, bl_mat);
873                                 polymat = static_cast<RAS_IPolyMaterial*>(kx_blmat);
874                         }
875                         else {
876                                 /* do Texture Face materials */
877                                 Image* bima = (tface)? (Image*)tface->tpage: NULL;
878                                 imastr =  (tface)? (bima? (bima)->id.name : "" ) : "";
879                 
880                                 char transp=0;
881                                 short mode=0, tile=0;
882                                 int     tilexrep=4,tileyrep = 4;
883                                 
884                                 if (bima) {
885                                         tilexrep = bima->xrep;
886                                         tileyrep = bima->yrep;
887                                 }
888
889                                 /* get tface properties if available */
890                                 if(tface) {
891                                         /* TF_DYNAMIC means the polygon is a collision face */
892                                         collider = ((tface->mode & TF_DYNAMIC) != 0);
893                                         transp = tface->transp;
894                                         tile = tface->tile;
895                                         mode = tface->mode;
896                                         
897                                         visible = !(tface->mode & TF_INVISIBLE);
898                                         twoside = ((tface->mode & TF_TWOSIDE)!=0);
899                                         
900                                         uv0.setValue(tface->uv[0]);
901                                         uv1.setValue(tface->uv[1]);
902                                         uv2.setValue(tface->uv[2]);
903         
904                                         if (mface->v4)
905                                                 uv3.setValue(tface->uv[3]);
906                                 } 
907                                 else {
908                                         /* no texfaces, set COLLSION true and everything else FALSE */
909                                         mode = default_face_mode;       
910                                         transp = TF_SOLID;
911                                         tile = 0;
912                                 }
913
914                                 /* get vertex colors */
915                                 if (mcol) {
916                                         /* we have vertex colors */
917                                         rgb0 = KX_Mcol2uint_new(mcol[0]);
918                                         rgb1 = KX_Mcol2uint_new(mcol[1]);
919                                         rgb2 = KX_Mcol2uint_new(mcol[2]);
920                                         
921                                         if (mface->v4)
922                                                 rgb3 = KX_Mcol2uint_new(mcol[3]);
923                                 }
924                                 else {
925                                         /* no vertex colors, take from material, otherwise white */
926                                         unsigned int color = 0xFFFFFFFFL;
927
928                                         if (ma)
929                                         {
930                                                 union
931                                                 {
932                                                         unsigned char cp[4];
933                                                         unsigned int integer;
934                                                 } col_converter;
935                                                 
936                                                 col_converter.cp[3] = (unsigned char) (ma->r*255.0);
937                                                 col_converter.cp[2] = (unsigned char) (ma->g*255.0);
938                                                 col_converter.cp[1] = (unsigned char) (ma->b*255.0);
939                                                 col_converter.cp[0] = (unsigned char) (ma->alpha*255.0);
940                                                 
941                                                 color = col_converter.integer;
942                                         }
943
944                                         rgb0 = KX_rgbaint2uint_new(color);
945                                         rgb1 = KX_rgbaint2uint_new(color);
946                                         rgb2 = KX_rgbaint2uint_new(color);      
947                                         
948                                         if (mface->v4)
949                                                 rgb3 = KX_rgbaint2uint_new(color);
950                                 }
951                                 
952                                 // only zsort alpha + add
953                                 bool alpha = (transp == TF_ALPHA || transp == TF_ADD);
954                                 bool zsort = (mode & TF_ALPHASORT)? alpha: 0;
955
956                                 if (kx_polymat == NULL)
957                                         kx_polymat = new KX_PolygonMaterial();
958                                 kx_polymat->Initialize(imastr, ma, (int)mface->mat_nr,
959                                         tile, tilexrep, tileyrep, 
960                                         mode, transp, alpha, zsort, lightlayer, tface, (unsigned int*)mcol);
961                                 polymat = static_cast<RAS_IPolyMaterial*>(kx_polymat);
962         
963                                 if (ma) {
964                                         polymat->m_specular = MT_Vector3(ma->specr, ma->specg, ma->specb)*ma->spec;
965                                         polymat->m_shininess = (float)ma->har/4.0; // 0 < ma->har <= 512
966                                         polymat->m_diffuse = MT_Vector3(ma->r, ma->g, ma->b)*(ma->emit + ma->ref);
967                                 }
968                                 else {
969                                         polymat->m_specular.setValue(0.0f,0.0f,0.0f);
970                                         polymat->m_shininess = 35.0;
971                                 }
972                         }
973
974                         /* mark face as flat, so vertices are split */
975                         bool flat = (mface->flag & ME_SMOOTH) == 0;
976
977                         // see if a bucket was reused or a new one was created
978                         // this way only one KX_BlenderMaterial object has to exist per bucket
979                         bool bucketCreated; 
980                         RAS_MaterialBucket* bucket = scene->FindBucket(polymat, bucketCreated);
981                         if (bucketCreated) {
982                                 // this is needed to free up memory afterwards
983                                 converter->RegisterPolyMaterial(polymat);
984                                 if(converter->GetMaterials()) {
985                                         converter->RegisterBlenderMaterial(bl_mat);
986                                         // the poly material has been stored in the bucket, next time we must create a new one
987                                         bl_mat = NULL;
988                                         kx_blmat = NULL;
989                                 } else {
990                                         // the poly material has been stored in the bucket, next time we must create a new one
991                                         kx_polymat = NULL;
992                                 }
993                         } else {
994                                 // from now on, use the polygon material from the material bucket
995                                 polymat = bucket->GetPolyMaterial();
996                                 // keep the material pointers, they will be reused for next face
997                         }
998                                                  
999                         int nverts = (mface->v4)? 4: 3;
1000                         RAS_Polygon *poly = meshobj->AddPolygon(bucket, nverts);
1001
1002                         poly->SetVisible(visible);
1003                         poly->SetCollider(collider);
1004                         poly->SetTwoside(twoside);
1005                         //poly->SetEdgeCode(mface->edcode);
1006
1007                         meshobj->AddVertex(poly,0,pt0,uv0,uv20,tan0,rgb0,no0,flat,mface->v1);
1008                         meshobj->AddVertex(poly,1,pt1,uv1,uv21,tan1,rgb1,no1,flat,mface->v2);
1009                         meshobj->AddVertex(poly,2,pt2,uv2,uv22,tan2,rgb2,no2,flat,mface->v3);
1010
1011                         if (nverts==4)
1012                                 meshobj->AddVertex(poly,3,pt3,uv3,uv23,tan3,rgb3,no3,flat,mface->v4);
1013                 }
1014
1015                 if (tface) 
1016                         tface++;
1017                 if (mcol)
1018                         mcol+=4;
1019
1020                 for (int lay=0; lay<MAX_MTFACE; lay++)
1021                 {
1022                         MTF_localLayer &layer = layers[lay];
1023                         if (layer.face == 0) break;
1024
1025                         layer.face++;
1026                 }
1027         }
1028         // keep meshobj->m_sharedvertex_map for reinstance phys mesh.
1029         // 2.49a and before it did: meshobj->m_sharedvertex_map.clear();
1030         // but this didnt save much ram. - Campbell
1031         meshobj->EndConversion();
1032
1033         // pre calculate texture generation
1034         for(list<RAS_MeshMaterial>::iterator mit = meshobj->GetFirstMaterial();
1035                 mit != meshobj->GetLastMaterial(); ++ mit) {
1036                 mit->m_bucket->GetPolyMaterial()->OnConstruction(lightlayer);
1037         }
1038
1039         if (layers)
1040                 delete []layers;
1041         
1042         dm->release(dm);
1043         // cleanup material
1044         if (bl_mat)
1045                 delete bl_mat;
1046         if (kx_blmat)
1047                 delete kx_blmat;
1048         if (kx_polymat)
1049                 delete kx_polymat;
1050         converter->RegisterGameMesh(meshobj, mesh);
1051         return meshobj;
1052 }
1053
1054         
1055         
1056 static PHY_MaterialProps *CreateMaterialFromBlenderObject(struct Object* blenderobject)
1057 {
1058         PHY_MaterialProps *materialProps = new PHY_MaterialProps;
1059         
1060         MT_assert(materialProps && "Create physics material properties failed");
1061                 
1062         Material* blendermat = give_current_material(blenderobject, 0);
1063                 
1064         if (blendermat)
1065         {
1066                 MT_assert(0.0f <= blendermat->reflect && blendermat->reflect <= 1.0f);
1067         
1068                 materialProps->m_restitution = blendermat->reflect;
1069                 materialProps->m_friction = blendermat->friction;
1070                 materialProps->m_fh_spring = blendermat->fh;
1071                 materialProps->m_fh_damping = blendermat->xyfrict;
1072                 materialProps->m_fh_distance = blendermat->fhdist;
1073                 materialProps->m_fh_normal = (blendermat->dynamode & MA_FH_NOR) != 0;
1074         }
1075         else {
1076                 //give some defaults
1077                 materialProps->m_restitution = 0.f;
1078                 materialProps->m_friction = 0.5;
1079                 materialProps->m_fh_spring = 0.f;
1080                 materialProps->m_fh_damping = 0.f;
1081                 materialProps->m_fh_distance = 0.f;
1082                 materialProps->m_fh_normal = false;
1083
1084         }
1085         
1086         return materialProps;
1087 }
1088
1089 static PHY_ShapeProps *CreateShapePropsFromBlenderObject(struct Object* blenderobject)
1090 {
1091         PHY_ShapeProps *shapeProps = new PHY_ShapeProps;
1092         
1093         MT_assert(shapeProps);
1094                 
1095         shapeProps->m_mass = blenderobject->mass;
1096         
1097 //  This needs to be fixed in blender. For now, we use:
1098         
1099 // in Blender, inertia stands for the size value which is equivalent to
1100 // the sphere radius
1101         shapeProps->m_inertia = blenderobject->formfactor;
1102         
1103         MT_assert(0.0f <= blenderobject->damping && blenderobject->damping <= 1.0f);
1104         MT_assert(0.0f <= blenderobject->rdamping && blenderobject->rdamping <= 1.0f);
1105         
1106         shapeProps->m_lin_drag = 1.0 - blenderobject->damping;
1107         shapeProps->m_ang_drag = 1.0 - blenderobject->rdamping;
1108         
1109         shapeProps->m_friction_scaling[0] = blenderobject->anisotropicFriction[0]; 
1110         shapeProps->m_friction_scaling[1] = blenderobject->anisotropicFriction[1];
1111         shapeProps->m_friction_scaling[2] = blenderobject->anisotropicFriction[2];
1112         shapeProps->m_do_anisotropic = ((blenderobject->gameflag & OB_ANISOTROPIC_FRICTION) != 0);
1113         
1114         shapeProps->m_do_fh     = (blenderobject->gameflag & OB_DO_FH) != 0; 
1115         shapeProps->m_do_rot_fh = (blenderobject->gameflag & OB_ROT_FH) != 0;
1116         
1117 //      velocity clamping XXX
1118         shapeProps->m_clamp_vel_min = blenderobject->min_vel;
1119         shapeProps->m_clamp_vel_max = blenderobject->max_vel;
1120         
1121         return shapeProps;
1122 }
1123
1124         
1125         
1126         
1127                 
1128 //////////////////////////////////////////////////////////
1129         
1130
1131
1132 static float my_boundbox_mesh(Mesh *me, float *loc, float *size)
1133 {
1134         MVert *mvert;
1135         BoundBox *bb;
1136         MT_Point3 min, max;
1137         float mloc[3], msize[3];
1138         float radius=0.0f, vert_radius, *co;
1139         int a;
1140         
1141         if(me->bb==0) me->bb= (struct BoundBox *)MEM_callocN(sizeof(BoundBox), "boundbox");
1142         bb= me->bb;
1143         
1144         INIT_MINMAX(min, max);
1145
1146         if (!loc) loc= mloc;
1147         if (!size) size= msize;
1148         
1149         mvert= me->mvert;
1150         for(a=0; a<me->totvert; a++, mvert++) {
1151                 co= mvert->co;
1152                 
1153                 /* bounds */
1154                 DO_MINMAX(co, min, max);
1155                 
1156                 /* radius */
1157                 vert_radius= co[0]*co[0] + co[1]*co[1] + co[2]*co[2];
1158                 if (vert_radius > radius)
1159                         radius= vert_radius;
1160         }
1161                 
1162         if(me->totvert) {
1163                 loc[0]= (min[0]+max[0])/2.0;
1164                 loc[1]= (min[1]+max[1])/2.0;
1165                 loc[2]= (min[2]+max[2])/2.0;
1166                 
1167                 size[0]= (max[0]-min[0])/2.0;
1168                 size[1]= (max[1]-min[1])/2.0;
1169                 size[2]= (max[2]-min[2])/2.0;
1170         }
1171         else {
1172                 loc[0]= loc[1]= loc[2]= 0.0;
1173                 size[0]= size[1]= size[2]= 0.0;
1174         }
1175                 
1176         bb->vec[0][0]=bb->vec[1][0]=bb->vec[2][0]=bb->vec[3][0]= loc[0]-size[0];
1177         bb->vec[4][0]=bb->vec[5][0]=bb->vec[6][0]=bb->vec[7][0]= loc[0]+size[0];
1178                 
1179         bb->vec[0][1]=bb->vec[1][1]=bb->vec[4][1]=bb->vec[5][1]= loc[1]-size[1];
1180         bb->vec[2][1]=bb->vec[3][1]=bb->vec[6][1]=bb->vec[7][1]= loc[1]+size[1];
1181
1182         bb->vec[0][2]=bb->vec[3][2]=bb->vec[4][2]=bb->vec[7][2]= loc[2]-size[2];
1183         bb->vec[1][2]=bb->vec[2][2]=bb->vec[5][2]=bb->vec[6][2]= loc[2]+size[2];
1184
1185         return sqrt(radius);
1186 }
1187                 
1188
1189
1190
1191 static void my_tex_space_mesh(Mesh *me)
1192                 {
1193         KeyBlock *kb;
1194         float *fp, loc[3], size[3], min[3], max[3];
1195         int a;
1196
1197         my_boundbox_mesh(me, loc, size);
1198         
1199         if(me->texflag & AUTOSPACE) {
1200                 if(me->key) {
1201                         kb= me->key->refkey;
1202                         if (kb) {
1203         
1204                                 INIT_MINMAX(min, max);
1205                 
1206                                 fp= (float *)kb->data;
1207                                 for(a=0; a<kb->totelem; a++, fp+=3) {   
1208                                         DO_MINMAX(fp, min, max);
1209                                 }
1210                                 if(kb->totelem) {
1211                                         loc[0]= (min[0]+max[0])/2.0; loc[1]= (min[1]+max[1])/2.0; loc[2]= (min[2]+max[2])/2.0;
1212                                         size[0]= (max[0]-min[0])/2.0; size[1]= (max[1]-min[1])/2.0; size[2]= (max[2]-min[2])/2.0;
1213         } 
1214         else {
1215                                         loc[0]= loc[1]= loc[2]= 0.0;
1216                                         size[0]= size[1]= size[2]= 0.0;
1217                                 }
1218                                 
1219                         }
1220                                 }
1221         
1222                 VECCOPY(me->loc, loc);
1223                 VECCOPY(me->size, size);
1224                 me->rot[0]= me->rot[1]= me->rot[2]= 0.0;
1225         
1226                 if(me->size[0]==0.0) me->size[0]= 1.0;
1227                 else if(me->size[0]>0.0 && me->size[0]<0.00001) me->size[0]= 0.00001;
1228                 else if(me->size[0]<0.0 && me->size[0]> -0.00001) me->size[0]= -0.00001;
1229         
1230                 if(me->size[1]==0.0) me->size[1]= 1.0;
1231                 else if(me->size[1]>0.0 && me->size[1]<0.00001) me->size[1]= 0.00001;
1232                 else if(me->size[1]<0.0 && me->size[1]> -0.00001) me->size[1]= -0.00001;
1233                                                 
1234                 if(me->size[2]==0.0) me->size[2]= 1.0;
1235                 else if(me->size[2]>0.0 && me->size[2]<0.00001) me->size[2]= 0.00001;
1236                 else if(me->size[2]<0.0 && me->size[2]> -0.00001) me->size[2]= -0.00001;
1237         }
1238         
1239 }
1240
1241 static void my_get_local_bounds(Object *ob, DerivedMesh *dm, float *center, float *size)
1242 {
1243         BoundBox *bb= NULL;
1244         /* uses boundbox, function used by Ketsji */
1245         switch (ob->type)
1246         {
1247                 case OB_MESH:
1248                         if (dm)
1249                         {
1250                                 float min_r[3], max_r[3];
1251                                 INIT_MINMAX(min_r, max_r);
1252                                 dm->getMinMax(dm, min_r, max_r);
1253                                 size[0]= 0.5*fabs(max_r[0] - min_r[0]);
1254                                 size[1]= 0.5*fabs(max_r[1] - min_r[1]);
1255                                 size[2]= 0.5*fabs(max_r[2] - min_r[2]);
1256                                         
1257                                 center[0]= 0.5*(max_r[0] + min_r[0]);
1258                                 center[1]= 0.5*(max_r[1] + min_r[1]);
1259                                 center[2]= 0.5*(max_r[2] + min_r[2]);
1260                                 return;
1261                         } else
1262                         {
1263                                 bb= ( (Mesh *)ob->data )->bb;
1264                                 if(bb==0) 
1265                                 {
1266                                         my_tex_space_mesh((struct Mesh *)ob->data);
1267                                         bb= ( (Mesh *)ob->data )->bb;
1268                                 }
1269                         }
1270                         break;
1271                 case OB_CURVE:
1272                 case OB_SURF:
1273                 case OB_FONT:
1274                         center[0]= center[1]= center[2]= 0.0;
1275                         size[0]  = size[1]=size[2]=0.0;
1276                         break;
1277                 case OB_MBALL:
1278                         bb= ob->bb;
1279                         break;
1280         }
1281         
1282         if(bb==NULL) 
1283         {
1284                 center[0]= center[1]= center[2]= 0.0;
1285                 size[0] = size[1]=size[2]=1.0;
1286         }
1287         else 
1288         {
1289                 size[0]= 0.5*fabs(bb->vec[0][0] - bb->vec[4][0]);
1290                 size[1]= 0.5*fabs(bb->vec[0][1] - bb->vec[2][1]);
1291                 size[2]= 0.5*fabs(bb->vec[0][2] - bb->vec[1][2]);
1292                                         
1293                 center[0]= 0.5*(bb->vec[0][0] + bb->vec[4][0]);
1294                 center[1]= 0.5*(bb->vec[0][1] + bb->vec[2][1]);
1295                 center[2]= 0.5*(bb->vec[0][2] + bb->vec[1][2]);
1296         }
1297 }
1298         
1299
1300
1301
1302 //////////////////////////////////////////////////////
1303
1304
1305 void BL_CreateGraphicObjectNew(KX_GameObject* gameobj,
1306                                                            const MT_Point3& localAabbMin,
1307                                                            const MT_Point3& localAabbMax,
1308                                                            KX_Scene* kxscene,
1309                                                            bool isActive,
1310                                                            e_PhysicsEngine physics_engine)
1311 {
1312         if (gameobj->GetMeshCount() > 0) 
1313         {
1314                 switch (physics_engine)
1315                 {
1316 #ifdef USE_BULLET
1317                 case UseBullet:
1318                         {
1319                                 CcdPhysicsEnvironment* env = (CcdPhysicsEnvironment*)kxscene->GetPhysicsEnvironment();
1320                                 assert(env);
1321                                 PHY_IMotionState* motionstate = new KX_MotionState(gameobj->GetSGNode());
1322                                 CcdGraphicController* ctrl = new CcdGraphicController(env, motionstate);
1323                                 gameobj->SetGraphicController(ctrl);
1324                                 ctrl->setNewClientInfo(gameobj->getClientInfo());
1325                                 ctrl->setLocalAabb(localAabbMin, localAabbMax);
1326                                 if (isActive) {
1327                                         // add first, this will create the proxy handle, only if the object is visible
1328                                         if (gameobj->GetVisible())
1329                                                 env->addCcdGraphicController(ctrl);
1330                                         // update the mesh if there is a deformer, this will also update the bounding box for modifiers
1331                                         RAS_Deformer* deformer = gameobj->GetDeformer();
1332                                         if (deformer)
1333                                                 deformer->UpdateBuckets();
1334                                 }
1335                         }
1336                         break;
1337 #endif
1338                 default:
1339                         break;
1340                 }
1341         }
1342 }
1343
1344 void BL_CreatePhysicsObjectNew(KX_GameObject* gameobj,
1345                                                  struct Object* blenderobject,
1346                                                  RAS_MeshObject* meshobj,
1347                                                  KX_Scene* kxscene,
1348                                                  int activeLayerBitInfo,
1349                                                  e_PhysicsEngine        physics_engine,
1350                                                  KX_BlenderSceneConverter *converter,
1351                                                  bool processCompoundChildren
1352                                                  )
1353                                         
1354 {
1355         //SYS_SystemHandle syshandle = SYS_GetSystem(); /*unused*/
1356         //int userigidbody = SYS_GetCommandLineInt(syshandle,"norigidbody",0);
1357         //bool bRigidBody = (userigidbody == 0);
1358
1359         // object has physics representation?
1360         if (!(blenderobject->gameflag & OB_COLLISION))
1361                 return;
1362
1363         // get Root Parent of blenderobject
1364         struct Object* parent= blenderobject->parent;
1365         while(parent && parent->parent) {
1366                 parent= parent->parent;
1367         }
1368
1369         bool isCompoundChild = false;
1370         bool hasCompoundChildren = !parent && (blenderobject->gameflag & OB_CHILD);
1371
1372         /* When the parent is not OB_DYNAMIC and has no OB_COLLISION then it gets no bullet controller
1373          * and cant be apart of the parents compound shape */
1374         if (parent && (parent->gameflag & (OB_DYNAMIC | OB_COLLISION))) {
1375                 
1376                 if ((parent->gameflag & OB_CHILD) != 0 && (blenderobject->gameflag & OB_CHILD))
1377                 {
1378                         isCompoundChild = true;
1379                 } 
1380         }
1381         if (processCompoundChildren != isCompoundChild)
1382                 return;
1383
1384
1385         PHY_ShapeProps* shapeprops =
1386                         CreateShapePropsFromBlenderObject(blenderobject);
1387
1388         
1389         PHY_MaterialProps* smmaterial = 
1390                 CreateMaterialFromBlenderObject(blenderobject);
1391                                         
1392         KX_ObjectProperties objprop;
1393         objprop.m_lockXaxis = (blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_X_AXIS) !=0;
1394         objprop.m_lockYaxis = (blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_Y_AXIS) !=0;
1395         objprop.m_lockZaxis = (blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_Z_AXIS) !=0;
1396         objprop.m_lockXRotaxis = (blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_X_ROT_AXIS) !=0;
1397         objprop.m_lockYRotaxis = (blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_Y_ROT_AXIS) !=0;
1398         objprop.m_lockZRotaxis = (blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_Z_ROT_AXIS) !=0;
1399
1400         objprop.m_isCompoundChild = isCompoundChild;
1401         objprop.m_hasCompoundChildren = hasCompoundChildren;
1402         objprop.m_margin = blenderobject->margin;
1403         
1404         // ACTOR is now a separate feature
1405         objprop.m_isactor = (blenderobject->gameflag & OB_ACTOR)!=0;
1406         objprop.m_dyna = (blenderobject->gameflag & OB_DYNAMIC) != 0;
1407         objprop.m_softbody = (blenderobject->gameflag & OB_SOFT_BODY) != 0;
1408         objprop.m_angular_rigidbody = (blenderobject->gameflag & OB_RIGID_BODY) != 0;
1409         
1410         ///contact processing threshold is only for rigid bodies and static geometry, not 'dynamic'
1411         if (objprop.m_angular_rigidbody || !objprop.m_dyna )
1412         {
1413                 objprop.m_contactProcessingThreshold = blenderobject->m_contactProcessingThreshold;
1414         } else
1415         {
1416                 objprop.m_contactProcessingThreshold = 0.f;
1417         }
1418
1419         objprop.m_sensor = (blenderobject->gameflag & OB_SENSOR) != 0;
1420         
1421         if (objprop.m_softbody)
1422         {
1423                 ///for game soft bodies
1424                 if (blenderobject->bsoft)
1425                 {
1426                         objprop.m_gamesoftFlag = blenderobject->bsoft->flag;
1427                                         ///////////////////
1428                         objprop.m_soft_linStiff = blenderobject->bsoft->linStiff;
1429                         objprop.m_soft_angStiff = blenderobject->bsoft->angStiff;               /* angular stiffness 0..1 */
1430                         objprop.m_soft_volume= blenderobject->bsoft->volume;                    /* volume preservation 0..1 */
1431
1432                         objprop.m_soft_viterations= blenderobject->bsoft->viterations;          /* Velocities solver iterations */
1433                         objprop.m_soft_piterations= blenderobject->bsoft->piterations;          /* Positions solver iterations */
1434                         objprop.m_soft_diterations= blenderobject->bsoft->diterations;          /* Drift solver iterations */
1435                         objprop.m_soft_citerations= blenderobject->bsoft->citerations;          /* Cluster solver iterations */
1436
1437                         objprop.m_soft_kSRHR_CL= blenderobject->bsoft->kSRHR_CL;                /* Soft vs rigid hardness [0,1] (cluster only) */
1438                         objprop.m_soft_kSKHR_CL= blenderobject->bsoft->kSKHR_CL;                /* Soft vs kinetic hardness [0,1] (cluster only) */
1439                         objprop.m_soft_kSSHR_CL= blenderobject->bsoft->kSSHR_CL;                /* Soft vs soft hardness [0,1] (cluster only) */
1440                         objprop.m_soft_kSR_SPLT_CL= blenderobject->bsoft->kSR_SPLT_CL;  /* Soft vs rigid impulse split [0,1] (cluster only) */
1441
1442                         objprop.m_soft_kSK_SPLT_CL= blenderobject->bsoft->kSK_SPLT_CL;  /* Soft vs rigid impulse split [0,1] (cluster only) */
1443                         objprop.m_soft_kSS_SPLT_CL= blenderobject->bsoft->kSS_SPLT_CL;  /* Soft vs rigid impulse split [0,1] (cluster only) */
1444                         objprop.m_soft_kVCF= blenderobject->bsoft->kVCF;                        /* Velocities correction factor (Baumgarte) */
1445                         objprop.m_soft_kDP= blenderobject->bsoft->kDP;                  /* Damping coefficient [0,1] */
1446
1447                         objprop.m_soft_kDG= blenderobject->bsoft->kDG;                  /* Drag coefficient [0,+inf] */
1448                         objprop.m_soft_kLF= blenderobject->bsoft->kLF;                  /* Lift coefficient [0,+inf] */
1449                         objprop.m_soft_kPR= blenderobject->bsoft->kPR;                  /* Pressure coefficient [-inf,+inf] */
1450                         objprop.m_soft_kVC= blenderobject->bsoft->kVC;                  /* Volume conversation coefficient [0,+inf] */
1451
1452                         objprop.m_soft_kDF= blenderobject->bsoft->kDF;                  /* Dynamic friction coefficient [0,1] */
1453                         objprop.m_soft_kMT= blenderobject->bsoft->kMT;                  /* Pose matching coefficient [0,1] */
1454                         objprop.m_soft_kCHR= blenderobject->bsoft->kCHR;                        /* Rigid contacts hardness [0,1] */
1455                         objprop.m_soft_kKHR= blenderobject->bsoft->kKHR;                        /* Kinetic contacts hardness [0,1] */
1456
1457                         objprop.m_soft_kSHR= blenderobject->bsoft->kSHR;                        /* Soft contacts hardness [0,1] */
1458                         objprop.m_soft_kAHR= blenderobject->bsoft->kAHR;                        /* Anchors hardness [0,1] */
1459                         objprop.m_soft_collisionflags= blenderobject->bsoft->collisionflags;    /* Vertex/Face or Signed Distance Field(SDF) or Clusters, Soft versus Soft or Rigid */
1460                         objprop.m_soft_numclusteriterations= blenderobject->bsoft->numclusteriterations;        /* number of iterations to refine collision clusters*/
1461                         //objprop.m_soft_welding = blenderobject->bsoft->welding;               /* welding */
1462                         /* disable welding: it doesn't bring any additional stability and it breaks the relation between soft body collision shape and graphic mesh */
1463                         objprop.m_soft_welding = 0.f;           
1464                         objprop.m_margin = blenderobject->bsoft->margin;
1465                         objprop.m_contactProcessingThreshold = 0.f;
1466                 } else
1467                 {
1468                         objprop.m_gamesoftFlag = OB_BSB_BENDING_CONSTRAINTS | OB_BSB_SHAPE_MATCHING | OB_BSB_AERO_VPOINT;
1469                         
1470                         objprop.m_soft_linStiff = 0.5;;
1471                         objprop.m_soft_angStiff = 1.f;          /* angular stiffness 0..1 */
1472                         objprop.m_soft_volume= 1.f;                     /* volume preservation 0..1 */
1473
1474
1475                         objprop.m_soft_viterations= 0;
1476                         objprop.m_soft_piterations= 1;
1477                         objprop.m_soft_diterations= 0;
1478                         objprop.m_soft_citerations= 4;
1479
1480                         objprop.m_soft_kSRHR_CL= 0.1f;
1481                         objprop.m_soft_kSKHR_CL= 1.f;
1482                         objprop.m_soft_kSSHR_CL= 0.5;
1483                         objprop.m_soft_kSR_SPLT_CL= 0.5f;
1484
1485                         objprop.m_soft_kSK_SPLT_CL= 0.5f;
1486                         objprop.m_soft_kSS_SPLT_CL= 0.5f;
1487                         objprop.m_soft_kVCF=  1;
1488                         objprop.m_soft_kDP= 0;
1489
1490                         objprop.m_soft_kDG= 0;
1491                         objprop.m_soft_kLF= 0;
1492                         objprop.m_soft_kPR= 0;
1493                         objprop.m_soft_kVC= 0;
1494
1495                         objprop.m_soft_kDF= 0.2f;
1496                         objprop.m_soft_kMT= 0.05f;
1497                         objprop.m_soft_kCHR= 1.0f;
1498                         objprop.m_soft_kKHR= 0.1f;
1499
1500                         objprop.m_soft_kSHR= 1.f;
1501                         objprop.m_soft_kAHR= 0.7f;
1502                         objprop.m_soft_collisionflags= OB_BSB_COL_SDF_RS + OB_BSB_COL_VF_SS;
1503                         objprop.m_soft_numclusteriterations= 16;
1504                         objprop.m_soft_welding = 0.f;
1505                         objprop.m_margin = 0.f;
1506                         objprop.m_contactProcessingThreshold = 0.f;
1507                 }
1508         }
1509
1510         objprop.m_ghost = (blenderobject->gameflag & OB_GHOST) != 0;
1511         objprop.m_disableSleeping = (blenderobject->gameflag & OB_COLLISION_RESPONSE) != 0;//abuse the OB_COLLISION_RESPONSE flag
1512         //mmm, for now, taks this for the size of the dynamicobject
1513         // Blender uses inertia for radius of dynamic object
1514         objprop.m_radius = blenderobject->inertia;
1515         objprop.m_in_active_layer = (blenderobject->lay & activeLayerBitInfo) != 0;
1516         objprop.m_dynamic_parent=NULL;
1517         objprop.m_isdeformable = ((blenderobject->gameflag2 & 2)) != 0;
1518         objprop.m_boundclass = objprop.m_dyna?KX_BOUNDSPHERE:KX_BOUNDMESH;
1519         
1520         if ((blenderobject->gameflag & OB_SOFT_BODY) && !(blenderobject->gameflag & OB_BOUNDS))
1521         {
1522                 objprop.m_boundclass = KX_BOUNDMESH;
1523         }
1524
1525         KX_BoxBounds bb;
1526         DerivedMesh* dm = NULL;
1527         if (gameobj->GetDeformer())
1528                 dm = gameobj->GetDeformer()->GetFinalMesh();
1529         my_get_local_bounds(blenderobject,dm,objprop.m_boundobject.box.m_center,bb.m_extends);
1530         if (blenderobject->gameflag & OB_BOUNDS)
1531         {
1532                 switch (blenderobject->boundtype)
1533                 {
1534                         case OB_BOUND_BOX:
1535                                 objprop.m_boundclass = KX_BOUNDBOX;
1536                                 //mmm, has to be divided by 2 to be proper extends
1537                                 objprop.m_boundobject.box.m_extends[0]=2.f*bb.m_extends[0];
1538                                 objprop.m_boundobject.box.m_extends[1]=2.f*bb.m_extends[1];
1539                                 objprop.m_boundobject.box.m_extends[2]=2.f*bb.m_extends[2];
1540                                 break;
1541                         case OB_BOUND_POLYT:
1542                                 if (blenderobject->type == OB_MESH)
1543                                 {
1544                                         objprop.m_boundclass = KX_BOUNDPOLYTOPE;
1545                                         break;
1546                                 }
1547                                 // Object is not a mesh... fall through OB_BOUND_POLYH to 
1548                                 // OB_BOUND_SPHERE
1549                         case OB_BOUND_POLYH:
1550                                 if (blenderobject->type == OB_MESH)
1551                                 {
1552                                         objprop.m_boundclass = KX_BOUNDMESH;
1553                                         break;
1554                                 }
1555                                 // Object is not a mesh... can't use polyheder. 
1556                                 // Fall through and become a sphere.
1557                         case OB_BOUND_SPHERE:
1558                         {
1559                                 objprop.m_boundclass = KX_BOUNDSPHERE;
1560                                 objprop.m_boundobject.c.m_radius = MT_max(bb.m_extends[0], MT_max(bb.m_extends[1], bb.m_extends[2]));
1561                                 break;
1562                         }
1563                         case OB_BOUND_CYLINDER:
1564                         {
1565                                 objprop.m_boundclass = KX_BOUNDCYLINDER;
1566                                 objprop.m_boundobject.c.m_radius = MT_max(bb.m_extends[0], bb.m_extends[1]);
1567                                 objprop.m_boundobject.c.m_height = 2.f*bb.m_extends[2];
1568                                 break;
1569                         }
1570                         case OB_BOUND_CONE:
1571                         {
1572                                 objprop.m_boundclass = KX_BOUNDCONE;
1573                                 objprop.m_boundobject.c.m_radius = MT_max(bb.m_extends[0], bb.m_extends[1]);
1574                                 objprop.m_boundobject.c.m_height = 2.f*bb.m_extends[2];
1575                                 break;
1576                         }
1577                 }
1578         }
1579
1580         
1581         if (parent/* && (parent->gameflag & OB_DYNAMIC)*/) {
1582                 // parented object cannot be dynamic
1583                 KX_GameObject *parentgameobject = converter->FindGameObject(parent);
1584                 objprop.m_dynamic_parent = parentgameobject;
1585                 //cannot be dynamic:
1586                 objprop.m_dyna = false;
1587                 objprop.m_softbody = false;
1588                 shapeprops->m_mass = 0.f;
1589         }
1590
1591         
1592         objprop.m_concave = (blenderobject->boundtype & 4) != 0;
1593         
1594         switch (physics_engine)
1595         {
1596 #ifdef USE_BULLET
1597                 case UseBullet:
1598                         KX_ConvertBulletObject(gameobj, meshobj, dm, kxscene, shapeprops, smmaterial, &objprop);
1599                         break;
1600
1601 #endif
1602                 case UseDynamo:
1603                         //KX_ConvertDynamoObject(gameobj,meshobj,kxscene,shapeprops,    smmaterial,     &objprop);
1604                         break;
1605                         
1606                 case UseNone:
1607                 default:
1608                         break;
1609         }
1610         delete shapeprops;
1611         delete smmaterial;
1612 }
1613
1614
1615
1616
1617
1618 static KX_LightObject *gamelight_from_blamp(Object *ob, Lamp *la, unsigned int layerflag, KX_Scene *kxscene, RAS_IRenderTools *rendertools, KX_BlenderSceneConverter *converter) {
1619         RAS_LightObject lightobj;
1620         KX_LightObject *gamelight;
1621         
1622         lightobj.m_att1 = la->att1;
1623         lightobj.m_att2 = (la->mode & LA_QUAD)?la->att2:0.0;
1624         lightobj.m_red = la->r;
1625         lightobj.m_green = la->g;
1626         lightobj.m_blue = la->b;
1627         lightobj.m_distance = la->dist;
1628         lightobj.m_energy = la->energy;
1629         lightobj.m_layer = layerflag;
1630         lightobj.m_spotblend = la->spotblend;
1631         lightobj.m_spotsize = la->spotsize;
1632         
1633         lightobj.m_nodiffuse = (la->mode & LA_NO_DIFF) != 0;
1634         lightobj.m_nospecular = (la->mode & LA_NO_SPEC) != 0;
1635         
1636         if (la->mode & LA_NEG)
1637         {
1638                 lightobj.m_red = -lightobj.m_red;
1639                 lightobj.m_green = -lightobj.m_green;
1640                 lightobj.m_blue = -lightobj.m_blue;
1641         }
1642                 
1643         if (la->type==LA_SUN) {
1644                 lightobj.m_type = RAS_LightObject::LIGHT_SUN;
1645         } else if (la->type==LA_SPOT) {
1646                 lightobj.m_type = RAS_LightObject::LIGHT_SPOT;
1647         } else {
1648                 lightobj.m_type = RAS_LightObject::LIGHT_NORMAL;
1649         }
1650
1651         gamelight = new KX_LightObject(kxscene, KX_Scene::m_callbacks, rendertools,
1652                 lightobj, converter->GetGLSLMaterials());
1653
1654         BL_ConvertLampIpos(la, gamelight, converter);
1655         
1656         return gamelight;
1657 }
1658
1659 static KX_Camera *gamecamera_from_bcamera(Object *ob, KX_Scene *kxscene, KX_BlenderSceneConverter *converter) {
1660         Camera* ca = static_cast<Camera*>(ob->data);
1661         RAS_CameraData camdata(ca->lens, ca->ortho_scale, ca->clipsta, ca->clipend, ca->type == CAM_PERSP, dof_camera(ob));
1662         KX_Camera *gamecamera;
1663         
1664         gamecamera= new KX_Camera(kxscene, KX_Scene::m_callbacks, camdata);
1665         gamecamera->SetName(ca->id.name + 2);
1666         
1667         BL_ConvertCameraIpos(ca, gamecamera, converter);
1668         
1669         return gamecamera;
1670 }
1671
1672 static KX_GameObject *gameobject_from_blenderobject(
1673                                                                 Object *ob, 
1674                                                                 KX_Scene *kxscene, 
1675                                                                 RAS_IRenderTools *rendertools, 
1676                                                                 KX_BlenderSceneConverter *converter) 
1677 {
1678         KX_GameObject *gameobj = NULL;
1679         
1680         switch(ob->type)
1681         {
1682         case OB_LAMP:
1683         {
1684                 KX_LightObject* gamelight= gamelight_from_blamp(ob, static_cast<Lamp*>(ob->data), ob->lay, kxscene, rendertools, converter);
1685                 gameobj = gamelight;
1686                 
1687                 gamelight->AddRef();
1688                 kxscene->GetLightList()->Add(gamelight);
1689
1690                 break;
1691         }
1692         
1693         case OB_CAMERA:
1694         {
1695                 KX_Camera* gamecamera = gamecamera_from_bcamera(ob, kxscene, converter);
1696                 gameobj = gamecamera;
1697                 
1698                 //don't add a reference: the camera list in kxscene->m_cameras is not released at the end
1699                 //gamecamera->AddRef();
1700                 kxscene->AddCamera(gamecamera);
1701                 
1702                 break;
1703         }
1704         
1705         case OB_MESH:
1706         {
1707                 Mesh* mesh = static_cast<Mesh*>(ob->data);
1708                 float center[3], extents[3];
1709                 float radius = my_boundbox_mesh((Mesh*) ob->data, center, extents);
1710                 RAS_MeshObject* meshobj = BL_ConvertMesh(mesh,ob,kxscene,converter);
1711                 
1712                 // needed for python scripting
1713                 kxscene->GetLogicManager()->RegisterMeshName(meshobj->GetName(),meshobj);
1714         
1715                 gameobj = new BL_DeformableGameObject(ob,kxscene,KX_Scene::m_callbacks);
1716         
1717                 // set transformation
1718                 gameobj->AddMesh(meshobj);
1719         
1720                 // for all objects: check whether they want to
1721                 // respond to updates
1722                 bool ignoreActivityCulling =  
1723                         ((ob->gameflag2 & OB_NEVER_DO_ACTIVITY_CULLING)!=0);
1724                 gameobj->SetIgnoreActivityCulling(ignoreActivityCulling);
1725                 gameobj->SetOccluder((ob->gameflag & OB_OCCLUDER) != 0, false);
1726         
1727                 // two options exists for deform: shape keys and armature
1728                 // only support relative shape key
1729                 bool bHasShapeKey = mesh->key != NULL && mesh->key->type==KEY_RELATIVE;
1730                 bool bHasDvert = mesh->dvert != NULL && ob->defbase.first;
1731                 bool bHasArmature = (ob->parent && ob->parent->type == OB_ARMATURE && ob->partype==PARSKEL && bHasDvert);
1732                 bool bHasModifier = BL_ModifierDeformer::HasCompatibleDeformer(ob);
1733                 bool bHasSoftBody = (!ob->parent && (ob->gameflag & OB_SOFT_BODY));
1734
1735                 if (bHasModifier) {
1736                         BL_ModifierDeformer *dcont = new BL_ModifierDeformer((BL_DeformableGameObject *)gameobj,
1737                                                                                                                                 kxscene->GetBlenderScene(), ob, meshobj);
1738                         ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
1739                         if (bHasShapeKey && bHasArmature)
1740                                 dcont->LoadShapeDrivers(ob->parent);
1741                 } else if (bHasShapeKey) {
1742                         // not that we can have shape keys without dvert! 
1743                         BL_ShapeDeformer *dcont = new BL_ShapeDeformer((BL_DeformableGameObject*)gameobj, 
1744                                                                                                                         ob, meshobj);
1745                         ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
1746                         if (bHasArmature)
1747                                 dcont->LoadShapeDrivers(ob->parent);
1748                 } else if (bHasArmature) {
1749                         BL_SkinDeformer *dcont = new BL_SkinDeformer((BL_DeformableGameObject*)gameobj,
1750                                                                                                                         ob, meshobj);
1751                         ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
1752                 } else if (bHasDvert) {
1753                         // this case correspond to a mesh that can potentially deform but not with the
1754                         // object to which it is attached for the moment. A skin mesh was created in
1755                         // BL_ConvertMesh() so must create a deformer too!
1756                         BL_MeshDeformer *dcont = new BL_MeshDeformer((BL_DeformableGameObject*)gameobj,
1757                                                                                                                   ob, meshobj);
1758                         ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
1759                 } else if (bHasSoftBody) {
1760                         KX_SoftBodyDeformer *dcont = new KX_SoftBodyDeformer(meshobj, (BL_DeformableGameObject*)gameobj);
1761                         ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
1762                 }
1763                 
1764                 MT_Point3 min = MT_Point3(center) - MT_Vector3(extents);
1765                 MT_Point3 max = MT_Point3(center) + MT_Vector3(extents);
1766                 SG_BBox bbox = SG_BBox(min, max);
1767                 gameobj->GetSGNode()->SetBBox(bbox);
1768                 gameobj->GetSGNode()->SetRadius(radius);
1769         
1770                 break;
1771         }
1772         
1773         case OB_ARMATURE:
1774         {
1775                 gameobj = new BL_ArmatureObject(
1776                         kxscene,
1777                         KX_Scene::m_callbacks,
1778                         ob,
1779                         kxscene->GetBlenderScene() // handle
1780                 );
1781                 /* Get the current pose from the armature object and apply it as the rest pose */
1782                 break;
1783         }
1784         
1785         case OB_EMPTY:
1786         {
1787                 gameobj = new KX_EmptyObject(kxscene,KX_Scene::m_callbacks);
1788                 // set transformation
1789                 break;
1790         }
1791         }
1792         if (gameobj) 
1793         {
1794                 gameobj->SetLayer(ob->lay);
1795                 gameobj->SetBlenderObject(ob);
1796                 /* set the visibility state based on the objects render option in the outliner */
1797                 if(ob->restrictflag & OB_RESTRICT_RENDER) gameobj->SetVisible(0, 0);
1798         }
1799         return gameobj;
1800 }
1801
1802 struct parentChildLink {
1803         struct Object* m_blenderchild;
1804         SG_Node* m_gamechildnode;
1805 };
1806
1807 #include "DNA_constraint_types.h"
1808 //XXX #include "BIF_editconstraint.h"
1809
1810 bPoseChannel *get_active_posechannel2 (Object *ob)
1811 {
1812         bArmature *arm= (bArmature*)ob->data;
1813         bPoseChannel *pchan;
1814         
1815         /* find active */
1816         for(pchan= (bPoseChannel *)ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1817                 if(pchan->bone && (pchan->bone == arm->act_bone) && (pchan->bone->layer & arm->layer))
1818                         return pchan;
1819         }
1820         
1821         return NULL;
1822 }
1823
1824 ListBase *get_active_constraints2(Object *ob)
1825 {
1826         if (!ob)
1827                 return NULL;
1828
1829   // XXX - shouldnt we care about the pose data and not the mode???
1830         if (ob->mode & OB_MODE_POSE) { 
1831                 bPoseChannel *pchan;
1832
1833                 pchan = get_active_posechannel2(ob);
1834                 if (pchan)
1835                         return &pchan->constraints;
1836         }
1837         else 
1838                 return &ob->constraints;
1839
1840         return NULL;
1841 }
1842
1843
1844 void RBJconstraints(Object *ob)//not used
1845 {
1846         ListBase *conlist;
1847         bConstraint *curcon;
1848
1849         conlist = get_active_constraints2(ob);
1850
1851         if (conlist) {
1852                 for (curcon = (bConstraint *)conlist->first; curcon; curcon=(bConstraint *)curcon->next) {
1853
1854                         printf("%i\n",curcon->type);
1855                 }
1856
1857
1858         }
1859 }
1860
1861 #include "PHY_IPhysicsEnvironment.h"
1862 #include "KX_IPhysicsController.h"
1863 #include "PHY_DynamicTypes.h"
1864
1865 KX_IPhysicsController* getPhId(CListValue* sumolist,STR_String busc){//not used
1866
1867     for (int j=0;j<sumolist->GetCount();j++)
1868         {
1869             KX_GameObject* gameobje = (KX_GameObject*) sumolist->GetValue(j);
1870             if (gameobje->GetName()==busc)
1871             return gameobje->GetPhysicsController();
1872         }
1873
1874         return 0;
1875
1876 }
1877
1878 KX_GameObject* getGameOb(STR_String busc,CListValue* sumolist){
1879
1880     for (int j=0;j<sumolist->GetCount();j++)
1881         {
1882             KX_GameObject* gameobje = (KX_GameObject*) sumolist->GetValue(j);
1883             if (gameobje->GetName()==busc)
1884             return gameobje;
1885         }
1886         
1887         return 0;
1888
1889 }
1890
1891 // convert blender objects into ketsji gameobjects
1892 void BL_ConvertBlenderObjects(struct Main* maggie,
1893                                                           KX_Scene* kxscene,
1894                                                           KX_KetsjiEngine* ketsjiEngine,
1895                                                           e_PhysicsEngine       physics_engine,
1896                                                           RAS_IRenderTools* rendertools,
1897                                                           RAS_ICanvas* canvas,
1898                                                           KX_BlenderSceneConverter* converter,
1899                                                           bool alwaysUseExpandFraming
1900                                                           )
1901 {       
1902
1903         Scene *blenderscene = kxscene->GetBlenderScene();
1904         // for SETLOOPER
1905         Scene *sce;
1906         Base *base;
1907
1908         // Get the frame settings of the canvas.
1909         // Get the aspect ratio of the canvas as designed by the user.
1910
1911         RAS_FrameSettings::RAS_FrameType frame_type;
1912         int aspect_width;
1913         int aspect_height;
1914         vector<MT_Vector3> inivel,iniang;
1915         set<Group*> grouplist;  // list of groups to be converted
1916         set<Object*> allblobj;  // all objects converted
1917         set<Object*> groupobj;  // objects from groups (never in active layer)
1918
1919         if (alwaysUseExpandFraming) {
1920                 frame_type = RAS_FrameSettings::e_frame_extend;
1921                 aspect_width = canvas->GetWidth();
1922                 aspect_height = canvas->GetHeight();
1923         } else {
1924                 if (blenderscene->gm.framing.type == SCE_GAMEFRAMING_BARS) {
1925                         frame_type = RAS_FrameSettings::e_frame_bars;
1926                 } else if (blenderscene->gm.framing.type == SCE_GAMEFRAMING_EXTEND) {
1927                         frame_type = RAS_FrameSettings::e_frame_extend;
1928                 } else {
1929                         frame_type = RAS_FrameSettings::e_frame_scale;
1930                 }
1931                 
1932                 aspect_width = blenderscene->gm.xsch;
1933                 aspect_height = blenderscene->gm.ysch;
1934         }
1935         
1936         RAS_FrameSettings frame_settings(
1937                 frame_type,
1938                 blenderscene->gm.framing.col[0],
1939                 blenderscene->gm.framing.col[1],
1940                 blenderscene->gm.framing.col[2],
1941                 aspect_width,
1942                 aspect_height
1943         );
1944         kxscene->SetFramingType(frame_settings);
1945
1946         kxscene->SetGravity(MT_Vector3(0,0, -blenderscene->gm.gravity));
1947         
1948         /* set activity culling parameters */
1949         kxscene->SetActivityCulling( (blenderscene->gm.mode & WO_ACTIVITY_CULLING) != 0);
1950         kxscene->SetActivityCullingRadius(blenderscene->gm.activityBoxRadius);
1951         kxscene->SetDbvtCulling((blenderscene->gm.mode & WO_DBVT_CULLING) != 0);
1952         
1953         // no occlusion culling by default
1954         kxscene->SetDbvtOcclusionRes(0);
1955
1956         int activeLayerBitInfo = blenderscene->lay;
1957         
1958         // list of all object converted, active and inactive
1959         CListValue*     sumolist = new CListValue();
1960         
1961         vector<parentChildLink> vec_parent_child;
1962         
1963         CListValue* objectlist = kxscene->GetObjectList();
1964         CListValue* inactivelist = kxscene->GetInactiveList();
1965         CListValue* parentlist = kxscene->GetRootParentList();
1966         
1967         SCA_LogicManager* logicmgr = kxscene->GetLogicManager();
1968         SCA_TimeEventManager* timemgr = kxscene->GetTimeEventManager();
1969         
1970         CListValue* logicbrick_conversionlist = new CListValue();
1971         
1972         //SG_TreeFactory tf;
1973         
1974         // Convert actions to actionmap
1975         bAction *curAct;
1976         for (curAct = (bAction*)maggie->action.first; curAct; curAct=(bAction*)curAct->id.next)
1977         {
1978                 logicmgr->RegisterActionName(curAct->id.name + 2, curAct);
1979         }
1980
1981         SetDefaultFaceType(blenderscene);
1982         // Let's support scene set.
1983         // Beware of name conflict in linked data, it will not crash but will create confusion
1984         // in Python scripting and in certain actuators (replace mesh). Linked scene *should* have
1985         // no conflicting name for Object, Object data and Action.
1986         for (SETLOOPER(blenderscene, base))
1987         {
1988                 Object* blenderobject = base->object;
1989                 allblobj.insert(blenderobject);
1990
1991                 KX_GameObject* gameobj = gameobject_from_blenderobject(
1992                                                                                 base->object, 
1993                                                                                 kxscene, 
1994                                                                                 rendertools, 
1995                                                                                 converter);
1996                                                                                 
1997                 bool isInActiveLayer = (blenderobject->lay & activeLayerBitInfo) !=0;
1998                 bool addobj=true;
1999                 
2000                 if (converter->addInitFromFrame)
2001                         if (!isInActiveLayer)
2002                                 addobj=false;
2003
2004                 if (gameobj&&addobj)
2005                 {
2006                         MT_Point3 posPrev;                      
2007                         MT_Matrix3x3 angor;                     
2008                         if (converter->addInitFromFrame) blenderscene->r.cfra=blenderscene->r.sfra;
2009                         
2010                         MT_Point3 pos;
2011                         pos.setValue(
2012                                 blenderobject->loc[0]+blenderobject->dloc[0],
2013                                 blenderobject->loc[1]+blenderobject->dloc[1],
2014                                 blenderobject->loc[2]+blenderobject->dloc[2]
2015                         );
2016                         MT_Vector3 eulxyz(blenderobject->rot);
2017                         MT_Vector3 scale(blenderobject->size);
2018                         if (converter->addInitFromFrame){//rcruiz
2019                                 float eulxyzPrev[3];
2020                                 blenderscene->r.cfra=blenderscene->r.sfra-1;
2021                                 //XXX update_for_newframe();
2022                                 MT_Vector3 tmp=pos-MT_Point3(blenderobject->loc[0]+blenderobject->dloc[0],
2023                                                                                         blenderobject->loc[1]+blenderobject->dloc[1],
2024                                                                                         blenderobject->loc[2]+blenderobject->dloc[2]
2025                                                                         );
2026                                 eulxyzPrev[0]=blenderobject->rot[0];
2027                                 eulxyzPrev[1]=blenderobject->rot[1];
2028                                 eulxyzPrev[2]=blenderobject->rot[2];
2029
2030                                 double fps = (double) blenderscene->r.frs_sec/
2031                                         (double) blenderscene->r.frs_sec_base;
2032
2033                                 tmp.scale(fps, fps, fps);
2034                                 inivel.push_back(tmp);
2035                                 tmp=eulxyz-eulxyzPrev;
2036                                 tmp.scale(fps, fps, fps);
2037                                 iniang.push_back(tmp);
2038                                 blenderscene->r.cfra=blenderscene->r.sfra;
2039                                 //XXX update_for_newframe();
2040                         }               
2041                                                 
2042                         gameobj->NodeSetLocalPosition(pos);
2043                         gameobj->NodeSetLocalOrientation(MT_Matrix3x3(eulxyz));
2044                         gameobj->NodeSetLocalScale(scale);
2045                         gameobj->NodeUpdateGS(0);
2046                         
2047                         BL_ConvertIpos(blenderobject,gameobj,converter);
2048                         BL_ConvertMaterialIpos(blenderobject, gameobj, converter);
2049                         
2050                         sumolist->Add(gameobj->AddRef());
2051                         
2052                         BL_ConvertProperties(blenderobject,gameobj,timemgr,kxscene,isInActiveLayer);
2053                         
2054                         gameobj->SetName(blenderobject->id.name + 2);
2055         
2056                         // update children/parent hierarchy
2057                         if ((blenderobject->parent != 0)&&(!converter->addInitFromFrame))
2058                         {
2059                                 // blender has an additional 'parentinverse' offset in each object
2060                                 SG_Callbacks callback(NULL,NULL,NULL,KX_Scene::KX_ScenegraphUpdateFunc,KX_Scene::KX_ScenegraphRescheduleFunc);
2061                                 SG_Node* parentinversenode = new SG_Node(NULL,kxscene,callback);
2062                         
2063                                 // define a normal parent relationship for this node.
2064                                 KX_NormalParentRelation * parent_relation = KX_NormalParentRelation::New();
2065                                 parentinversenode->SetParentRelation(parent_relation);
2066         
2067                                 parentChildLink pclink;
2068                                 pclink.m_blenderchild = blenderobject;
2069                                 pclink.m_gamechildnode = parentinversenode;
2070                                 vec_parent_child.push_back(pclink);
2071
2072                                 float* fl = (float*) blenderobject->parentinv;
2073                                 MT_Transform parinvtrans(fl);
2074                                 parentinversenode->SetLocalPosition(parinvtrans.getOrigin());
2075                                 // problem here: the parent inverse transform combines scaling and rotation 
2076                                 // in the basis but the scenegraph needs separate rotation and scaling.
2077                                 // This is not important for OpenGL (it uses 4x4 matrix) but it is important
2078                                 // for the physic engine that needs a separate scaling
2079                                 //parentinversenode->SetLocalOrientation(parinvtrans.getBasis());
2080
2081                                 // Extract the rotation and the scaling from the basis
2082                                 MT_Matrix3x3 ori(parinvtrans.getBasis());
2083                                 MT_Vector3 x(ori.getColumn(0));
2084                                 MT_Vector3 y(ori.getColumn(1));
2085                                 MT_Vector3 z(ori.getColumn(2));
2086                                 MT_Vector3 parscale(x.length(), y.length(), z.length());
2087                                 if (!MT_fuzzyZero(parscale[0]))
2088                                         x /= parscale[0];
2089                                 if (!MT_fuzzyZero(parscale[1]))
2090                                         y /= parscale[1];
2091                                 if (!MT_fuzzyZero(parscale[2]))
2092                                         z /= parscale[2];
2093                                 ori.setColumn(0, x);                                                            
2094                                 ori.setColumn(1, y);                                                            
2095                                 ori.setColumn(2, z);                                                            
2096                                 parentinversenode->SetLocalOrientation(ori);
2097                                 parentinversenode->SetLocalScale(parscale);
2098                                 
2099                                 parentinversenode->AddChild(gameobj->GetSGNode());
2100                         }
2101                         
2102                         // needed for python scripting
2103                         logicmgr->RegisterGameObjectName(gameobj->GetName(),gameobj);
2104
2105                         // needed for group duplication
2106                         logicmgr->RegisterGameObj(blenderobject, gameobj);
2107                         for (int i = 0; i < gameobj->GetMeshCount(); i++)
2108                                 logicmgr->RegisterGameMeshName(gameobj->GetMesh(i)->GetName(), blenderobject);
2109         
2110                         converter->RegisterGameObject(gameobj, blenderobject);  
2111                         // this was put in rapidly, needs to be looked at more closely
2112                         // only draw/use objects in active 'blender' layers
2113         
2114                         logicbrick_conversionlist->Add(gameobj->AddRef());
2115                         
2116                         if (converter->addInitFromFrame){
2117                                 posPrev=gameobj->NodeGetWorldPosition();
2118                                 angor=gameobj->NodeGetWorldOrientation();
2119                         }
2120                         if (isInActiveLayer)
2121                         {
2122                                 objectlist->Add(gameobj->AddRef());
2123                                 //tf.Add(gameobj->GetSGNode());
2124                                 
2125                                 gameobj->NodeUpdateGS(0);
2126                                 gameobj->AddMeshUser();
2127                 
2128                         }
2129                         else
2130                         {
2131                                 //we must store this object otherwise it will be deleted 
2132                                 //at the end of this function if it is not a root object
2133                                 inactivelist->Add(gameobj->AddRef());
2134                         }
2135                         if (gameobj->IsDupliGroup())
2136                                 grouplist.insert(blenderobject->dup_group);
2137                         if (converter->addInitFromFrame){
2138                                 gameobj->NodeSetLocalPosition(posPrev);
2139                                 gameobj->NodeSetLocalOrientation(angor);
2140                         }
2141                                                 
2142                 }
2143                 /* Note about memory leak issues:
2144                    When a CValue derived class is created, m_refcount is initialized to 1
2145                    so the class must be released after being used to make sure that it won't 
2146                    hang in memory. If the object needs to be stored for a long time, 
2147                    use AddRef() so that this Release() does not free the object.
2148                    Make sure that for any AddRef() there is a Release()!!!! 
2149                    Do the same for any object derived from CValue, CExpression and NG_NetworkMessage
2150                  */
2151                 if (gameobj)
2152                         gameobj->Release();
2153
2154         }
2155
2156         if (!grouplist.empty())
2157         {
2158                 // now convert the group referenced by dupli group object
2159                 // keep track of all groups already converted
2160                 set<Group*> allgrouplist = grouplist;
2161                 set<Group*> tempglist;
2162                 // recurse
2163                 while (!grouplist.empty())
2164                 {
2165                         set<Group*>::iterator git;
2166                         tempglist.clear();
2167                         tempglist.swap(grouplist);
2168                         for (git=tempglist.begin(); git!=tempglist.end(); git++)
2169                         {
2170                                 Group* group = *git;
2171                                 GroupObject* go;
2172                                 for(go=(GroupObject*)group->gobject.first; go; go=(GroupObject*)go->next) 
2173                                 {
2174                                         Object* blenderobject = go->ob;
2175                                         if (converter->FindGameObject(blenderobject) == NULL)
2176                                         {
2177                                                 allblobj.insert(blenderobject);
2178                                                 groupobj.insert(blenderobject);
2179                                                 KX_GameObject* gameobj = gameobject_from_blenderobject(
2180                                                                                                                 blenderobject, 
2181                                                                                                                 kxscene, 
2182                                                                                                                 rendertools, 
2183                                                                                                                 converter);
2184                                                                                 
2185                                                 // this code is copied from above except that
2186                                                 // object from groups are never in active layer
2187                                                 bool isInActiveLayer = false;
2188                                                 bool addobj=true;
2189                                                 
2190                                                 if (converter->addInitFromFrame)
2191                                                         if (!isInActiveLayer)
2192                                                                 addobj=false;
2193                                                                                                                 
2194                                                 if (gameobj&&addobj)
2195                                                 {
2196                                                         MT_Point3 posPrev;                      
2197                                                         MT_Matrix3x3 angor;                     
2198                                                         if (converter->addInitFromFrame) 
2199                                                                 blenderscene->r.cfra=blenderscene->r.sfra;
2200                                                         
2201                                                         MT_Point3 pos(
2202                                                                 blenderobject->loc[0]+blenderobject->dloc[0],
2203                                                                 blenderobject->loc[1]+blenderobject->dloc[1],
2204                                                                 blenderobject->loc[2]+blenderobject->dloc[2]
2205                                                         );
2206                                                         MT_Vector3 eulxyz(blenderobject->rot);
2207                                                         MT_Vector3 scale(blenderobject->size);
2208                                                         if (converter->addInitFromFrame){//rcruiz
2209                                                                 float eulxyzPrev[3];
2210                                                                 blenderscene->r.cfra=blenderscene->r.sfra-1;
2211                                                                 //XXX update_for_newframe();
2212                                                                 MT_Vector3 tmp=pos-MT_Point3(blenderobject->loc[0]+blenderobject->dloc[0],
2213                                                                                                                         blenderobject->loc[1]+blenderobject->dloc[1],
2214                                                                                                                         blenderobject->loc[2]+blenderobject->dloc[2]
2215                                                                                                         );
2216                                                                 eulxyzPrev[0]=blenderobject->rot[0];
2217                                                                 eulxyzPrev[1]=blenderobject->rot[1];
2218                                                                 eulxyzPrev[2]=blenderobject->rot[2];
2219
2220                                                                 double fps = (double) blenderscene->r.frs_sec/
2221                                                                         (double) blenderscene->r.frs_sec_base;
2222
2223                                                                 tmp.scale(fps, fps, fps);
2224                                                                 inivel.push_back(tmp);
2225                                                                 tmp=eulxyz-eulxyzPrev;
2226                                                                 tmp.scale(fps, fps, fps);
2227                                                                 iniang.push_back(tmp);
2228                                                                 blenderscene->r.cfra=blenderscene->r.sfra;
2229                                                                 //XXX update_for_newframe();
2230                                                         }               
2231                                                                                 
2232                                                         gameobj->NodeSetLocalPosition(pos);
2233                                                         gameobj->NodeSetLocalOrientation(MT_Matrix3x3(eulxyz));
2234                                                         gameobj->NodeSetLocalScale(scale);
2235                                                         gameobj->NodeUpdateGS(0);
2236                                                         
2237                                                         BL_ConvertIpos(blenderobject,gameobj,converter);
2238                                                         BL_ConvertMaterialIpos(blenderobject,gameobj, converter);       
2239                                         
2240                                                         sumolist->Add(gameobj->AddRef());
2241                                                         
2242                                                         BL_ConvertProperties(blenderobject,gameobj,timemgr,kxscene,isInActiveLayer);
2243                                                         
2244                                         
2245                                                         gameobj->SetName(blenderobject->id.name + 2);
2246                                         
2247                                                         // update children/parent hierarchy
2248                                                         if ((blenderobject->parent != 0)&&(!converter->addInitFromFrame))
2249                                                         {
2250                                                                 // blender has an additional 'parentinverse' offset in each object
2251                                                                 SG_Callbacks callback(NULL,NULL,NULL,KX_Scene::KX_ScenegraphUpdateFunc,KX_Scene::KX_ScenegraphRescheduleFunc);
2252                                                                 SG_Node* parentinversenode = new SG_Node(NULL,kxscene,callback);
2253                                                         
2254                                                                 // define a normal parent relationship for this node.
2255                                                                 KX_NormalParentRelation * parent_relation = KX_NormalParentRelation::New();
2256                                                                 parentinversenode->SetParentRelation(parent_relation);
2257                                         
2258                                                                 parentChildLink pclink;
2259                                                                 pclink.m_blenderchild = blenderobject;
2260                                                                 pclink.m_gamechildnode = parentinversenode;
2261                                                                 vec_parent_child.push_back(pclink);
2262
2263                                                                 float* fl = (float*) blenderobject->parentinv;
2264                                                                 MT_Transform parinvtrans(fl);
2265                                                                 parentinversenode->SetLocalPosition(parinvtrans.getOrigin());
2266
2267                                                                 // Extract the rotation and the scaling from the basis
2268                                                                 MT_Matrix3x3 ori(parinvtrans.getBasis());
2269                                                                 MT_Vector3 x(ori.getColumn(0));
2270                                                                 MT_Vector3 y(ori.getColumn(1));
2271                                                                 MT_Vector3 z(ori.getColumn(2));
2272                                                                 MT_Vector3 localscale(x.length(), y.length(), z.length());
2273                                                                 if (!MT_fuzzyZero(localscale[0]))
2274                                                                         x /= localscale[0];
2275                                                                 if (!MT_fuzzyZero(localscale[1]))
2276                                                                         y /= localscale[1];
2277                                                                 if (!MT_fuzzyZero(localscale[2]))
2278                                                                         z /= localscale[2];
2279                                                                 ori.setColumn(0, x);                                                            
2280                                                                 ori.setColumn(1, y);                                                            
2281                                                                 ori.setColumn(2, z);                                                            
2282                                                                 parentinversenode->SetLocalOrientation(ori);
2283                                                                 parentinversenode->SetLocalScale(localscale);
2284                                                                 
2285                                                                 parentinversenode->AddChild(gameobj->GetSGNode());
2286                                                         }
2287                                                         
2288                                                         // needed for python scripting
2289                                                         logicmgr->RegisterGameObjectName(gameobj->GetName(),gameobj);
2290
2291                                                         // needed for group duplication
2292                                                         logicmgr->RegisterGameObj(blenderobject, gameobj);
2293                                                         for (int i = 0; i < gameobj->GetMeshCount(); i++)
2294                                                                 logicmgr->RegisterGameMeshName(gameobj->GetMesh(i)->GetName(), blenderobject);
2295                                         
2296                                                         converter->RegisterGameObject(gameobj, blenderobject);  
2297                                                         // this was put in rapidly, needs to be looked at more closely
2298                                                         // only draw/use objects in active 'blender' layers
2299                                         
2300                                                         logicbrick_conversionlist->Add(gameobj->AddRef());
2301                                                         
2302                                                         if (converter->addInitFromFrame){
2303                                                                 posPrev=gameobj->NodeGetWorldPosition();
2304                                                                 angor=gameobj->NodeGetWorldOrientation();
2305                                                         }
2306                                                         if (isInActiveLayer)
2307                                                         {
2308                                                                 objectlist->Add(gameobj->AddRef());
2309                                                                 //tf.Add(gameobj->GetSGNode());
2310                                                                 
2311                                                                 gameobj->NodeUpdateGS(0);
2312                                                                 gameobj->AddMeshUser();
2313                                                         }
2314                                                         else
2315                                                         {
2316                                                                 //we must store this object otherwise it will be deleted 
2317                                                                 //at the end of this function if it is not a root object
2318                                                                 inactivelist->Add(gameobj->AddRef());
2319
2320                                                         }
2321                                                         if (gameobj->IsDupliGroup())
2322                                                         {
2323                                                                 // check that the group is not already converted
2324                                                                 if (allgrouplist.insert(blenderobject->dup_group).second)
2325                                                                         grouplist.insert(blenderobject->dup_group);
2326                                                         }
2327                                                         if (converter->addInitFromFrame){
2328                                                                 gameobj->NodeSetLocalPosition(posPrev);
2329                                                                 gameobj->NodeSetLocalOrientation(angor);
2330                                                         }
2331                                                                                 
2332                                                 }
2333                                                 if (gameobj)
2334                                                         gameobj->Release();
2335                                         }
2336                                 }
2337                         }
2338                 }
2339         }
2340
2341         // non-camera objects not supported as camera currently
2342         if (blenderscene->camera && blenderscene->camera->type == OB_CAMERA) {
2343                 KX_Camera *gamecamera= (KX_Camera*) converter->FindGameObject(blenderscene->camera);
2344                 
2345                 if(gamecamera)
2346                         kxscene->SetActiveCamera(gamecamera);
2347         }
2348
2349         //      Set up armatures
2350         set<Object*>::iterator oit;
2351         for(oit=allblobj.begin(); oit!=allblobj.end(); oit++)
2352         {
2353                 Object* blenderobj = *oit;
2354                 if (blenderobj->type==OB_MESH) {
2355                         Mesh *me = (Mesh*)blenderobj->data;
2356         
2357                         if (me->dvert){
2358                                 BL_DeformableGameObject *obj = (BL_DeformableGameObject*)converter->FindGameObject(blenderobj);
2359         
2360                                 if (obj && blenderobj->parent && blenderobj->parent->type==OB_ARMATURE && blenderobj->partype==PARSKEL){
2361                                         KX_GameObject *par = converter->FindGameObject(blenderobj->parent);
2362                                         if (par && obj->GetDeformer())
2363                                                 ((BL_SkinDeformer*)obj->GetDeformer())->SetArmature((BL_ArmatureObject*) par);
2364                                 }
2365                         }
2366                 }
2367         }
2368         
2369         // create hierarchy information
2370         int i;
2371         vector<parentChildLink>::iterator pcit;
2372         
2373         for (pcit = vec_parent_child.begin();!(pcit==vec_parent_child.end());++pcit)
2374         {
2375         
2376                 struct Object* blenderchild = pcit->m_blenderchild;
2377                 struct Object* blenderparent = blenderchild->parent;
2378                 KX_GameObject* parentobj = converter->FindGameObject(blenderparent);
2379                 KX_GameObject* childobj = converter->FindGameObject(blenderchild);
2380
2381                 assert(childobj);
2382
2383                 if (!parentobj || objectlist->SearchValue(childobj) != objectlist->SearchValue(parentobj))
2384                 {
2385                         // special case: the parent and child object are not in the same layer. 
2386                         // This weird situation is used in Apricot for test purposes.
2387                         // Resolve it by not converting the child
2388                         childobj->GetSGNode()->DisconnectFromParent();
2389                         delete pcit->m_gamechildnode;
2390                         // Now destroy the child object but also all its descendent that may already be linked
2391                         // Remove the child reference in the local list!
2392                         // Note: there may be descendents already if the children of the child were processed
2393                         //       by this loop before the child. In that case, we must remove the children also
2394                         CListValue* childrenlist = childobj->GetChildrenRecursive();
2395                         childrenlist->Add(childobj->AddRef());
2396                         for ( i=0;i<childrenlist->GetCount();i++)
2397                         {
2398                                 KX_GameObject* obj = static_cast<KX_GameObject*>(childrenlist->GetValue(i));
2399                                 if (sumolist->RemoveValue(obj))
2400                                         obj->Release();
2401                                 if (logicbrick_conversionlist->RemoveValue(obj))
2402                                         obj->Release();
2403                         }
2404                         childrenlist->Release();
2405                         
2406                         // now destroy recursively
2407                         converter->UnregisterGameObject(childobj); // removing objects during conversion make sure this runs too
2408                         kxscene->RemoveObject(childobj);
2409                         
2410                         continue;
2411                 }
2412
2413                 switch (blenderchild->partype)
2414                 {
2415                         case PARVERT1:
2416                         {
2417                                 // creat a new vertex parent relationship for this node.
2418                                 KX_VertexParentRelation * vertex_parent_relation = KX_VertexParentRelation::New();
2419                                 pcit->m_gamechildnode->SetParentRelation(vertex_parent_relation);
2420                                 break;
2421                         }
2422                         case PARSLOW:
2423                         {
2424                                 // creat a new slow parent relationship for this node.
2425                                 KX_SlowParentRelation * slow_parent_relation = KX_SlowParentRelation::New(blenderchild->sf);
2426                                 pcit->m_gamechildnode->SetParentRelation(slow_parent_relation);
2427                                 break;
2428                         }       
2429                         case PARBONE:
2430                         {
2431                                 // parent this to a bone
2432                                 Bone *parent_bone = get_named_bone( (bArmature *)(blenderchild->parent)->data, blenderchild->parsubstr);
2433
2434                                 if(parent_bone) {
2435                                         KX_BoneParentRelation *bone_parent_relation = KX_BoneParentRelation::New(parent_bone);
2436                                         pcit->m_gamechildnode->SetParentRelation(bone_parent_relation);
2437                                 }
2438                         
2439                                 break;
2440                         }
2441                         case PARSKEL: // skinned - ignore
2442                                 break;
2443                         case PAROBJECT:
2444                         case PARCURVE:
2445                         case PARKEY:
2446                         case PARVERT3:
2447                         default:
2448                                 // unhandled
2449                                 break;
2450                 }
2451         
2452                 parentobj->     GetSGNode()->AddChild(pcit->m_gamechildnode);
2453         }
2454         vec_parent_child.clear();
2455         
2456         // find 'root' parents (object that has not parents in SceneGraph)
2457         for (i=0;i<sumolist->GetCount();++i)
2458         {
2459                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2460                 if (gameobj->GetSGNode()->GetSGParent() == 0)
2461                 {
2462                         parentlist->Add(gameobj->AddRef());
2463                         gameobj->NodeUpdateGS(0);
2464                 }
2465         }
2466
2467         // create graphic controller for culling
2468         if (kxscene->GetDbvtCulling())
2469         {
2470                 bool occlusion = false;
2471                 for (i=0; i<sumolist->GetCount();i++)
2472                 {
2473                         KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2474                         if (gameobj->GetMeshCount() > 0) 
2475                         {
2476                                 MT_Point3 box[2];
2477                                 gameobj->GetSGNode()->BBox().getmm(box, MT_Transform::Identity());
2478                                 // box[0] is the min, box[1] is the max
2479                                 bool isactive = objectlist->SearchValue(gameobj);
2480                                 BL_CreateGraphicObjectNew(gameobj,box[0],box[1],kxscene,isactive,physics_engine);
2481                                 if (gameobj->GetOccluder())
2482                                         occlusion = true;
2483                         }
2484                 }
2485                 if (occlusion)
2486                         kxscene->SetDbvtOcclusionRes(blenderscene->gm.occlusionRes);
2487         }
2488         if (blenderscene->world)
2489                 kxscene->GetPhysicsEnvironment()->setNumTimeSubSteps(blenderscene->gm.physubstep);
2490
2491         // now that the scenegraph is complete, let's instantiate the deformers.
2492         // We need that to create reusable derived mesh and physic shapes
2493         for (i=0;i<sumolist->GetCount();++i)
2494         {
2495                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2496                 if (gameobj->GetDeformer())
2497                         gameobj->GetDeformer()->UpdateBuckets();
2498         }
2499
2500         // Set up armature constraints
2501         for (i=0;i<sumolist->GetCount();++i)
2502         {
2503                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2504                 if (gameobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE)
2505                         ((BL_ArmatureObject*)gameobj)->LoadConstraints(converter);
2506         }
2507
2508         bool processCompoundChildren = false;
2509
2510         // create physics information
2511         for (i=0;i<sumolist->GetCount();i++)
2512         {
2513                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2514                 struct Object* blenderobject = gameobj->GetBlenderObject();
2515                 int nummeshes = gameobj->GetMeshCount();
2516                 RAS_MeshObject* meshobj = 0;
2517                 if (nummeshes > 0)
2518                 {
2519                         meshobj = gameobj->GetMesh(0);
2520                 }
2521                 int layerMask = (groupobj.find(blenderobject) == groupobj.end()) ? activeLayerBitInfo : 0;
2522                 BL_CreatePhysicsObjectNew(gameobj,blenderobject,meshobj,kxscene,layerMask,physics_engine,converter,processCompoundChildren);
2523         }
2524
2525         processCompoundChildren = true;
2526         // create physics information
2527         for (i=0;i<sumolist->GetCount();i++)
2528         {
2529                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2530                 struct Object* blenderobject = gameobj->GetBlenderObject();
2531                 int nummeshes = gameobj->GetMeshCount();
2532                 RAS_MeshObject* meshobj = 0;
2533                 if (nummeshes > 0)
2534                 {
2535                         meshobj = gameobj->GetMesh(0);
2536                 }
2537                 int layerMask = (groupobj.find(blenderobject) == groupobj.end()) ? activeLayerBitInfo : 0;
2538                 BL_CreatePhysicsObjectNew(gameobj,blenderobject,meshobj,kxscene,layerMask,physics_engine,converter,processCompoundChildren);
2539         }
2540         
2541         //set ini linearVel and int angularVel //rcruiz
2542         if (converter->addInitFromFrame)
2543                 for (i=0;i<sumolist->GetCount();i++)
2544                 {
2545                         KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2546                         if (gameobj->IsDynamic()){
2547                                 gameobj->setLinearVelocity(inivel[i],false);
2548                                 gameobj->setAngularVelocity(iniang[i],false);
2549                         }
2550                 
2551                 
2552                 }       
2553
2554                 // create physics joints
2555         for (i=0;i<sumolist->GetCount();i++)
2556         {
2557                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2558                 struct Object* blenderobject = gameobj->GetBlenderObject();
2559                 ListBase *conlist;
2560                 bConstraint *curcon;
2561                 conlist = get_active_constraints2(blenderobject);
2562
2563                 if (conlist) {
2564                         for (curcon = (bConstraint *)conlist->first; curcon; curcon=(bConstraint *)curcon->next) {
2565                                 if (curcon->type==CONSTRAINT_TYPE_RIGIDBODYJOINT){
2566
2567                                         bRigidBodyJointConstraint *dat=(bRigidBodyJointConstraint *)curcon->data;
2568
2569                                         if (!dat->child){
2570
2571                                                 PHY_IPhysicsController* physctr2 = 0;
2572
2573                                                 if (dat->tar)
2574                                                 {
2575                                                         KX_GameObject *gotar=getGameOb(dat->tar->id.name,sumolist);
2576                                                         if (gotar && gotar->GetPhysicsController())
2577                                                                 physctr2 = (PHY_IPhysicsController*) gotar->GetPhysicsController()->GetUserData();
2578                                                 }
2579
2580                                                 if (gameobj->GetPhysicsController())
2581                                                 {
2582                                                         float radsPerDeg = 6.283185307179586232f / 360.f;
2583
2584                                                         PHY_IPhysicsController* physctrl = (PHY_IPhysicsController*) gameobj->GetPhysicsController()->GetUserData();
2585                                                         //we need to pass a full constraint frame, not just axis
2586                                     
2587                                                         //localConstraintFrameBasis
2588                                                         MT_Matrix3x3 localCFrame(MT_Vector3(radsPerDeg*dat->axX,radsPerDeg*dat->axY,radsPerDeg*dat->axZ));
2589                                                         MT_Vector3 axis0 = localCFrame.getColumn(0);
2590                                                         MT_Vector3 axis1 = localCFrame.getColumn(1);
2591                                                         MT_Vector3 axis2 = localCFrame.getColumn(2);
2592                                                                 
2593                                                         int constraintId = kxscene->GetPhysicsEnvironment()->createConstraint(physctrl,physctr2,(PHY_ConstraintType)dat->type,(float)dat->pivX,
2594                                                                 (float)dat->pivY,(float)dat->pivZ,
2595                                                                 (float)axis0.x(),(float)axis0.y(),(float)axis0.z(),
2596                                                                 (float)axis1.x(),(float)axis1.y(),(float)axis1.z(),
2597                                                                 (float)axis2.x(),(float)axis2.y(),(float)axis2.z(),dat->flag);
2598                                                         if (constraintId)
2599                                                         {
2600                                                                 //if it is a generic 6DOF constraint, set all the limits accordingly
2601                                                                 if (dat->type == PHY_GENERIC_6DOF_CONSTRAINT)
2602                                                                 {
2603                                                                         int dof;
2604                                                                         int dofbit=1;
2605                                                                         for (dof=0;dof<6;dof++)
2606                                                                         {
2607                                                                                 if (dat->flag & dofbit)
2608                                                                                 {
2609                                                                                         kxscene->GetPhysicsEnvironment()->setConstraintParam(constraintId,dof,dat->minLimit[dof],dat->maxLimit[dof]);
2610                                                                                 } else
2611                                                                                 {
2612                     &nbs