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