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