Reserved some Bullet 2.x constraint data.
[blender.git] / source / gameengine / Converter / BL_BlenderDataConversion.cpp
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL/BL DUAL 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. The Blender
10  * Foundation also sells licenses for use in proprietary software under
11  * the Blender License.  See http://www.blender.org/BL/ for information
12  * about this.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
24  * All rights reserved.
25  *
26  * The Original Code is: all of this file.
27  *
28  * Contributor(s): none yet.
29  *
30  * ***** END GPL/BL DUAL LICENSE BLOCK *****
31  * Convert blender data to ketsji
32  */
33
34 #ifdef HAVE_CONFIG_H
35 #include <config.h>
36 #endif
37
38 #ifdef WIN32
39 #pragma warning (disable : 4786)
40 #endif
41
42 #include <math.h>
43
44 #include "BL_BlenderDataConversion.h"
45 #include "KX_BlenderGL.h"
46 #include "KX_BlenderScalarInterpolator.h"
47
48 #include "RAS_IPolygonMaterial.h"
49 #include "KX_PolygonMaterial.h"
50
51 // Expressions
52 #include "ListValue.h"
53 #include "IntValue.h"
54 // Collision & Fuzzics LTD
55
56 #include "PHY_Pro.h"
57
58
59 #include "KX_Scene.h"
60 #include "KX_GameObject.h"
61 #include "RAS_FramingManager.h"
62 #include "RAS_MeshObject.h"
63
64 #include "KX_ConvertActuators.h"
65 #include "KX_ConvertControllers.h"
66 #include "KX_ConvertSensors.h"
67
68 #include "SCA_LogicManager.h"
69 #include "SCA_EventManager.h"
70 #include "SCA_TimeEventManager.h"
71 #include "KX_Light.h"
72 #include "KX_Camera.h"
73 #include "KX_EmptyObject.h"
74 #include "MT_Point3.h"
75 #include "MT_Transform.h"
76 #include "MT_MinMax.h"
77 #include "SCA_IInputDevice.h"
78 #include "RAS_TexMatrix.h"
79 #include "RAS_ICanvas.h"
80 #include "RAS_MaterialBucket.h"
81 //#include "KX_BlenderPolyMaterial.h"
82 #include "RAS_Polygon.h"
83 #include "RAS_TexVert.h"
84 #include "RAS_BucketManager.h"
85 #include "RAS_IRenderTools.h"
86 #include "BL_Material.h"
87 #include "KX_BlenderMaterial.h"
88 #include "BL_Texture.h"
89
90 #include "DNA_action_types.h"
91 #include "BKE_main.h"
92 #include "BKE_global.h"
93 #include "BL_SkinMeshObject.h"
94 #include "BL_SkinDeformer.h"
95 #include "BL_MeshDeformer.h"
96 //#include "BL_ArmatureController.h"
97
98 #include "BlenderWorldInfo.h"
99
100 #include "KX_KetsjiEngine.h"
101 #include "KX_BlenderSceneConverter.h"
102
103 #include"SND_Scene.h"
104 #include "SND_SoundListener.h"
105
106 /* This little block needed for linking to Blender... */
107 #ifdef WIN32
108 #include "BLI_winstuff.h"
109 #endif
110
111 /* This list includes only data type definitions */
112 #include "DNA_object_types.h"
113 #include "DNA_material_types.h"
114 #include "DNA_texture_types.h"
115 #include "DNA_image_types.h"
116 #include "DNA_lamp_types.h"
117 #include "DNA_group_types.h"
118 #include "DNA_scene_types.h"
119 #include "DNA_camera_types.h"
120 #include "DNA_property_types.h"
121 #include "DNA_text_types.h"
122 #include "DNA_sensor_types.h"
123 #include "DNA_controller_types.h"
124 #include "DNA_actuator_types.h"
125 #include "DNA_mesh_types.h"
126 #include "DNA_meshdata_types.h"
127 #include "DNA_view3d_types.h"
128 #include "DNA_world_types.h"
129 #include "DNA_sound_types.h"
130 #include "DNA_key_types.h"
131 #include "DNA_armature_types.h"
132
133 #include "MEM_guardedalloc.h"
134 #include "BKE_utildefines.h"
135 #include "BKE_key.h"
136 #include "BKE_mesh.h"
137 #include "MT_Point3.h"
138
139
140 #include "BKE_material.h" /* give_current_material */
141 /* end of blender include block */
142
143 #include "KX_BlenderInputDevice.h"
144 #include "KX_ConvertProperties.h"
145 #include "KX_HashedPtr.h"
146
147
148 #include "KX_ScalarInterpolator.h"
149
150 #include "KX_IpoConvert.h"
151 #include "SYS_System.h"
152
153 #include "SG_Node.h"
154 #include "SG_BBox.h"
155 #include "SG_Tree.h"
156
157 // defines USE_ODE to choose physics engine
158 #include "KX_ConvertPhysicsObject.h"
159
160
161 // This file defines relationships between parents and children
162 // in the game engine.
163
164 #include "KX_SG_NodeRelationships.h"
165 #include "KX_SG_BoneParentNodeRelationship.h"
166
167 #include "BL_ArmatureObject.h"
168 #include "BL_DeformableGameObject.h"
169
170 static int default_face_mode = TF_DYNAMIC;
171
172 static unsigned int KX_rgbaint2uint_new(unsigned int icol)
173 {
174         union
175         {
176                 unsigned int integer;
177                 unsigned char cp[4];
178         } out_colour, in_colour;
179         
180         in_colour.integer = icol;
181         out_colour.cp[0] = in_colour.cp[3]; // red
182         out_colour.cp[1] = in_colour.cp[2]; // green
183         out_colour.cp[2] = in_colour.cp[1]; // blue
184         out_colour.cp[3] = in_colour.cp[0]; // alpha
185         
186         return out_colour.integer;
187 }
188
189 /* Now the real converting starts... */
190 static unsigned int KX_Mcol2uint_new(MCol col)
191 {
192         /* color has to be converted without endian sensitivity. So no shifting! */
193         union
194         {
195                 MCol col;
196                 unsigned int integer;
197                 unsigned char cp[4];
198         } out_colour, in_colour;
199
200         in_colour.col = col;
201         out_colour.cp[0] = in_colour.cp[3]; // red
202         out_colour.cp[1] = in_colour.cp[2]; // green
203         out_colour.cp[2] = in_colour.cp[1]; // blue
204         out_colour.cp[3] = in_colour.cp[0]; // alpha
205         
206         return out_colour.integer;
207 }
208
209 static void SetDefaultFaceType(Scene* scene)
210 {
211         default_face_mode = TF_DYNAMIC;
212         Base *base = static_cast<Base*>(scene->base.first);
213         while(base)
214         {
215                 if (base->object->type == OB_LAMP)
216                 {
217                         default_face_mode = TF_DYNAMIC|TF_LIGHT;
218                         return;
219                 }
220                 base = base->next;
221         }
222 }
223
224
225 // --
226 static void GetRGB(short type,
227         MFace* mface,
228         MCol* mmcol,
229         Material *mat,
230         unsigned int &c0, 
231         unsigned int &c1, 
232         unsigned int &c2, 
233         unsigned int &c3)
234 {
235         unsigned int colour = 0xFFFFFFFFL;
236         switch(type)
237         {
238                 case 0: // vertex colors
239                 {
240                         if(mmcol) {
241                                 c0 = KX_Mcol2uint_new(mmcol[0]);
242                                 c1 = KX_Mcol2uint_new(mmcol[1]);
243                                 c2 = KX_Mcol2uint_new(mmcol[2]);
244                                 if (mface->v4)
245                                         c3 = KX_Mcol2uint_new(mmcol[3]);
246                         }else // backup white
247                         {
248                                 c0 = KX_rgbaint2uint_new(colour);
249                                 c1 = KX_rgbaint2uint_new(colour);
250                                 c2 = KX_rgbaint2uint_new(colour);       
251                                 if (mface->v4)
252                                         c3 = KX_rgbaint2uint_new( colour );
253                         }
254                 } break;
255                 
256         
257                 case 1: // material rgba
258                 {
259                         if (mat) {
260                                 union {
261                                         unsigned char cp[4];
262                                         unsigned int integer;
263                                 } col_converter;
264                                 col_converter.cp[3] = (unsigned char) (mat->r*255.0);
265                                 col_converter.cp[2] = (unsigned char) (mat->g*255.0);
266                                 col_converter.cp[1] = (unsigned char) (mat->b*255.0);
267                                 col_converter.cp[0] = (unsigned char) (mat->alpha*255.0);
268                                 colour = col_converter.integer;
269                         }
270                         c0 = KX_rgbaint2uint_new(colour);
271                         c1 = KX_rgbaint2uint_new(colour);
272                         c2 = KX_rgbaint2uint_new(colour);       
273                         if (mface->v4)
274                                 c3 = KX_rgbaint2uint_new(colour);
275                 } break;
276                 
277                 default: // white
278                 {
279                         c0 = KX_rgbaint2uint_new(colour);
280                         c1 = KX_rgbaint2uint_new(colour);
281                         c2 = KX_rgbaint2uint_new(colour);       
282                         if (mface->v4)
283                                 c3 = KX_rgbaint2uint_new(colour);
284                 } break;
285         }
286 }
287
288 // ------------------------------------
289 BL_Material* ConvertMaterial(  Mesh* mesh, Material *mat, MTFace* tface,  MFace* mface, MCol* mmcol, int lightlayer, Object* blenderobj )
290 {
291         //this needs some type of manager
292         BL_Material *material = new BL_Material();
293
294         int numchan =   -1;
295         bool validmat   = (mat!=0);
296         bool validface  = (mesh->mtface && tface);
297         
298         short type = 0;
299         if( validmat )
300                 type = 1; // material color 
301         
302         material->IdMode = DEFAULT_BLENDER;
303
304         // --------------------------------
305         if(validmat) {
306
307                 // use vertex colors by explicitly setting
308                 if(mat->mode &MA_VERTEXCOLP)
309                         type = 0;
310
311                 // use lighting?
312                 material->ras_mode |= ( mat->mode & MA_SHLESS )?0:USE_LIGHT;
313                 MTex *mttmp = 0;
314                 numchan = getNumTexChannels(mat);
315                 int valid_index = 0;
316                 
317                 // use the face texture if
318                 // 1) it is set in the buttons
319                 // 2) we have a face texture and a material but no valid texture in slot 1
320                 bool facetex = false;
321                 if(validface && mat->mode &MA_FACETEXTURE) 
322                         facetex = true;
323                 if(validface && !mat->mtex[0])
324                         facetex = true;
325                 if(validface && mat->mtex[0]) {
326                         MTex *tmp = mat->mtex[0];
327                         if(!tmp->tex || tmp->tex && !tmp->tex->ima )
328                                 facetex = true;
329                 }
330                 numchan = numchan>MAXTEX?MAXTEX:numchan;
331         
332                 // foreach MTex
333                 for(int i=0; i<numchan; i++) {
334                         // use face tex
335                         if(i==0 && facetex ) {
336                                 Image*tmp = (Image*)(tface->tpage);
337                                 if(tmp) {
338                                         material->img[i] = tmp;
339                                         material->texname[i] = material->img[i]->id.name;
340                                         material->flag[i] |= ( tface->transp  &TF_ALPHA )?USEALPHA:0;
341                                         material->flag[i] |= ( tface->transp  &TF_ADD   )?CALCALPHA:0;
342                                         material->ras_mode|= ( tface->transp  &(TF_ADD | TF_ALPHA))?TRANSP:0;
343                                         if(material->img[i]->flag & IMA_REFLECT)
344                                                 material->mapping[i].mapping |= USEREFL;
345                                         else
346                                                 material->mapping[i].mapping |= USEUV;
347                                         if(material->ras_mode & USE_LIGHT)
348                                                 material->ras_mode &= ~USE_LIGHT;
349                                         if(tface->mode & TF_LIGHT)
350                                                 material->ras_mode |= USE_LIGHT;
351
352                                         valid_index++;
353                                 }
354                                 else {
355                                         material->img[i] = 0;
356                                         material->texname[i] = "";
357                                 }
358                                 continue;
359                         }
360
361                         mttmp = getImageFromMaterial( mat, i );
362                         if( mttmp ) {
363                                 if( mttmp->tex ) {
364                                         if( mttmp->tex->type == TEX_IMAGE ) {
365                                                 material->mtexname[i] = mttmp->tex->id.name;
366                                                 material->img[i] = mttmp->tex->ima;
367                                                 if( material->img[i] ) {
368
369                                                         material->texname[i] = material->img[i]->id.name;
370                                                         material->flag[i] |= ( mttmp->tex->imaflag &TEX_MIPMAP )?MIPMAP:0;
371                                                         // -----------------------
372                                                         if( mttmp->tex->imaflag &TEX_USEALPHA ) {
373                                                                 material->flag[i]       |= USEALPHA;
374                                                         }
375                                                         // -----------------------
376                                                         else if( mttmp->tex->imaflag &TEX_CALCALPHA ) {
377                                                                 material->flag[i]       |= CALCALPHA;
378                                                         }
379                                                         else if(mttmp->tex->flag &TEX_NEGALPHA) {
380                                                                 material->flag[i]       |= USENEGALPHA;
381                                                         }
382
383                                                         material->color_blend[i] = mttmp->colfac;
384                                                         material->flag[i] |= ( mttmp->mapto  & MAP_ALPHA                )?TEXALPHA:0;
385                                                         material->flag[i] |= ( mttmp->texflag& MTEX_NEGATIVE    )?TEXNEG:0;
386
387                                                 }
388                                         }
389                                         else if(mttmp->tex->type == TEX_ENVMAP) {
390                                                 if( mttmp->tex->env->stype == ENV_LOAD ) {
391                                         
392                                                         material->mtexname[i]= mttmp->tex->id.name;
393                                                         material->cubemap[i] = mttmp->tex->env;
394                                                         if(material->cubemap[i]->ima) {
395                                                                 material->texname[i] = material->cubemap[i]->ima->id.name;
396                                                                 material->mapping[i].mapping |= USEENV;
397                                                         }
398                                                         else {
399                                                                 // in the player, we need to split it our self
400                                                                 material->cubemap[i]->ima = mttmp->tex->ima;
401                                                                 if(material->cubemap[i]->ima) {
402                                                                         material->texname[i] = material->cubemap[i]->ima->id.name;
403                                                                         material->mapping[i].mapping |= USEENV;
404                                                                 }
405                                                                 //
406                                                         }
407                                                 }
408                                         }
409                                         material->flag[i] |= (mat->ipo!=0)?HASIPO:0;
410                                         /// --------------------------------
411                                         // mapping methods
412                                         material->mapping[i].mapping |= ( mttmp->texco  & TEXCO_REFL    )?USEREFL:0;
413                                         
414                                         if(mttmp->texco & TEXCO_OBJECT) {
415                                                 material->mapping[i].mapping |= USEOBJ;
416                                                 if(mttmp->object)
417                                                         material->mapping[i].objconame = mttmp->object->id.name;
418                                         }
419                                         else if(mttmp->texco &TEXCO_REFL)
420                                                 material->mapping[i].mapping |= USEREFL;
421                                         else if(mttmp->texco &(TEXCO_ORCO|TEXCO_GLOB))
422                                                 material->mapping[i].mapping |= USEORCO;
423                                         else if(mttmp->texco &TEXCO_UV)
424                                                 material->mapping[i].mapping |= USEUV;
425                                         else if(mttmp->texco &TEXCO_NORM)
426                                                 material->mapping[i].mapping |= USENORM;
427                                         else if(mttmp->texco &TEXCO_TANGENT)
428                                                 material->mapping[i].mapping |= USETANG;
429                                         else
430                                                 material->mapping[i].mapping |= DISABLE;
431                                         
432                                         material->mapping[i].scale[0] = mttmp->size[0];
433                                         material->mapping[i].scale[1] = mttmp->size[1];
434                                         material->mapping[i].scale[2] = mttmp->size[2];
435                                         material->mapping[i].offsets[0] = mttmp->ofs[0];
436                                         material->mapping[i].offsets[1] = mttmp->ofs[1];
437                                         material->mapping[i].offsets[2] = mttmp->ofs[2];
438
439                                         material->mapping[i].projplane[0] = mttmp->projx;
440                                         material->mapping[i].projplane[1] = mttmp->projy;
441                                         material->mapping[i].projplane[2] = mttmp->projz;
442                                         /// --------------------------------
443                                         
444                                         switch( mttmp->blendtype ) {
445                                         case MTEX_BLEND:
446                                                 material->blend_mode[i] = BLEND_MIX;
447                                                 break;
448                                         case MTEX_MUL:
449                                                 material->blend_mode[i] = BLEND_MUL;
450                                                 break;
451                                         case MTEX_ADD:
452                                                 material->blend_mode[i] = BLEND_ADD;
453                                                 break;
454                                         case MTEX_SUB:
455                                                 material->blend_mode[i] = BLEND_SUB;
456                                                 break;
457                                         case MTEX_SCREEN:
458                                                 material->blend_mode[i] = BLEND_SCR;
459                                                 break;
460                                         }
461                                         valid_index++;
462                                 }
463                         }
464                 }
465                 // above one tex the switches here
466                 // are not used
467                 switch(valid_index) {
468                 case 0:
469                         material->IdMode = DEFAULT_BLENDER;
470                         break;
471                 case 1:
472                         material->IdMode = ONETEX;
473                         break;
474                 default:
475                         material->IdMode = GREATERTHAN2;
476                         break;
477                 }
478                 material->SetUsers(mat->id.us);
479
480                 material->num_enabled = valid_index;
481
482                 material->speccolor[0]  = mat->specr;
483                 material->speccolor[1]  = mat->specg;
484                 material->speccolor[2]  = mat->specb;
485                 material->hard                  = (float)mat->har/4.0f;
486                 material->matcolor[0]   = mat->r;
487                 material->matcolor[1]   = mat->g;
488                 material->matcolor[2]   = mat->b;
489                 material->matcolor[3]   = mat->alpha;
490                 material->alpha                 = mat->alpha;
491                 material->emit                  = mat->emit;
492                 material->spec_f                = mat->spec;
493                 material->ref                   = mat->ref;
494                 material->amb                   = mat->amb;
495
496                 // set alpha testing without z-sorting
497                 if( ( validface && (!tface->transp)) && mat->mode & MA_ZTRA) {
498                         // sets the RAS_IPolyMaterial::m_flag |RAS_FORCEALPHA
499                         // this is so we don't have the overhead of the z-sorting code
500                         material->ras_mode|=ALPHA_TEST;
501                 }
502                 else{
503                         // use regular z-sorting
504                         material->ras_mode |= ((mat->mode & MA_ZTRA) != 0)?ZSORT:0;
505                 }
506                 material->ras_mode |= ((mat->mode & MA_WIRE) != 0)?WIRE:0;
507         }
508         else {
509                 int valid = 0;
510                 // check for tface tex to fallback on
511                 if( validface ){
512
513                         // no light bugfix
514                         if(tface->mode) material->ras_mode |= USE_LIGHT;
515
516                         material->img[0] = (Image*)(tface->tpage);
517                         // ------------------------
518                         if(material->img[0]) {
519                                 material->texname[0] = material->img[0]->id.name;
520                                 material->mapping[0].mapping |= ( (material->img[0]->flag & IMA_REFLECT)!=0 )?USEREFL:0;
521                                 material->flag[0] |= ( tface->transp  &TF_ALPHA )?USEALPHA:0;
522                                 material->flag[0] |= ( tface->transp  &TF_ADD   )?CALCALPHA:0;
523                                 material->ras_mode|= ( tface->transp  & (TF_ADD|TF_ALPHA))?TRANSP:0;
524                                 valid++;
525                         }
526                 }
527                 material->SetUsers(-1);
528                 material->num_enabled   = valid;
529                 material->IdMode                = TEXFACE;
530                 material->speccolor[0]  = 1.f;
531                 material->speccolor[1]  = 1.f;
532                 material->speccolor[2]  = 1.f;
533                 material->hard                  = 35.f;
534                 material->matcolor[0]   = 0.5f;
535                 material->matcolor[1]   = 0.5f;
536                 material->matcolor[2]   = 0.5f;
537                 material->spec_f                = 0.5f;
538                 material->ref                   = 0.8f;
539         }
540         MT_Point2 uv[4];
541
542         if( validface ) {
543
544                 material->ras_mode |= !( 
545                         (tface->flag & TF_HIDE) ||
546                         (tface->mode & TF_INVISIBLE)
547                         )?POLY_VIS:0;
548
549                 material->ras_mode |= ( (tface->mode & TF_DYNAMIC)!= 0 )?COLLIDER:0;
550                 material->transp = tface->transp;
551                 
552                 if(tface->transp)
553                         material->ras_mode |= TRANSP;
554
555                 material->tile  = tface->tile;
556                 material->mode  = tface->mode;
557                         
558                 uv[0]   = MT_Point2(tface->uv[0]);
559                 uv[1]   = MT_Point2(tface->uv[1]);
560                 uv[2]   = MT_Point2(tface->uv[2]);
561
562                 if (mface->v4) 
563                         uv[3]   = MT_Point2(tface->uv[3]);
564         } 
565         else {
566                 // nothing at all
567                 material->ras_mode |= (COLLIDER|POLY_VIS| (validmat?0:USE_LIGHT));
568                 material->mode          = default_face_mode;    
569                 material->transp        = TF_SOLID;
570                 material->tile          = 0;
571         }
572         unsigned int rgb[4];
573         GetRGB(type,mface,mmcol,mat,rgb[0],rgb[1],rgb[2], rgb[3]);
574         material->SetConversionRGB(rgb);
575         material->SetConversionUV(uv);
576
577         material->ras_mode |= (mface->v4==0)?TRIANGLE:0;
578         if(validmat)
579                 material->matname       =(mat->id.name);
580
581         material->tface         = tface;
582         material->material      = mat;
583         return material;
584 }
585
586
587 static void BL_ComputeTriTangentSpace(const MT_Vector3 &v1, const MT_Vector3 &v2, const MT_Vector3 &v3, 
588         const MT_Vector2 &uv1, const MT_Vector2 &uv2, const MT_Vector2 &uv3, 
589         MFace* mface, MT_Vector3 *tan1, MT_Vector3 *tan2)
590 {
591                 MT_Vector3 dx1(v2 - v1), dx2(v3 - v1);
592                 MT_Vector2 duv1(uv2 - uv1), duv2(uv3 - uv1);
593                 
594                 MT_Scalar r = 1.0 / (duv1.x() * duv2.y() - duv2.x() * duv1.y());
595                 duv1 *= r;
596                 duv2 *= r;
597                 MT_Vector3 sdir(duv2.y() * dx1 - duv1.y() * dx2);
598                 MT_Vector3 tdir(duv1.x() * dx2 - duv2.x() * dx1);
599                 
600                 tan1[mface->v1] += sdir;
601                 tan1[mface->v2] += sdir;
602                 tan1[mface->v3] += sdir;
603                 
604                 tan2[mface->v1] += tdir;
605                 tan2[mface->v2] += tdir;
606                 tan2[mface->v3] += tdir;
607 }
608
609 static MT_Vector4*  BL_ComputeMeshTangentSpace(Mesh* mesh)
610 {
611         MFace* mface = static_cast<MFace*>(mesh->mface);
612         MTFace* tface = static_cast<MTFace*>(mesh->mtface);
613
614         MT_Vector3 *tan1 = new MT_Vector3[mesh->totvert];
615         MT_Vector3 *tan2 = new MT_Vector3[mesh->totvert];
616         
617         unsigned int v;
618         for (v = 0; v < mesh->totvert; v++)
619         {
620                 tan1[v] = MT_Vector3(0.0, 0.0, 0.0);
621                 tan2[v] = MT_Vector3(0.0, 0.0, 0.0);
622         }
623         
624         for (unsigned int p = 0; p < mesh->totface; p++, mface++, tface++)
625         {
626                 MT_Vector3      v1(mesh->mvert[mface->v1].co),
627                                 v2(mesh->mvert[mface->v2].co),
628                                 v3(mesh->mvert[mface->v3].co);
629                                 
630                 MT_Vector2      uv1(tface->uv[0]),
631                                 uv2(tface->uv[1]),
632                                 uv3(tface->uv[2]);
633                                 
634                 BL_ComputeTriTangentSpace(v1, v2, v3, uv1, uv2, uv3, mface, tan1, tan2);
635                 if (mface->v4)
636                 {
637                         MT_Vector3 v4(mesh->mvert[mface->v4].co);
638                         MT_Vector2 uv4(tface->uv[3]);
639                         
640                         BL_ComputeTriTangentSpace(v1, v3, v4, uv1, uv3, uv4, mface, tan1, tan2);
641                 }
642         }
643         
644         MT_Vector4 *tangent = new MT_Vector4[mesh->totvert];
645         for (v = 0; v < mesh->totvert; v++)
646         {
647                 const MT_Vector3 no(mesh->mvert[v].no[0]/32767.0, 
648                                         mesh->mvert[v].no[1]/32767.0, 
649                                         mesh->mvert[v].no[2]/32767.0);
650                 // Gram-Schmidt orthogonalize
651                 MT_Vector3 t(tan1[v] - no.cross(no.cross(tan1[v])));
652                 if (!MT_fuzzyZero(t))
653                         t /= t.length();
654
655                 tangent[v].x() = t.x();
656                 tangent[v].y() = t.y();
657                 tangent[v].z() = t.z();
658                 // Calculate handedness
659                 tangent[v].w() = no.dot(tan1[v].cross(tan2[v])) < 0.0 ? -1.0 : 1.0;
660         }
661         
662         delete [] tan1;
663         delete [] tan2;
664         
665         return tangent;
666 }
667
668 RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, RAS_IRenderTools* rendertools, KX_Scene* scene, KX_BlenderSceneConverter *converter)
669 {
670         RAS_MeshObject *meshobj;
671         bool    skinMesh = false;
672         
673         int lightlayer = blenderobj->lay;
674         
675         MFace* mface = static_cast<MFace*>(mesh->mface);
676         MTFace* tface = static_cast<MTFace*>(mesh->mtface);
677         MCol* mmcol = mesh->mcol;
678         MT_assert(mface || mesh->totface == 0);
679         
680         // Determine if we need to make a skinned mesh
681         if (mesh->dvert){
682                 meshobj = new BL_SkinMeshObject(lightlayer);
683                 skinMesh = true;
684         }
685         else {
686                 meshobj = new RAS_MeshObject(lightlayer);
687         }
688         MT_Vector4 *tangent = 0;
689         if (tface)
690                 tangent = BL_ComputeMeshTangentSpace(mesh);
691         
692         meshobj->SetName(mesh->id.name);
693         
694         meshobj->m_xyz_index_to_vertex_index_mapping.resize(mesh->totvert);
695         
696         for (int f=0;f<mesh->totface;f++,mface++)
697         {
698                 
699                 bool collider = true;
700                 
701                 // only add valid polygons
702                 if (mface->v3)
703                 {
704                         MT_Point2 uv0(0.0,0.0),uv1(0.0,0.0),uv2(0.0,0.0),uv3(0.0,0.0);
705                         // rgb3 is set from the adjoint face in a square
706                         unsigned int rgb0,rgb1,rgb2,rgb3 = 0;
707                         MT_Vector3      no0(mesh->mvert[mface->v1].no[0], mesh->mvert[mface->v1].no[1], mesh->mvert[mface->v1].no[2]),
708                                         no1(mesh->mvert[mface->v2].no[0], mesh->mvert[mface->v2].no[1], mesh->mvert[mface->v2].no[2]),
709                                         no2(mesh->mvert[mface->v3].no[0], mesh->mvert[mface->v3].no[1], mesh->mvert[mface->v3].no[2]),
710                                         no3(0.0, 0.0, 0.0);
711                         MT_Point3       pt0(mesh->mvert[mface->v1].co),
712                                         pt1(mesh->mvert[mface->v2].co),
713                                         pt2(mesh->mvert[mface->v3].co),
714                                         pt3(0.0, 0.0, 0.0);
715                         MT_Vector4      tan0(0.0, 0.0, 0.0, 0.0),
716                                         tan1(0.0, 0.0, 0.0, 0.0),
717                                         tan2(0.0, 0.0, 0.0, 0.0),
718                                         tan3(0.0, 0.0, 0.0, 0.0);
719
720                         no0 /= 32767.0;
721                         no1 /= 32767.0;
722                         no2 /= 32767.0;
723                         if (mface->v4)
724                         {
725                                 pt3 = MT_Point3(mesh->mvert[mface->v4].co);
726                                 no3 = MT_Vector3(mesh->mvert[mface->v4].no[0], mesh->mvert[mface->v4].no[1], mesh->mvert[mface->v4].no[2]);
727                                 no3 /= 32767.0;
728                         }
729         
730                         if(!(mface->flag & ME_SMOOTH))
731                         {
732                                 MT_Vector3 norm = ((pt1-pt0).cross(pt2-pt0)).safe_normalized();
733                                 norm[0] = ((int) (10*norm[0]))/10.0;
734                                 norm[1] = ((int) (10*norm[1]))/10.0;
735                                 norm[2] = ((int) (10*norm[2]))/10.0;
736                                 no0=no1=no2=no3= norm;
737         
738                         }
739                 
740                         {
741                                 Material* ma = 0;
742                                 bool polyvisible = true;
743                                 RAS_IPolyMaterial* polymat = NULL;
744
745                                 if(converter->GetMaterials()) 
746                                 {       
747                                         if(mesh->totcol > 1)
748                                                 ma = mesh->mat[mface->mat_nr];
749                                         else 
750                                                 ma = give_current_material(blenderobj, 1);
751
752                                         BL_Material *bl_mat = ConvertMaterial(mesh, ma, tface, mface, mmcol, lightlayer, blenderobj);
753                                         // set the index were dealing with
754                                         bl_mat->material_index =  (int)mface->mat_nr;
755
756                                         polyvisible = ((bl_mat->ras_mode & POLY_VIS)!=0);
757                                         collider = ((bl_mat->ras_mode & COLLIDER)!=0);
758                                         
759                                         polymat = new KX_BlenderMaterial(scene, bl_mat, skinMesh, lightlayer, blenderobj );
760                                         converter->RegisterBlenderMaterial(bl_mat);
761                                         
762                                         unsigned int rgb[4];
763                                         bl_mat->GetConversionRGB(rgb);
764                                         rgb0 = rgb[0];
765                                         rgb1 = rgb[1];
766                                         rgb2 = rgb[2];
767                                         rgb3 = rgb[3];
768                                         MT_Point2 uv[4];
769                                         bl_mat->GetConversionUV(uv);
770                                         uv0 = uv[0];
771                                         uv1 = uv[1];
772                                         uv2 = uv[2];
773                                         uv3 = uv[3];
774                                         if(tangent){
775                                                 tan0 = tangent[mface->v1];
776                                                 tan1 = tangent[mface->v2];
777                                                 tan2 = tangent[mface->v3];
778                                                 if (mface->v4)
779                                                         tan3 = tangent[mface->v4];
780                                         }
781                                         // this is needed to free up memory afterwards
782                                         converter->RegisterPolyMaterial(polymat);
783                                 }
784                                 else
785                                 {
786                                         ma = give_current_material(blenderobj, 1);
787
788                                         Image* bima = ((mesh->mtface && tface) ? (Image*) tface->tpage : NULL);
789                 
790                                         STR_String imastr = 
791                                                 ((mesh->mtface && tface) ? 
792                                                 (bima? (bima)->id.name : "" ) : "" );
793                         
794                                         char transp=0;
795                                         short mode=0, tile=0;
796                                         int     tilexrep=4,tileyrep = 4;
797                                         
798                                         if (bima)
799                                         {
800                                                 tilexrep = bima->xrep;
801                                                 tileyrep = bima->yrep;
802                                 
803                                         }
804
805                                         if (mesh->mtface && tface)
806                                         {
807                                                 // Use texface colors if available
808                                                 //TF_DYNAMIC means the polygon is a collision face
809                                                 collider = ((tface->mode & TF_DYNAMIC) != 0);
810                                                 transp = tface->transp;
811                                                 tile = tface->tile;
812                                                 mode = tface->mode;
813                                                 
814                                                 polyvisible = !((tface->flag & TF_HIDE)||(tface->mode & TF_INVISIBLE));
815                                                 
816                                                 uv0 = MT_Point2(tface->uv[0]);
817                                                 uv1 = MT_Point2(tface->uv[1]);
818                                                 uv2 = MT_Point2(tface->uv[2]);
819                 
820                                                 if (mface->v4)
821                                                         uv3 = MT_Point2(tface->uv[3]);
822                                         } 
823                                         if (mmcol)
824                                         {
825                                                 // Use vertex colours
826                                                 rgb0 = KX_Mcol2uint_new(mmcol[0]);
827                                                 rgb1 = KX_Mcol2uint_new(mmcol[1]);
828                                                 rgb2 = KX_Mcol2uint_new(mmcol[2]);
829                                                 
830                                                 if (mface->v4)
831                                                         rgb3 = KX_Mcol2uint_new(mmcol[3]);
832                                         }
833                                         else
834                                         {
835                                                 // If there are no vertex colors OR texfaces,
836                                                 // Initialize face to white and set COLLSION true and everything else FALSE
837                                                 unsigned int colour = 0xFFFFFFFFL;
838                                                 mode = default_face_mode;       
839                                                 transp = TF_SOLID;
840                                                 tile = 0;
841                                                 if (ma)
842                                                 {
843                                                         // If we have a material, take the default colour from the material.
844                                                         union
845                                                         {
846                                                                 unsigned char cp[4];
847                                                                 unsigned int integer;
848                                                         } col_converter;
849                                                         
850                                                         col_converter.cp[3] = (unsigned char) (ma->r*255.0);
851                                                         col_converter.cp[2] = (unsigned char) (ma->g*255.0);
852                                                         col_converter.cp[1] = (unsigned char) (ma->b*255.0);
853                                                         col_converter.cp[0] = (unsigned char) (ma->alpha*255.0);
854                                                         
855                                                         colour = col_converter.integer;
856                                                 }
857                                                 
858                                                 rgb0 = KX_rgbaint2uint_new(colour);
859                                                 rgb1 = KX_rgbaint2uint_new(colour);
860                                                 rgb2 = KX_rgbaint2uint_new(colour);     
861                                                 
862                                                 if (mface->v4)
863                                                         rgb3 = KX_rgbaint2uint_new(colour);
864                                         }
865                                         
866                                         bool istriangle = (mface->v4==0);
867                                         bool zsort = ma?(ma->mode & MA_ZTRA) != 0:false;
868                                         
869                                         polymat = new KX_PolygonMaterial(imastr, ma,
870                                                 tile, tilexrep, tileyrep, 
871                                                 mode, transp, zsort, lightlayer, istriangle, blenderobj, tface, (unsigned int*)mmcol);
872                 
873                                         if (ma)
874                                         {
875                                                 polymat->m_specular = MT_Vector3(ma->specr, ma->specg, ma->specb)*ma->spec;
876                                                 polymat->m_shininess = (float)ma->har/4.0; // 0 < ma->har <= 512
877                                                 polymat->m_diffuse = MT_Vector3(ma->r, ma->g, ma->b)*(ma->emit + ma->ref);
878
879                                         } else
880                                         {
881                                                 polymat->m_specular = MT_Vector3(0.0f,0.0f,0.0f);
882                                                 polymat->m_shininess = 35.0;
883                                         }
884                                         // this is needed to free up memory afterwards
885                                         converter->RegisterPolyMaterial(polymat);
886
887                                 }
888         
889                                 RAS_MaterialBucket* bucket = scene->FindBucket(polymat);
890                                                          
891                                 int nverts = mface->v4?4:3;
892                                 int vtxarray = meshobj->FindVertexArray(nverts,polymat);
893                                 RAS_Polygon* poly = new RAS_Polygon(bucket,polyvisible,nverts,vtxarray);
894                                 if (skinMesh) {
895                                         int d1, d2, d3, d4=0;
896                                         bool flat;
897
898                                         /* If the face is set to solid, all fnors are the same */
899                                         if (mface->flag & ME_SMOOTH)
900                                                 flat = false;
901                                         else
902                                                 flat = true;
903                                         
904                                         d1=((BL_SkinMeshObject*)meshobj)->FindOrAddDeform(vtxarray, mface->v1, &mesh->dvert[mface->v1], polymat);
905                                         d2=((BL_SkinMeshObject*)meshobj)->FindOrAddDeform(vtxarray, mface->v2, &mesh->dvert[mface->v2], polymat);
906                                         d3=((BL_SkinMeshObject*)meshobj)->FindOrAddDeform(vtxarray, mface->v3, &mesh->dvert[mface->v3], polymat);
907                                         if (nverts==4)
908                                                 d4=((BL_SkinMeshObject*)meshobj)->FindOrAddDeform(vtxarray, mface->v4, &mesh->dvert[mface->v4], polymat);
909                                         poly->SetVertex(0,((BL_SkinMeshObject*)meshobj)->FindOrAddVertex(vtxarray,pt0,uv0,tan0,rgb0,no0,d1,flat, polymat));
910                                         poly->SetVertex(1,((BL_SkinMeshObject*)meshobj)->FindOrAddVertex(vtxarray,pt1,uv1,tan1,rgb1,no1,d2,flat, polymat));
911                                         poly->SetVertex(2,((BL_SkinMeshObject*)meshobj)->FindOrAddVertex(vtxarray,pt2,uv2,tan2,rgb2,no2,d3,flat, polymat));
912                                         if (nverts==4)
913                                                 poly->SetVertex(3,((BL_SkinMeshObject*)meshobj)->FindOrAddVertex(vtxarray,pt3,uv3,tan3,rgb3,no3,d4, flat,polymat));
914                                 }
915                                 else
916                                 {
917                                         poly->SetVertex(0,meshobj->FindOrAddVertex(vtxarray,pt0,uv0,tan0,rgb0,no0,polymat,mface->v1));
918                                         poly->SetVertex(1,meshobj->FindOrAddVertex(vtxarray,pt1,uv1,tan1,rgb1,no1,polymat,mface->v2));
919                                         poly->SetVertex(2,meshobj->FindOrAddVertex(vtxarray,pt2,uv2,tan2,rgb2,no2,polymat,mface->v3));
920                                         if (nverts==4)
921                                                 poly->SetVertex(3,meshobj->FindOrAddVertex(vtxarray,pt3,uv3,tan3,rgb3,no3,polymat,mface->v4));
922                                 }
923                                 meshobj->AddPolygon(poly);
924                                 if (poly->IsCollider())
925                                 {
926                                         RAS_TriangleIndex idx;
927                                         idx.m_index[0] = mface->v1;
928                                         idx.m_index[1] = mface->v2;
929                                         idx.m_index[2] = mface->v3;
930                                         idx.m_collider = collider;
931                                         meshobj->m_triangle_indices.push_back(idx);
932                                         if (nverts==4)
933                                         {
934                                         idx.m_index[0] = mface->v1;
935                                         idx.m_index[1] = mface->v3;
936                                         idx.m_index[2] = mface->v4;
937                                         idx.m_collider = collider;
938                                         meshobj->m_triangle_indices.push_back(idx);
939                                         }
940                                 }
941                                 
942 //                              poly->SetVisibleWireframeEdges(mface->edcode);
943                                 poly->SetCollider(collider);
944                         }
945                 }
946                 if (tface) 
947                         tface++;
948                 if (mmcol)
949                         mmcol+=4;
950         }
951         meshobj->UpdateMaterialList();
952
953
954
955         // -----------------------------------
956         // pre calculate texture generation
957         for(RAS_MaterialBucket::Set::iterator mit = meshobj->GetFirstMaterial();
958                 mit != meshobj->GetLastMaterial(); ++ mit) {
959                 (*mit)->GetPolyMaterial()->OnConstruction();
960         }
961
962         if(tangent)
963                 delete [] tangent;
964
965
966         return meshobj;
967 }
968
969         
970         
971 static PHY_MaterialProps *CreateMaterialFromBlenderObject(struct Object* blenderobject,
972                                                                                                   KX_Scene *kxscene)
973 {
974         PHY_MaterialProps *materialProps = new PHY_MaterialProps;
975         
976         MT_assert(materialProps && "Create physics material properties failed");
977                 
978         Material* blendermat = give_current_material(blenderobject, 0);
979                 
980         if (blendermat)
981         {
982                 MT_assert(0.0f <= blendermat->reflect && blendermat->reflect <= 1.0f);
983         
984                 materialProps->m_restitution = blendermat->reflect;
985                 materialProps->m_friction = blendermat->friction;
986                 materialProps->m_fh_spring = blendermat->fh;
987                 materialProps->m_fh_damping = blendermat->xyfrict;
988                 materialProps->m_fh_distance = blendermat->fhdist;
989                 materialProps->m_fh_normal = (blendermat->dynamode & MA_FH_NOR) != 0;
990         }
991         else {
992                 //give some defaults
993                 materialProps->m_restitution = 0.f;
994                 materialProps->m_friction = 0.5;
995                 materialProps->m_fh_spring = 0.f;
996                 materialProps->m_fh_damping = 0.f;
997                 materialProps->m_fh_distance = 0.f;
998                 materialProps->m_fh_normal = false;
999
1000         }
1001         
1002         return materialProps;
1003 }
1004
1005 static PHY_ShapeProps *CreateShapePropsFromBlenderObject(struct Object* blenderobject,
1006                                                                                                  KX_Scene *kxscene)
1007 {
1008         PHY_ShapeProps *shapeProps = new PHY_ShapeProps;
1009         
1010         MT_assert(shapeProps);
1011                 
1012         shapeProps->m_mass = blenderobject->mass;
1013         
1014 //  This needs to be fixed in blender. For now, we use:
1015         
1016 // in Blender, inertia stands for the size value which is equivalent to
1017 // the sphere radius
1018         shapeProps->m_inertia = blenderobject->formfactor;
1019         
1020         MT_assert(0.0f <= blenderobject->damping && blenderobject->damping <= 1.0f);
1021         MT_assert(0.0f <= blenderobject->rdamping && blenderobject->rdamping <= 1.0f);
1022         
1023         shapeProps->m_lin_drag = 1.0 - blenderobject->damping;
1024         shapeProps->m_ang_drag = 1.0 - blenderobject->rdamping;
1025         
1026         shapeProps->m_friction_scaling[0] = blenderobject->anisotropicFriction[0]; 
1027         shapeProps->m_friction_scaling[1] = blenderobject->anisotropicFriction[1];
1028         shapeProps->m_friction_scaling[2] = blenderobject->anisotropicFriction[2];
1029         shapeProps->m_do_anisotropic = ((blenderobject->gameflag & OB_ANISOTROPIC_FRICTION) != 0);
1030         
1031         shapeProps->m_do_fh     = (blenderobject->gameflag & OB_DO_FH) != 0; 
1032         shapeProps->m_do_rot_fh = (blenderobject->gameflag & OB_ROT_FH) != 0;
1033         
1034         return shapeProps;
1035 }
1036
1037         
1038         
1039         
1040                 
1041 //////////////////////////////////////////////////////////
1042         
1043
1044
1045 static float my_boundbox_mesh(Mesh *me, float *loc, float *size)
1046 {
1047         MVert *mvert;
1048         BoundBox *bb;
1049         MT_Point3 min, max;
1050         float mloc[3], msize[3];
1051         int a;
1052         
1053         if(me->bb==0) me->bb= (struct BoundBox *)MEM_callocN(sizeof(BoundBox), "boundbox");
1054         bb= me->bb;
1055         
1056         INIT_MINMAX(min, max);
1057
1058         if (!loc) loc= mloc;
1059         if (!size) size= msize;
1060         
1061         mvert= me->mvert;
1062         for(a=0; a<me->totvert; a++, mvert++) {
1063                 DO_MINMAX(mvert->co, min, max);
1064         }
1065                 
1066         if(me->totvert) {
1067                 loc[0]= (min[0]+max[0])/2.0;
1068                 loc[1]= (min[1]+max[1])/2.0;
1069                 loc[2]= (min[2]+max[2])/2.0;
1070                 
1071                 size[0]= (max[0]-min[0])/2.0;
1072                 size[1]= (max[1]-min[1])/2.0;
1073                 size[2]= (max[2]-min[2])/2.0;
1074         }
1075         else {
1076                 loc[0]= loc[1]= loc[2]= 0.0;
1077                 size[0]= size[1]= size[2]= 0.0;
1078         }
1079                 
1080         bb->vec[0][0]=bb->vec[1][0]=bb->vec[2][0]=bb->vec[3][0]= loc[0]-size[0];
1081         bb->vec[4][0]=bb->vec[5][0]=bb->vec[6][0]=bb->vec[7][0]= loc[0]+size[0];
1082                 
1083         bb->vec[0][1]=bb->vec[1][1]=bb->vec[4][1]=bb->vec[5][1]= loc[1]-size[1];
1084         bb->vec[2][1]=bb->vec[3][1]=bb->vec[6][1]=bb->vec[7][1]= loc[1]+size[1];
1085
1086         bb->vec[0][2]=bb->vec[3][2]=bb->vec[4][2]=bb->vec[7][2]= loc[2]-size[2];
1087         bb->vec[1][2]=bb->vec[2][2]=bb->vec[5][2]=bb->vec[6][2]= loc[2]+size[2];
1088
1089         float radius = 0;
1090         for (a=0, mvert = me->mvert; a < me->totvert; a++, mvert++)
1091         {
1092                 float vert_radius = MT_Vector3(mvert->co).length2();
1093                 if (vert_radius > radius)
1094                         radius = vert_radius;
1095         } 
1096         return sqrt(radius);
1097 }
1098                 
1099
1100
1101
1102 static void my_tex_space_mesh(Mesh *me)
1103                 {
1104         KeyBlock *kb;
1105         float *fp, loc[3], size[3], min[3], max[3];
1106         int a;
1107
1108         my_boundbox_mesh(me, loc, size);
1109         
1110         if(me->texflag & AUTOSPACE) {
1111                 if(me->key) {
1112                         kb= me->key->refkey;
1113                         if (kb) {
1114         
1115                                 INIT_MINMAX(min, max);
1116                 
1117                                 fp= (float *)kb->data;
1118                                 for(a=0; a<kb->totelem; a++, fp+=3) {   
1119                                         DO_MINMAX(fp, min, max);
1120                                 }
1121                                 if(kb->totelem) {
1122                                         loc[0]= (min[0]+max[0])/2.0; loc[1]= (min[1]+max[1])/2.0; loc[2]= (min[2]+max[2])/2.0;
1123                                         size[0]= (max[0]-min[0])/2.0; size[1]= (max[1]-min[1])/2.0; size[2]= (max[2]-min[2])/2.0;
1124         } 
1125         else {
1126                                         loc[0]= loc[1]= loc[2]= 0.0;
1127                                         size[0]= size[1]= size[2]= 0.0;
1128                                 }
1129                                 
1130                         }
1131                                 }
1132         
1133                 VECCOPY(me->loc, loc);
1134                 VECCOPY(me->size, size);
1135                 me->rot[0]= me->rot[1]= me->rot[2]= 0.0;
1136         
1137                 if(me->size[0]==0.0) me->size[0]= 1.0;
1138                 else if(me->size[0]>0.0 && me->size[0]<0.00001) me->size[0]= 0.00001;
1139                 else if(me->size[0]<0.0 && me->size[0]> -0.00001) me->size[0]= -0.00001;
1140         
1141                 if(me->size[1]==0.0) me->size[1]= 1.0;
1142                 else if(me->size[1]>0.0 && me->size[1]<0.00001) me->size[1]= 0.00001;
1143                 else if(me->size[1]<0.0 && me->size[1]> -0.00001) me->size[1]= -0.00001;
1144                                                 
1145                 if(me->size[2]==0.0) me->size[2]= 1.0;
1146                 else if(me->size[2]>0.0 && me->size[2]<0.00001) me->size[2]= 0.00001;
1147                 else if(me->size[2]<0.0 && me->size[2]> -0.00001) me->size[2]= -0.00001;
1148         }
1149         
1150 }
1151
1152 static void my_get_local_bounds(Object *ob, float *centre, float *size)
1153 {
1154         BoundBox *bb= NULL;
1155         /* uses boundbox, function used by Ketsji */
1156         switch (ob->type)
1157         {
1158                 case OB_MESH:
1159                         bb= ( (Mesh *)ob->data )->bb;
1160                         if(bb==0) 
1161                         {
1162                                 my_tex_space_mesh((struct Mesh *)ob->data);
1163                                 bb= ( (Mesh *)ob->data )->bb;
1164                         }
1165                         break;
1166                 case OB_CURVE:
1167                 case OB_SURF:
1168                 case OB_FONT:
1169                         centre[0]= centre[1]= centre[2]= 0.0;
1170                         size[0]  = size[1]=size[2]=0.0;
1171                         break;
1172                 case OB_MBALL:
1173                         bb= ob->bb;
1174                         break;
1175         }
1176         
1177         if(bb==NULL) 
1178         {
1179                 centre[0]= centre[1]= centre[2]= 0.0;
1180                 size[0] = size[1]=size[2]=1.0;
1181         }
1182         else 
1183         {
1184                 size[0]= 0.5*fabs(bb->vec[0][0] - bb->vec[4][0]);
1185                 size[1]= 0.5*fabs(bb->vec[0][1] - bb->vec[2][1]);
1186                 size[2]= 0.5*fabs(bb->vec[0][2] - bb->vec[1][2]);
1187                                         
1188                 centre[0]= 0.5*(bb->vec[0][0] + bb->vec[4][0]);
1189                 centre[1]= 0.5*(bb->vec[0][1] + bb->vec[2][1]);
1190                 centre[2]= 0.5*(bb->vec[0][2] + bb->vec[1][2]);
1191         }
1192 }
1193         
1194
1195
1196
1197 //////////////////////////////////////////////////////
1198
1199
1200
1201
1202
1203 void BL_CreatePhysicsObjectNew(KX_GameObject* gameobj,
1204                                                  struct Object* blenderobject,
1205                                                  RAS_MeshObject* meshobj,
1206                                                  KX_Scene* kxscene,
1207                                                  int activeLayerBitInfo,
1208                                                  e_PhysicsEngine        physics_engine,
1209                                                  KX_BlenderSceneConverter *converter
1210                                                  )
1211                                         
1212 {
1213         //SYS_SystemHandle syshandle = SYS_GetSystem(); /*unused*/
1214         //int userigidbody = SYS_GetCommandLineInt(syshandle,"norigidbody",0);
1215         //bool bRigidBody = (userigidbody == 0);
1216
1217         PHY_ShapeProps* shapeprops =
1218                         CreateShapePropsFromBlenderObject(blenderobject, 
1219                         kxscene);
1220
1221         
1222         PHY_MaterialProps* smmaterial = 
1223                 CreateMaterialFromBlenderObject(blenderobject, kxscene);
1224                                         
1225         KX_ObjectProperties objprop;
1226         if ((objprop.m_isactor = (blenderobject->gameflag & OB_ACTOR)!=0))
1227         {
1228                 objprop.m_dyna = (blenderobject->gameflag & OB_DYNAMIC) != 0;
1229                 objprop.m_angular_rigidbody = (blenderobject->gameflag & OB_RIGID_BODY) != 0;
1230                 objprop.m_ghost = (blenderobject->gameflag & OB_GHOST) != 0;
1231                 objprop.m_disableSleeping = (blenderobject->gameflag & OB_COLLISION_RESPONSE) != 0;//abuse the OB_COLLISION_RESPONSE flag
1232         } else {
1233                 objprop.m_dyna = false;
1234                 objprop.m_angular_rigidbody = false;
1235                 objprop.m_ghost = false;
1236                 objprop.m_disableSleeping = false;
1237         }
1238         //mmm, for now, taks this for the size of the dynamicobject
1239         // Blender uses inertia for radius of dynamic object
1240         objprop.m_radius = blenderobject->inertia;
1241         objprop.m_in_active_layer = (blenderobject->lay & activeLayerBitInfo) != 0;
1242         objprop.m_dynamic_parent=NULL;
1243         objprop.m_isdeformable = ((blenderobject->gameflag2 & 2)) != 0;
1244         objprop.m_boundclass = objprop.m_dyna?KX_BOUNDSPHERE:KX_BOUNDMESH;
1245         
1246         KX_BoxBounds bb;
1247         my_get_local_bounds(blenderobject,objprop.m_boundobject.box.m_center,bb.m_extends);
1248         if (blenderobject->gameflag & OB_BOUNDS)
1249         {
1250                 switch (blenderobject->boundtype)
1251                 {
1252                         case OB_BOUND_BOX:
1253                                 objprop.m_boundclass = KX_BOUNDBOX;
1254                                 //mmm, has to be divided by 2 to be proper extends
1255                                 objprop.m_boundobject.box.m_extends[0]=2.f*bb.m_extends[0];
1256                                 objprop.m_boundobject.box.m_extends[1]=2.f*bb.m_extends[1];
1257                                 objprop.m_boundobject.box.m_extends[2]=2.f*bb.m_extends[2];
1258                                 break;
1259                         case OB_BOUND_POLYT:
1260                                 if (blenderobject->type == OB_MESH)
1261                                 {
1262                                         objprop.m_boundclass = KX_BOUNDPOLYTOPE;
1263                                         break;
1264                                 }
1265                                 // Object is not a mesh... fall through OB_BOUND_POLYH to 
1266                                 // OB_BOUND_SPHERE
1267                         case OB_BOUND_POLYH:
1268                                 if (blenderobject->type == OB_MESH)
1269                                 {
1270                                         objprop.m_boundclass = KX_BOUNDMESH;
1271                                         break;
1272                                 }
1273                                 // Object is not a mesh... can't use polyheder. 
1274                                 // Fall through and become a sphere.
1275                         case OB_BOUND_SPHERE:
1276                         {
1277                                 objprop.m_boundclass = KX_BOUNDSPHERE;
1278                                 objprop.m_boundobject.c.m_radius = MT_max(bb.m_extends[0], MT_max(bb.m_extends[1], bb.m_extends[2]));
1279                                 break;
1280                         }
1281                         case OB_BOUND_CYLINDER:
1282                         {
1283                                 objprop.m_boundclass = KX_BOUNDCYLINDER;
1284                                 objprop.m_boundobject.c.m_radius = MT_max(bb.m_extends[0], bb.m_extends[1]);
1285                                 objprop.m_boundobject.c.m_height = 2.f*bb.m_extends[2];
1286                                 break;
1287                         }
1288                         case OB_BOUND_CONE:
1289                         {
1290                                 objprop.m_boundclass = KX_BOUNDCONE;
1291                                 objprop.m_boundobject.c.m_radius = MT_max(bb.m_extends[0], bb.m_extends[1]);
1292                                 objprop.m_boundobject.c.m_height = 2.f*bb.m_extends[2];
1293                                 break;
1294                         }
1295                 }
1296         }
1297
1298         // get Root Parent of blenderobject
1299         struct Object* parent= blenderobject->parent;
1300         while(parent && parent->parent) {
1301                 parent= parent->parent;
1302         }
1303
1304         if (parent && (parent->gameflag & OB_DYNAMIC)) {
1305                 
1306                 KX_GameObject *parentgameobject = converter->FindGameObject(parent);
1307                 objprop.m_dynamic_parent = parentgameobject;
1308
1309         }
1310
1311         objprop.m_concave = (blenderobject->boundtype & 4) != 0;
1312         
1313         switch (physics_engine)
1314         {
1315 #ifdef USE_BULLET
1316                 case UseBullet:
1317                         KX_ConvertBulletObject(gameobj, meshobj, kxscene, shapeprops, smmaterial, &objprop);
1318                         break;
1319
1320 #endif
1321 #ifdef USE_SUMO_SOLID
1322                 case UseSumo:
1323                         KX_ConvertSumoObject(gameobj, meshobj, kxscene, shapeprops, smmaterial, &objprop);
1324                         break;
1325 #endif
1326                         
1327 #ifdef USE_ODE
1328                 case UseODE:
1329                         KX_ConvertODEEngineObject(gameobj, meshobj, kxscene, shapeprops, smmaterial, &objprop);
1330                         break;
1331 #endif //USE_ODE
1332
1333                 case UseDynamo:
1334                         //KX_ConvertDynamoObject(gameobj,meshobj,kxscene,shapeprops,    smmaterial,     &objprop);
1335                         break;
1336                         
1337                 case UseNone:
1338                 default:
1339                         break;
1340         }
1341
1342 }
1343
1344
1345
1346
1347
1348 static KX_LightObject *gamelight_from_blamp(Lamp *la, unsigned int layerflag, KX_Scene *kxscene, RAS_IRenderTools *rendertools, KX_BlenderSceneConverter *converter) {
1349         RAS_LightObject lightobj;
1350         KX_LightObject *gamelight;
1351         
1352         lightobj.m_att1 = la->att1;
1353         lightobj.m_att2 = (la->mode & LA_QUAD)?la->att2:0.0;
1354         lightobj.m_red = la->r;
1355         lightobj.m_green = la->g;
1356         lightobj.m_blue = la->b;
1357         lightobj.m_distance = la->dist;
1358         lightobj.m_energy = la->energy;
1359         lightobj.m_layer = layerflag;
1360         lightobj.m_spotblend = la->spotblend;
1361         lightobj.m_spotsize = la->spotsize;
1362         
1363         lightobj.m_nodiffuse = (la->mode & LA_NO_DIFF) != 0;
1364         lightobj.m_nospecular = (la->mode & LA_NO_SPEC) != 0;
1365         
1366         if (la->mode & LA_NEG)
1367         {
1368                 lightobj.m_red = -lightobj.m_red;
1369                 lightobj.m_green = -lightobj.m_green;
1370                 lightobj.m_blue = -lightobj.m_blue;
1371         }
1372                 
1373         if (la->type==LA_SUN) {
1374                 lightobj.m_type = RAS_LightObject::LIGHT_SUN;
1375         } else if (la->type==LA_SPOT) {
1376                 lightobj.m_type = RAS_LightObject::LIGHT_SPOT;
1377         } else {
1378                 lightobj.m_type = RAS_LightObject::LIGHT_NORMAL;
1379         }
1380         
1381         gamelight = new KX_LightObject(kxscene, KX_Scene::m_callbacks, rendertools, lightobj);
1382         BL_ConvertLampIpos(la, gamelight, converter);
1383         
1384         return gamelight;
1385 }
1386
1387 static KX_Camera *gamecamera_from_bcamera(Camera *ca, KX_Scene *kxscene, KX_BlenderSceneConverter *converter) {
1388         RAS_CameraData camdata(ca->lens, ca->clipsta, ca->clipend, ca->type == CAM_PERSP);
1389         KX_Camera *gamecamera;
1390         
1391         gamecamera= new KX_Camera(kxscene, KX_Scene::m_callbacks, camdata);
1392         gamecamera->SetName(ca->id.name + 2);
1393         
1394         BL_ConvertCameraIpos(ca, gamecamera, converter);
1395         
1396         return gamecamera;
1397 }
1398
1399 static KX_GameObject *gameobject_from_blenderobject(
1400                                                                 Object *ob, 
1401                                                                 KX_Scene *kxscene, 
1402                                                                 RAS_IRenderTools *rendertools, 
1403                                                                 KX_BlenderSceneConverter *converter,
1404                                                                 Scene *blenderscene) 
1405 {
1406         KX_GameObject *gameobj = NULL;
1407         
1408         switch(ob->type)
1409         {
1410         case OB_LAMP:
1411         {
1412                 KX_LightObject* gamelight= gamelight_from_blamp(static_cast<Lamp*>(ob->data), ob->lay, kxscene, rendertools, converter);
1413                 gameobj = gamelight;
1414                 
1415                 gamelight->AddRef();
1416                 kxscene->GetLightList()->Add(gamelight);
1417                 
1418                 break;
1419         }
1420         
1421         case OB_CAMERA:
1422         {
1423                 KX_Camera* gamecamera = gamecamera_from_bcamera(static_cast<Camera*>(ob->data), kxscene, converter);
1424                 gameobj = gamecamera;
1425                 
1426                 gamecamera->AddRef();
1427                 kxscene->AddCamera(gamecamera);
1428                 
1429                 break;
1430         }
1431         
1432         case OB_MESH:
1433         {
1434                 Mesh* mesh = static_cast<Mesh*>(ob->data);
1435                 RAS_MeshObject* meshobj = converter->FindGameMesh(mesh, ob->lay);
1436                 float centre[3], extents[3];
1437                 float radius = my_boundbox_mesh((Mesh*) ob->data, centre, extents);
1438                 
1439                 if (!meshobj) {
1440                         meshobj = BL_ConvertMesh(mesh,ob,rendertools,kxscene,converter);
1441                         converter->RegisterGameMesh(meshobj, mesh);
1442                 }
1443                 
1444                 // needed for python scripting
1445                 kxscene->GetLogicManager()->RegisterMeshName(meshobj->GetName(),meshobj);
1446         
1447                 gameobj = new BL_DeformableGameObject(kxscene,KX_Scene::m_callbacks);
1448         
1449                 // set transformation
1450                 gameobj->AddMesh(meshobj);
1451         
1452                 // for all objects: check whether they want to
1453                 // respond to updates
1454                 bool ignoreActivityCulling =  
1455                         ((ob->gameflag2 & OB_NEVER_DO_ACTIVITY_CULLING)!=0);
1456                 gameobj->SetIgnoreActivityCulling(ignoreActivityCulling);
1457         
1458                 //      If this is a skin object, make Skin Controller
1459                 if (ob->parent && ob->parent->type == OB_ARMATURE && ob->partype==PARSKEL && ((Mesh*)ob->data)->dvert){
1460                         BL_SkinDeformer *dcont = new BL_SkinDeformer(ob, (BL_SkinMeshObject*)meshobj );                         
1461                         ((BL_DeformableGameObject*)gameobj)->m_pDeformer = dcont;
1462                 }
1463                 else if (((Mesh*)ob->data)->dvert){
1464                         BL_MeshDeformer *dcont = new BL_MeshDeformer(ob, (BL_SkinMeshObject*)meshobj );
1465                         ((BL_DeformableGameObject*)gameobj)->m_pDeformer = dcont;
1466                 }
1467                 
1468                 MT_Point3 min = MT_Point3(centre) - MT_Vector3(extents);
1469                 MT_Point3 max = MT_Point3(centre) + MT_Vector3(extents);
1470                 SG_BBox bbox = SG_BBox(min, max);
1471                 gameobj->GetSGNode()->SetBBox(bbox);
1472                 gameobj->GetSGNode()->SetRadius(radius);
1473         
1474                 break;
1475         }
1476         
1477         case OB_ARMATURE:
1478         {
1479                 gameobj = new BL_ArmatureObject(
1480                         kxscene,
1481                         KX_Scene::m_callbacks,
1482                         ob // handle
1483                 );
1484                 /* Get the current pose from the armature object and apply it as the rest pose */
1485                 break;
1486         }
1487         
1488         case OB_EMPTY:
1489         {
1490                 gameobj = new KX_EmptyObject(kxscene,KX_Scene::m_callbacks);
1491                 // set transformation
1492                 break;
1493         }
1494         }
1495         
1496         return gameobj;
1497 }
1498
1499 struct parentChildLink {
1500         struct Object* m_blenderchild;
1501         SG_Node* m_gamechildnode;
1502 };
1503
1504         /**
1505          * Find the specified scene by name, or the first
1506          * scene if nothing matches (shouldn't happen).
1507          */
1508 static struct Scene *GetSceneForName(struct Main *maggie, const STR_String& scenename) {
1509         Scene *sce;
1510
1511         for (sce= (Scene*) maggie->scene.first; sce; sce= (Scene*) sce->id.next)
1512                 if (scenename == (sce->id.name+2))
1513                         return sce;
1514
1515         return (Scene*) maggie->scene.first;
1516 }
1517
1518 #include "DNA_constraint_types.h"
1519 #include "BIF_editconstraint.h"
1520
1521 bPoseChannel *get_active_posechannel2 (Object *ob)
1522 {
1523         bArmature *arm= (bArmature*)ob->data;
1524         bPoseChannel *pchan;
1525         
1526         /* find active */
1527         for(pchan= (bPoseChannel *)ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1528                 if(pchan->bone && (pchan->bone->flag & BONE_ACTIVE) && (pchan->bone->layer & arm->layer))
1529                         return pchan;
1530         }
1531         
1532         return NULL;
1533 }
1534
1535 ListBase *get_active_constraints2(Object *ob)
1536 {
1537         if (!ob)
1538                 return NULL;
1539
1540         if (ob->flag & OB_POSEMODE) {
1541                 bPoseChannel *pchan;
1542
1543                 pchan = get_active_posechannel2(ob);
1544                 if (pchan)
1545                         return &pchan->constraints;
1546         }
1547         else 
1548                 return &ob->constraints;
1549
1550         return NULL;
1551 }
1552
1553
1554 void RBJconstraints(Object *ob)//not used
1555 {
1556         ListBase *conlist;
1557         bConstraint *curcon;
1558
1559         conlist = get_active_constraints2(ob);
1560
1561         if (conlist) {
1562                 for (curcon = (bConstraint *)conlist->first; curcon; curcon=(bConstraint *)curcon->next) {
1563
1564                         printf("%i\n",curcon->type);
1565                 }
1566
1567
1568         }
1569 }
1570
1571 #include "PHY_IPhysicsEnvironment.h"
1572 #include "KX_IPhysicsController.h"
1573 #include "PHY_DynamicTypes.h"
1574
1575 KX_IPhysicsController* getPhId(CListValue* sumolist,STR_String busc){//not used
1576
1577     for (int j=0;j<sumolist->GetCount();j++)
1578         {
1579             KX_GameObject* gameobje = (KX_GameObject*) sumolist->GetValue(j);
1580             if (gameobje->GetName()==busc)
1581             return gameobje->GetPhysicsController();
1582         }
1583
1584 }
1585
1586 KX_GameObject* getGameOb(STR_String busc,CListValue* sumolist){
1587
1588     for (int j=0;j<sumolist->GetCount();j++)
1589         {
1590             KX_GameObject* gameobje = (KX_GameObject*) sumolist->GetValue(j);
1591             if (gameobje->GetName()==busc)
1592             return gameobje;
1593         }
1594
1595 }
1596
1597 // convert blender objects into ketsji gameobjects
1598 void BL_ConvertBlenderObjects(struct Main* maggie,
1599                                                           const STR_String& scenename,
1600                                                           KX_Scene* kxscene,
1601                                                           KX_KetsjiEngine* ketsjiEngine,
1602                                                           e_PhysicsEngine       physics_engine,
1603                                                           PyObject* pythondictionary,
1604                                                           SCA_IInputDevice* keydev,
1605                                                           RAS_IRenderTools* rendertools,
1606                                                           RAS_ICanvas* canvas,
1607                                                           KX_BlenderSceneConverter* converter,
1608                                                           bool alwaysUseExpandFraming
1609                                                           )
1610 {       
1611
1612         Scene *blenderscene = GetSceneForName(maggie, scenename);
1613
1614         // Get the frame settings of the canvas.
1615         // Get the aspect ratio of the canvas as designed by the user.
1616
1617         RAS_FrameSettings::RAS_FrameType frame_type;
1618         int aspect_width;
1619         int aspect_height;
1620         
1621         if (alwaysUseExpandFraming) {
1622                 frame_type = RAS_FrameSettings::e_frame_extend;
1623                 aspect_width = canvas->GetWidth();
1624                 aspect_height = canvas->GetHeight();
1625         } else {
1626                 if (blenderscene->framing.type == SCE_GAMEFRAMING_BARS) {
1627                         frame_type = RAS_FrameSettings::e_frame_bars;
1628                 } else if (blenderscene->framing.type == SCE_GAMEFRAMING_EXTEND) {
1629                         frame_type = RAS_FrameSettings::e_frame_extend;
1630                 } else {
1631                         frame_type = RAS_FrameSettings::e_frame_scale;
1632                 }
1633                 
1634                 aspect_width = blenderscene->r.xsch;
1635                 aspect_height = blenderscene->r.ysch;
1636         }
1637         
1638         RAS_FrameSettings frame_settings(
1639                 frame_type,
1640                 blenderscene->framing.col[0],
1641                 blenderscene->framing.col[1],
1642                 blenderscene->framing.col[2],
1643                 aspect_width,
1644                 aspect_height
1645         );
1646         kxscene->SetFramingType(frame_settings);
1647
1648         kxscene->SetGravity(MT_Vector3(0,0,(blenderscene->world != NULL) ? -blenderscene->world->gravity : -9.8));
1649         
1650         /* set activity culling parameters */
1651         if (blenderscene->world) {
1652                 kxscene->SetActivityCulling( (blenderscene->world->mode & WO_ACTIVITY_CULLING) != 0);
1653                 kxscene->SetActivityCullingRadius(blenderscene->world->activityBoxRadius);
1654         } else {
1655                 kxscene->SetActivityCulling(false);
1656         }
1657         
1658         int activeLayerBitInfo = blenderscene->lay;
1659         
1660         // templist to find Root Parents (object with no parents)
1661         CListValue* templist = new CListValue();
1662         CListValue*     sumolist = new CListValue();
1663         
1664         vector<parentChildLink> vec_parent_child;
1665         
1666         CListValue* objectlist = kxscene->GetObjectList();
1667         CListValue* parentlist = kxscene->GetRootParentList();
1668         
1669         SCA_LogicManager* logicmgr = kxscene->GetLogicManager();
1670         SCA_TimeEventManager* timemgr = kxscene->GetTimeEventManager();
1671         
1672         CListValue* logicbrick_conversionlist = new CListValue();
1673         
1674         SG_TreeFactory tf;
1675         
1676         // Convert actions to actionmap
1677         bAction *curAct;
1678         for (curAct = (bAction*)maggie->action.first; curAct; curAct=(bAction*)curAct->id.next)
1679         {
1680                 logicmgr->RegisterActionName(curAct->id.name, curAct);
1681         }
1682
1683         SetDefaultFaceType(blenderscene);
1684         
1685         Base *base = static_cast<Base*>(blenderscene->base.first);
1686         while(base)
1687         {
1688                 Object* blenderobject = base->object;
1689                 KX_GameObject* gameobj = gameobject_from_blenderobject(
1690                                                                                 base->object, 
1691                                                                                 kxscene, 
1692                                                                                 rendertools, 
1693                                                                                 converter,
1694                                                                                 blenderscene);
1695                                                                                         
1696                 if (gameobj)
1697                 {
1698                         MT_Point3 pos = MT_Point3(
1699                                 blenderobject->loc[0]+blenderobject->dloc[0],
1700                                 blenderobject->loc[1]+blenderobject->dloc[1],
1701                                 blenderobject->loc[2]+blenderobject->dloc[2]
1702                         );
1703                         MT_Vector3 eulxyz = MT_Vector3(
1704                                 blenderobject->rot[0],
1705                                 blenderobject->rot[1],
1706                                 blenderobject->rot[2]
1707                         );
1708                         MT_Vector3 scale = MT_Vector3(
1709                                 blenderobject->size[0],
1710                                 blenderobject->size[1],
1711                                 blenderobject->size[2]
1712                         );
1713                         
1714                         gameobj->NodeSetLocalPosition(pos);
1715                         gameobj->NodeSetLocalOrientation(MT_Matrix3x3(eulxyz));
1716                         gameobj->NodeSetLocalScale(scale);
1717                         gameobj->NodeUpdateGS(0,true);
1718                         
1719                         BL_ConvertIpos(blenderobject,gameobj,converter);
1720                         // TODO: expand to multiple ipos per mesh
1721                         Material *mat = give_current_material(blenderobject, 1);
1722                         if(mat) BL_ConvertMaterialIpos(mat, gameobj, converter);        
1723         
1724                         bool isInActiveLayer = (blenderobject->lay & activeLayerBitInfo) !=0;
1725         
1726                         sumolist->Add(gameobj->AddRef());
1727                         
1728                         BL_ConvertProperties(blenderobject,gameobj,timemgr,kxscene,isInActiveLayer);
1729                         
1730         
1731                         gameobj->SetName(blenderobject->id.name);
1732         
1733                         // templist to find Root Parents (object with no parents)
1734                         templist->Add(gameobj->AddRef());
1735                         
1736                         // update children/parent hierarchy
1737                         if (blenderobject->parent != 0)
1738                         {
1739                                 // blender has an additional 'parentinverse' offset in each object
1740                                 SG_Node* parentinversenode = new SG_Node(NULL,NULL,SG_Callbacks());
1741                         
1742                                 // define a normal parent relationship for this node.
1743                                 KX_NormalParentRelation * parent_relation = KX_NormalParentRelation::New();
1744                                 parentinversenode->SetParentRelation(parent_relation);
1745         
1746                                 parentChildLink pclink;
1747                                 pclink.m_blenderchild = blenderobject;
1748                                 pclink.m_gamechildnode = parentinversenode;
1749                                 vec_parent_child.push_back(pclink);
1750
1751                                 float* fl = (float*) blenderobject->parentinv;
1752                                 MT_Transform parinvtrans(fl);
1753                                 parentinversenode->SetLocalPosition(parinvtrans.getOrigin());
1754                                 parentinversenode->SetLocalOrientation(parinvtrans.getBasis());
1755                                 
1756                                 parentinversenode->AddChild(gameobj->GetSGNode());
1757                         }
1758                         
1759                         // needed for python scripting
1760                         logicmgr->RegisterGameObjectName(gameobj->GetName(),gameobj);
1761
1762                         // needed for dynamic object morphing
1763                         logicmgr->RegisterGameObj(gameobj, blenderobject);
1764                         for (int i = 0; i < gameobj->GetMeshCount(); i++)
1765                                 logicmgr->RegisterGameMeshName(gameobj->GetMesh(i)->GetName(), blenderobject);
1766         
1767                         converter->RegisterGameObject(gameobj, blenderobject);  
1768                         
1769                         // this was put in rapidly, needs to be looked at more closely
1770                         // only draw/use objects in active 'blender' layers
1771         
1772                         logicbrick_conversionlist->Add(gameobj->AddRef());
1773                         
1774                         if (isInActiveLayer)
1775                         {
1776                                 objectlist->Add(gameobj->AddRef());
1777                                 tf.Add(gameobj->GetSGNode());
1778                                 
1779                                 gameobj->NodeUpdateGS(0,true);
1780                                 gameobj->Bucketize();
1781                                 
1782                         }
1783                         
1784                 }
1785                         
1786                 base = base->next;
1787         }
1788
1789         if (blenderscene->camera) {
1790                 KX_Camera *gamecamera= (KX_Camera*) converter->FindGameObject(blenderscene->camera);
1791                 
1792                 kxscene->SetActiveCamera(gamecamera);
1793         }
1794
1795         //      Set up armatures
1796         for (base = static_cast<Base*>(blenderscene->base.first); base; base=base->next){
1797                 if (base->object->type==OB_MESH){
1798                         Mesh *me = (Mesh*)base->object->data;
1799         
1800                         if (me->dvert){
1801                                 KX_GameObject *obj = converter->FindGameObject(base->object);
1802         
1803                                 if (base->object->parent && base->object->parent->type==OB_ARMATURE && base->object->partype==PARSKEL){
1804                                         KX_GameObject *par = converter->FindGameObject(base->object->parent);
1805                                         if (par)
1806                                                 ((BL_SkinDeformer*)(((BL_DeformableGameObject*)obj)->m_pDeformer))->SetArmature((BL_ArmatureObject*) par);
1807                                 }
1808                         }
1809                 }
1810         }
1811         
1812         // create hierarchy information
1813         int i;
1814         vector<parentChildLink>::iterator pcit;
1815         
1816         for (pcit = vec_parent_child.begin();!(pcit==vec_parent_child.end());++pcit)
1817         {
1818         
1819                 struct Object* blenderchild = pcit->m_blenderchild;
1820                 switch (blenderchild->partype)
1821                 {
1822                         case PARVERT1:
1823                         {
1824                                 // creat a new vertex parent relationship for this node.
1825                                 KX_VertexParentRelation * vertex_parent_relation = KX_VertexParentRelation::New();
1826                                 pcit->m_gamechildnode->SetParentRelation(vertex_parent_relation);
1827                                 break;
1828                         }
1829                         case PARSLOW:
1830                         {
1831                                 // creat a new slow parent relationship for this node.
1832                                 KX_SlowParentRelation * slow_parent_relation = KX_SlowParentRelation::New(blenderchild->sf);
1833                                 pcit->m_gamechildnode->SetParentRelation(slow_parent_relation);
1834                                 break;
1835                         }       
1836                         case PARBONE:
1837                         {
1838                                 // parent this to a bone
1839                                 Bone *parent_bone = get_named_bone(get_armature(blenderchild->parent), blenderchild->parsubstr);
1840                                 KX_BoneParentRelation *bone_parent_relation = KX_BoneParentRelation::New(parent_bone);
1841                                 pcit->m_gamechildnode->SetParentRelation(bone_parent_relation);
1842                         
1843                                 break;
1844                         }
1845                         case PARSKEL: // skinned - ignore
1846                                 break;
1847                         case PAROBJECT:
1848                         case PARCURVE:
1849                         case PARKEY:
1850                         case PARVERT3:
1851                         default:
1852                                 // unhandled
1853                                 break;
1854                 }
1855         
1856                 struct Object* blenderparent = blenderchild->parent;
1857                 KX_GameObject* parentobj = converter->FindGameObject(blenderparent);
1858                 if (parentobj)
1859                 {
1860                         parentobj->     GetSGNode()->AddChild(pcit->m_gamechildnode);
1861                 }
1862         }
1863         vec_parent_child.clear();
1864         
1865         // find 'root' parents (object that has not parents in SceneGraph)
1866         for (i=0;i<templist->GetCount();++i)
1867         {
1868                 KX_GameObject* gameobj = (KX_GameObject*) templist->GetValue(i);
1869                 if (gameobj->GetSGNode()->GetSGParent() == 0)
1870                 {
1871                         parentlist->Add(gameobj->AddRef());
1872                         gameobj->NodeUpdateGS(0,true);
1873                 }
1874         }
1875         
1876         // create physics information
1877         for (i=0;i<sumolist->GetCount();i++)
1878         {
1879                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
1880                 struct Object* blenderobject = converter->FindBlenderObject(gameobj);
1881                 int nummeshes = gameobj->GetMeshCount();
1882                 RAS_MeshObject* meshobj = 0;
1883
1884                 if (nummeshes > 0)
1885                 {
1886                         meshobj = gameobj->GetMesh(0);
1887                 }
1888
1889                 BL_CreatePhysicsObjectNew(gameobj,blenderobject,meshobj,kxscene,activeLayerBitInfo,physics_engine,converter);
1890
1891         }
1892         
1893                 // create physics joints
1894         for (i=0;i<sumolist->GetCount();i++)
1895         {
1896                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
1897                 struct Object* blenderobject = converter->FindBlenderObject(gameobj);
1898                 int nummeshes = gameobj->GetMeshCount();
1899                 RAS_MeshObject* meshobj = 0;
1900         ListBase *conlist;
1901         bConstraint *curcon;
1902         conlist = get_active_constraints2(blenderobject);
1903         if (conlist) {
1904             for (curcon = (bConstraint *)conlist->first; curcon; curcon=(bConstraint *)curcon->next) {
1905                 if (curcon->type==CONSTRAINT_TYPE_RIGIDBODYJOINT){
1906                     bRigidBodyJointConstraint *dat=(bRigidBodyJointConstraint *)curcon->data;
1907                     if (dat->tar)
1908                         if (!dat->child){
1909                             KX_GameObject *gotar=getGameOb(dat->tar->id.name,sumolist);
1910                             PHY_IPhysicsController* physctrl = (PHY_IPhysicsController*) (int)gameobj->GetPhysicsController()->GetUserData();
1911                             PHY_IPhysicsController* physctr2 = (PHY_IPhysicsController*) (int)gotar->GetPhysicsController()->GetUserData();
1912                             kxscene->GetPhysicsEnvironment()->createConstraint(physctrl,physctr2,(PHY_ConstraintType)dat->type,(float)dat->pivX,(float)dat->pivY,(float)dat->pivZ,(float)dat->axX,(float)dat->axY,(float)dat->axZ);
1913                             /*switch(dat->type){
1914                                 case CONSTRAINT_RB_BALL:
1915                                     KX_GameObject *gotar=getGameOb(dat->tar->id.name,sumolist);
1916                                     PHY_IPhysicsController* physctrl = (PHY_IPhysicsController*) (int)gameobj->GetPhysicsController()->GetUserData();
1917                                     PHY_IPhysicsController* physctr2 = (PHY_IPhysicsController*) (int)gotar->GetPhysicsController()->GetUserData();
1918                                     kxscene->GetPhysicsEnvironment()->createConstraint(physctrl,physctr2,(PHY_ConstraintType)dat->type,(float)dat->pivX,(float)dat->pivY,(float)dat->pivZ,(float)dat->axX,(float)dat->axY,(float)dat->axZ);
1919                                     break;
1920                                 case CONSTRAINT_RB_HINGE:
1921                                     KX_GameObject *gotar=getGameOb(dat->tar->id.name,sumolist);
1922                                     PHY_IPhysicsController* physctrl = (PHY_IPhysicsController*) (int)gameobj->GetPhysicsController()->GetUserData();
1923                                     PHY_IPhysicsController* physctr2 = (PHY_IPhysicsController*) (int)gotar->GetPhysicsController()->GetUserData();
1924                                     kxscene->GetPhysicsEnvironment()->createConstraint(physctrl,physctr2,(PHY_ConstraintType)dat->type,(float)dat->pivX,(float)dat->pivY,(float)dat->pivZ,(float)dat->axX,(float)dat->axY,(float)dat->axZ);
1925                                     break;
1926                             }*/
1927                         }
1928                 }
1929             }
1930         }
1931
1932         }
1933
1934     //Intento de actualizar posicion
1935         /*for (i=0;i<sumolist->GetCount();i++)
1936         {
1937                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
1938                 struct Object* blenderobject = converter->FindBlenderObject(gameobj);
1939
1940                 MT_Point3 pos = MT_Point3(
1941                                 blenderobject->loc[0]+blenderobject->dloc[0],
1942                                 blenderobject->loc[1]+blenderobject->dloc[1],
1943                                 blenderobject->loc[2]+blenderobject->dloc[2]
1944                         );
1945                 MT_Vector3 eulxyz = MT_Vector3(
1946                                 blenderobject->rot[0],
1947                                 blenderobject->rot[1],
1948                                 blenderobject->rot[2]
1949                         );
1950                 MT_Vector3 scale = MT_Vector3(
1951                                 blenderobject->size[0],
1952                                 blenderobject->size[1],
1953                                 blenderobject->size[2]
1954                         );
1955
1956                 gameobj->NodeSetLocalPosition(pos);
1957                 gameobj->NodeSetLocalOrientation(MT_Matrix3x3(eulxyz));
1958                 gameobj->NodeSetLocalScale(scale);
1959                 gameobj->NodeUpdateGS(0,true);
1960         }*/
1961     //rcruiz>
1962
1963         
1964         templist->Release();
1965         sumolist->Release();    
1966
1967
1968         int executePriority=0; /* incremented by converter routines */
1969         
1970         // convert global sound stuff
1971
1972         /* XXX, glob is the very very wrong place for this
1973          * to be, re-enable once the listener has been moved into
1974          * the scene. */
1975 #if 1
1976         SND_Scene* soundscene = kxscene->GetSoundScene();
1977         SND_SoundListener* listener = soundscene->GetListener();
1978         if (listener && G.listener)
1979         {
1980                 listener->SetDopplerFactor(G.listener->dopplerfactor);
1981                 listener->SetDopplerVelocity(G.listener->dopplervelocity);
1982                 listener->SetGain(G.listener->gain);
1983         }
1984 #endif
1985
1986         // convert world
1987         KX_WorldInfo* worldinfo = new BlenderWorldInfo(blenderscene->world);
1988         converter->RegisterWorldInfo(worldinfo);
1989         kxscene->SetWorldInfo(worldinfo);
1990
1991 #define CONVERT_LOGIC
1992 #ifdef CONVERT_LOGIC
1993         // convert logic bricks, sensors, controllers and actuators
1994         for (i=0;i<logicbrick_conversionlist->GetCount();i++)
1995         {
1996                 KX_GameObject* gameobj = static_cast<KX_GameObject*>(logicbrick_conversionlist->GetValue(i));
1997                 struct Object* blenderobj = converter->FindBlenderObject(gameobj);
1998                 bool isInActiveLayer = (blenderobj->lay & activeLayerBitInfo)!=0;
1999                 BL_ConvertActuators(maggie->name, blenderobj,gameobj,logicmgr,kxscene,ketsjiEngine,executePriority, activeLayerBitInfo,isInActiveLayer,rendertools,converter);
2000         }
2001         for ( i=0;i<logicbrick_conversionlist->GetCount();i++)
2002         {
2003                 KX_GameObject* gameobj = static_cast<KX_GameObject*>(logicbrick_conversionlist->GetValue(i));
2004                 struct Object* blenderobj = converter->FindBlenderObject(gameobj);
2005                 bool isInActiveLayer = (blenderobj->lay & activeLayerBitInfo)!=0;
2006                 BL_ConvertControllers(blenderobj,gameobj,logicmgr,pythondictionary,executePriority,activeLayerBitInfo,isInActiveLayer,converter);
2007         }
2008         for ( i=0;i<logicbrick_conversionlist->GetCount();i++)
2009         {
2010                 KX_GameObject* gameobj = static_cast<KX_GameObject*>(logicbrick_conversionlist->GetValue(i));
2011                 struct Object* blenderobj = converter->FindBlenderObject(gameobj);
2012                 bool isInActiveLayer = (blenderobj->lay & activeLayerBitInfo)!=0;
2013                 BL_ConvertSensors(blenderobj,gameobj,logicmgr,kxscene,keydev,executePriority,activeLayerBitInfo,isInActiveLayer,canvas,converter);
2014         }
2015 #endif //CONVERT_LOGIC
2016
2017         logicbrick_conversionlist->Release();
2018         
2019         // Calculate the scene btree -
2020         // too slow - commented out.
2021         //kxscene->SetNodeTree(tf.MakeTree());
2022 }
2023