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