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