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