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