fix [#26803] Libs paths are case sensitive in windows
[blender.git] / source / gameengine / Converter / KX_BlenderSceneConverter.cpp
1 /*
2  * $Id$
3  * ***** BEGIN GPL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  *
19  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
20  * All rights reserved.
21  *
22  * The Original Code is: all of this file.
23  *
24  * Contributor(s): none yet.
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 /** \file gameengine/Converter/KX_BlenderSceneConverter.cpp
30  *  \ingroup bgeconv
31  */
32
33
34 #if defined(WIN32) && !defined(FREE_WINDOWS)
35 #pragma warning (disable:4786) // suppress stl-MSVC debug info warning
36 #endif
37
38 #include "KX_Scene.h"
39 #include "KX_GameObject.h"
40 #include "KX_BlenderSceneConverter.h"
41 #include "KX_IpoConvert.h"
42 #include "RAS_MeshObject.h"
43 #include "KX_PhysicsEngineEnums.h"
44 #include "PHY_IPhysicsEnvironment.h"
45 #include "KX_KetsjiEngine.h"
46 #include "KX_IPhysicsController.h"
47 #include "BL_Material.h"
48 #include "BL_ActionActuator.h"
49 #include "KX_BlenderMaterial.h"
50 #include "KX_PolygonMaterial.h"
51
52
53 #include "SYS_System.h"
54
55 #include "DummyPhysicsEnvironment.h"
56
57 #include "KX_ConvertPhysicsObject.h"
58
59 #ifdef USE_BULLET
60 #include "CcdPhysicsEnvironment.h"
61 #endif
62
63 #include "KX_BlenderSceneConverter.h"
64 #include "KX_BlenderScalarInterpolator.h"
65 #include "BL_BlenderDataConversion.h"
66 #include "BlenderWorldInfo.h"
67 #include "KX_Scene.h"
68
69 /* This little block needed for linking to Blender... */
70 #ifdef WIN32
71 #include "BLI_winstuff.h"
72 #endif
73
74 /* This list includes only data type definitions */
75 #include "DNA_scene_types.h"
76 #include "DNA_world_types.h"
77 #include "BKE_main.h"
78
79 #include "BLI_math.h"
80
81 extern "C"
82 {
83 #include "DNA_object_types.h"
84 #include "DNA_curve_types.h"
85 #include "DNA_mesh_types.h"
86 #include "DNA_material_types.h"
87 #include "BLI_blenlib.h"
88 #include "MEM_guardedalloc.h"
89 #include "BKE_global.h"
90 #include "BKE_animsys.h"
91 #include "BKE_library.h"
92 #include "BKE_material.h" // copy_material
93 #include "BKE_mesh.h" // copy_mesh
94 #include "DNA_space_types.h"
95 #include "DNA_anim_types.h"
96 #include "RNA_define.h"
97 #include "../../blender/editors/include/ED_keyframing.h"
98 }
99
100 /* Only for dynamic loading and merging */
101 #include "RAS_BucketManager.h" // XXX cant stay
102 #include "KX_BlenderSceneConverter.h"
103 #include "BL_BlenderDataConversion.h"
104 #include "KX_MeshProxy.h"
105 #include "RAS_MeshObject.h"
106 extern "C" {
107         #include "BKE_context.h"
108         #include "BLO_readfile.h"
109         #include "BKE_idcode.h"
110         #include "BKE_report.h"
111         #include "DNA_space_types.h"
112         #include "DNA_windowmanager_types.h" /* report api */
113         #include "../../blender/blenlib/BLI_linklist.h"
114 }
115
116 KX_BlenderSceneConverter::KX_BlenderSceneConverter(
117                                                         struct Main* maggie,
118                                                         class KX_KetsjiEngine* engine
119                                                         )
120                                                         : m_maggie(maggie),
121                                                         /*m_maggie_dyn(NULL),*/
122                                                         m_ketsjiEngine(engine),
123                                                         m_alwaysUseExpandFraming(false),
124                                                         m_usemat(false),
125                                                         m_useglslmat(false)
126 {
127         tag_main(maggie, 0); /* avoid re-tagging later on */
128         m_newfilename = "";
129 }
130
131
132 KX_BlenderSceneConverter::~KX_BlenderSceneConverter()
133 {
134         // clears meshes, and hashmaps from blender to gameengine data
135         int i;
136         // delete sumoshapes
137         
138
139         int numAdtLists = m_map_blender_to_gameAdtList.size();
140         for (i=0; i<numAdtLists; i++) {
141                 BL_InterpolatorList *adtList= *m_map_blender_to_gameAdtList.at(i);
142
143                 delete (adtList);
144         }
145
146         vector<pair<KX_Scene*,KX_WorldInfo*> >::iterator itw = m_worldinfos.begin();
147         while (itw != m_worldinfos.end()) {
148                 delete (*itw).second;
149                 itw++;
150         }
151
152         vector<pair<KX_Scene*,RAS_IPolyMaterial*> >::iterator itp = m_polymaterials.begin();
153         while (itp != m_polymaterials.end()) {
154                 delete (*itp).second;
155                 itp++;
156         }
157
158         // delete after RAS_IPolyMaterial
159         vector<pair<KX_Scene*,BL_Material *> >::iterator itmat = m_materials.begin();
160         while (itmat != m_materials.end()) {
161                 delete (*itmat).second;
162                 itmat++;
163         }       
164
165
166         vector<pair<KX_Scene*,RAS_MeshObject*> >::iterator itm = m_meshobjects.begin();
167         while (itm != m_meshobjects.end()) {
168                 delete (*itm).second;
169                 itm++;
170         }
171
172 #ifdef USE_BULLET
173         KX_ClearBulletSharedShapes();
174 #endif
175
176         /* free any data that was dynamically loaded */
177         for (vector<Main*>::iterator it=m_DynamicMaggie.begin(); !(it==m_DynamicMaggie.end()); it++) {
178                 Main *main= *it;
179                 free_main(main);
180         }
181
182         m_DynamicMaggie.clear();
183 }
184
185 void KX_BlenderSceneConverter::SetNewFileName(const STR_String& filename)
186 {
187         m_newfilename = filename;
188 }
189
190
191
192 bool KX_BlenderSceneConverter::TryAndLoadNewFile()
193 {
194         bool result = false;
195
196         // find the file
197 /*      if ()
198         {
199                 result = true;
200         }
201         // if not, clear the newfilename
202         else
203         {
204                 m_newfilename = "";     
205         }
206 */
207         return result;
208 }
209
210 Scene *KX_BlenderSceneConverter::GetBlenderSceneForName(const STR_String& name)
211 {
212         Scene *sce;
213
214         /**
215          * Find the specified scene by name, or the first
216          * scene if nothing matches (shouldn't happen).
217          */
218         if((sce= (Scene *)BLI_findstring(&m_maggie->scene, name.ReadPtr(), offsetof(ID, name) + 2)))
219                 return sce;
220
221         for (vector<Main*>::iterator it=m_DynamicMaggie.begin(); !(it==m_DynamicMaggie.end()); it++) {
222                 Main *main= *it;
223
224                 if((sce= (Scene *)BLI_findstring(&main->scene, name.ReadPtr(), offsetof(ID, name) + 2)))
225                         return sce;
226         }
227
228         return (Scene*)m_maggie->scene.first;
229
230 }
231 #include "KX_PythonInit.h"
232
233 #ifdef USE_BULLET
234
235 #include "LinearMath/btIDebugDraw.h"
236
237
238 struct  BlenderDebugDraw : public btIDebugDraw
239 {
240         BlenderDebugDraw () :
241                 m_debugMode(0) 
242         {
243         }
244         
245         int m_debugMode;
246
247         virtual void    drawLine(const btVector3& from,const btVector3& to,const btVector3& color)
248         {
249                 if (m_debugMode >0)
250                 {
251                         MT_Vector3 kxfrom(from[0],from[1],from[2]);
252                         MT_Vector3 kxto(to[0],to[1],to[2]);
253                         MT_Vector3 kxcolor(color[0],color[1],color[2]);
254
255                         KX_RasterizerDrawDebugLine(kxfrom,kxto,kxcolor);
256                 }
257         }
258         
259         virtual void    reportErrorWarning(const char* warningString)
260         {
261
262         }
263
264         virtual void    drawContactPoint(const btVector3& PointOnB,const btVector3& normalOnB,float distance,int lifeTime,const btVector3& color)
265         {
266                 //not yet
267         }
268
269         virtual void    setDebugMode(int debugMode)
270         {
271                 m_debugMode = debugMode;
272         }
273         virtual int             getDebugMode() const
274         {
275                 return m_debugMode;
276         }
277         ///todo: find out if Blender can do this
278         virtual void    draw3dText(const btVector3& location,const char* textString)
279         {
280
281         }
282                 
283 };
284
285 #endif
286
287 void KX_BlenderSceneConverter::ConvertScene(class KX_Scene* destinationscene,
288                                                                                         class RAS_IRenderTools* rendertools,
289                                                                                         class RAS_ICanvas* canvas)
290 {
291         //find out which physics engine
292         Scene *blenderscene = destinationscene->GetBlenderScene();
293
294         e_PhysicsEngine physics_engine = UseBullet;
295         bool useDbvtCulling = false;
296         // hook for registration function during conversion.
297         m_currentScene = destinationscene;
298         destinationscene->SetSceneConverter(this);
299         SG_SetActiveStage(SG_STAGE_CONVERTER);
300
301         if (blenderscene)
302         {
303         
304                 switch (blenderscene->gm.physicsEngine)
305                 {
306                 case WOPHY_BULLET:
307                         {
308                                 physics_engine = UseBullet;
309                                 useDbvtCulling = (blenderscene->gm.mode & WO_DBVT_CULLING) != 0;
310                                 break;
311                         }
312                                                         
313                         case WOPHY_ODE:
314                         {
315                                 physics_engine = UseODE;
316                                 break;
317                         }
318                         case WOPHY_DYNAMO:
319                         {
320                                 physics_engine = UseDynamo;
321                                 break;
322                         }
323                         case WOPHY_SUMO:
324                         {
325                                 physics_engine = UseSumo; 
326                                 break;
327                         }
328                         case WOPHY_NONE:
329                         {
330                                 physics_engine = UseNone;
331                         }
332                 }
333         }
334
335         switch (physics_engine)
336         {
337 #ifdef USE_BULLET
338                 case UseBullet:
339                         {
340                                 CcdPhysicsEnvironment* ccdPhysEnv = new CcdPhysicsEnvironment(useDbvtCulling);
341                                 ccdPhysEnv->setDebugDrawer(new BlenderDebugDraw());
342                                 ccdPhysEnv->setDeactivationLinearTreshold(0.8f); // default, can be overridden by Python
343                                 ccdPhysEnv->setDeactivationAngularTreshold(1.0f); // default, can be overridden by Python
344
345                                 SYS_SystemHandle syshandle = SYS_GetSystem(); /*unused*/
346                                 int visualizePhysics = SYS_GetCommandLineInt(syshandle,"show_physics",0);
347                                 if (visualizePhysics)
348                                         ccdPhysEnv->setDebugMode(btIDebugDraw::DBG_DrawWireframe|btIDebugDraw::DBG_DrawAabb|btIDebugDraw::DBG_DrawContactPoints|btIDebugDraw::DBG_DrawText|btIDebugDraw::DBG_DrawConstraintLimits|btIDebugDraw::DBG_DrawConstraints);
349                 
350                                 //todo: get a button in blender ?
351                                 //disable / enable debug drawing (contact points, aabb's etc)   
352                                 //ccdPhysEnv->setDebugMode(1);
353                                 destinationscene->SetPhysicsEnvironment(ccdPhysEnv);
354                                 break;
355                         }
356 #endif  
357                 case UseDynamo:
358                 {
359                 }
360                 
361                 default:
362                 case UseNone:
363                         physics_engine = UseNone;
364                         destinationscene ->SetPhysicsEnvironment(new DummyPhysicsEnvironment());
365                         break;
366         }
367
368         BL_ConvertBlenderObjects(m_maggie,
369                 destinationscene,
370                 m_ketsjiEngine,
371                 physics_engine,
372                 rendertools,
373                 canvas,
374                 this,
375                 m_alwaysUseExpandFraming
376                 );
377
378         //These lookup are not needed during game
379         m_map_blender_to_gameactuator.clear();
380         m_map_blender_to_gamecontroller.clear();
381         m_map_blender_to_gameobject.clear();
382
383         //Clearing this lookup table has the effect of disabling the cache of meshes
384         //between scenes, even if they are shared in the blend file.
385         //This cache mecanism is buggy so I leave it disable and the memory leak
386         //that would result from this is fixed in RemoveScene()
387         m_map_mesh_to_gamemesh.clear();
388 }
389
390 // This function removes all entities stored in the converter for that scene
391 // It should be used instead of direct delete scene
392 // Note that there was some provision for sharing entities (meshes...) between
393 // scenes but that is now disabled so all scene will have their own copy
394 // and we can delete them here. If the sharing is reactivated, change this code too..
395 // (see KX_BlenderSceneConverter::ConvertScene)
396 void KX_BlenderSceneConverter::RemoveScene(KX_Scene *scene)
397 {
398         int i, size;
399         // delete the scene first as it will stop the use of entities
400         delete scene;
401         // delete the entities of this scene
402         vector<pair<KX_Scene*,KX_WorldInfo*> >::iterator worldit;
403         size = m_worldinfos.size();
404         for (i=0, worldit=m_worldinfos.begin(); i<size; ) {
405                 if ((*worldit).first == scene) {
406                         delete (*worldit).second;
407                         *worldit = m_worldinfos.back();
408                         m_worldinfos.pop_back();
409                         size--;
410                 } else {
411                         i++;
412                         worldit++;
413                 }
414         }
415
416         vector<pair<KX_Scene*,RAS_IPolyMaterial*> >::iterator polymit;
417         size = m_polymaterials.size();
418         for (i=0, polymit=m_polymaterials.begin(); i<size; ) {
419                 if ((*polymit).first == scene) {
420                         delete (*polymit).second;
421                         *polymit = m_polymaterials.back();
422                         m_polymaterials.pop_back();
423                         size--;
424                 } else {
425                         i++;
426                         polymit++;
427                 }
428         }
429
430         vector<pair<KX_Scene*,BL_Material*> >::iterator matit;
431         size = m_materials.size();
432         for (i=0, matit=m_materials.begin(); i<size; ) {
433                 if ((*matit).first == scene) {
434                         delete (*matit).second;
435                         *matit = m_materials.back();
436                         m_materials.pop_back();
437                         size--;
438                 } else {
439                         i++;
440                         matit++;
441                 }
442         }
443
444         vector<pair<KX_Scene*,RAS_MeshObject*> >::iterator meshit;
445         size = m_meshobjects.size();
446         for (i=0, meshit=m_meshobjects.begin(); i<size; ) {
447                 if ((*meshit).first == scene) {
448                         delete (*meshit).second;
449                         *meshit = m_meshobjects.back();
450                         m_meshobjects.pop_back();
451                         size--;
452                 } else {
453                         i++;
454                         meshit++;
455                 }
456         }
457 }
458
459 // use blender materials
460 void KX_BlenderSceneConverter::SetMaterials(bool val)
461 {
462         m_usemat = val;
463         m_useglslmat = false;
464 }
465
466 void KX_BlenderSceneConverter::SetGLSLMaterials(bool val)
467 {
468         m_usemat = val;
469         m_useglslmat = val;
470 }
471
472 bool KX_BlenderSceneConverter::GetMaterials()
473 {
474         return m_usemat;
475 }
476
477 bool KX_BlenderSceneConverter::GetGLSLMaterials()
478 {
479         return m_useglslmat;
480 }
481
482 void KX_BlenderSceneConverter::RegisterBlenderMaterial(BL_Material *mat)
483 {
484         m_materials.push_back(pair<KX_Scene*,BL_Material *>(m_currentScene,mat));
485 }
486
487
488
489 void KX_BlenderSceneConverter::SetAlwaysUseExpandFraming(
490         bool to_what)
491 {
492         m_alwaysUseExpandFraming= to_what;
493 }
494
495         
496
497 void KX_BlenderSceneConverter::RegisterGameObject(
498                                                                         KX_GameObject *gameobject, 
499                                                                         struct Object *for_blenderobject) 
500 {
501         /* only maintained while converting, freed during game runtime */
502         m_map_blender_to_gameobject.insert(CHashedPtr(for_blenderobject),gameobject);
503 }
504
505 /* only need to run this during conversion since
506  * m_map_blender_to_gameobject is freed after conversion */
507 void KX_BlenderSceneConverter::UnregisterGameObject(
508                                                                         KX_GameObject *gameobject) 
509 {
510         struct Object *bobp= gameobject->GetBlenderObject();
511         if (bobp) {
512                 CHashedPtr bptr(bobp);
513                 KX_GameObject **gobp= m_map_blender_to_gameobject[bptr];
514                 if (gobp && *gobp == gameobject)
515                 {
516                         // also maintain m_map_blender_to_gameobject if the gameobject
517                         // being removed is matching the blender object
518                         m_map_blender_to_gameobject.remove(bptr);
519                 }
520         }
521 }
522
523 KX_GameObject *KX_BlenderSceneConverter::FindGameObject(
524                                                                         struct Object *for_blenderobject) 
525 {
526         KX_GameObject **obp= m_map_blender_to_gameobject[CHashedPtr(for_blenderobject)];
527         
528         return obp?*obp:NULL;
529 }
530
531 void KX_BlenderSceneConverter::RegisterGameMesh(
532                                                                         RAS_MeshObject *gamemesh,
533                                                                         struct Mesh *for_blendermesh)
534 {
535         if(for_blendermesh) { /* dynamically loaded meshes we dont want to keep lookups for */
536                 m_map_mesh_to_gamemesh.insert(CHashedPtr(for_blendermesh),gamemesh);
537         }
538         m_meshobjects.push_back(pair<KX_Scene*,RAS_MeshObject*>(m_currentScene,gamemesh));
539 }
540
541
542
543 RAS_MeshObject *KX_BlenderSceneConverter::FindGameMesh(
544                                                                         struct Mesh *for_blendermesh/*,
545                                                                         unsigned int onlayer*/)
546 {
547         RAS_MeshObject** meshp = m_map_mesh_to_gamemesh[CHashedPtr(for_blendermesh)];
548         
549         if (meshp/* && onlayer==(*meshp)->GetLightLayer()*/) {
550                 return *meshp;
551         } else {
552                 return NULL;
553         }
554 }
555
556         
557
558
559         
560
561 void KX_BlenderSceneConverter::RegisterPolyMaterial(RAS_IPolyMaterial *polymat)
562 {
563         m_polymaterials.push_back(pair<KX_Scene*,RAS_IPolyMaterial*>(m_currentScene,polymat));
564 }
565
566
567
568 void KX_BlenderSceneConverter::RegisterInterpolatorList(
569                                                                         BL_InterpolatorList *adtList,
570                                                                         struct AnimData *for_adt)
571 {
572         m_map_blender_to_gameAdtList.insert(CHashedPtr(for_adt), adtList);
573 }
574
575
576
577 BL_InterpolatorList *KX_BlenderSceneConverter::FindInterpolatorList(
578                                                                         struct AnimData *for_adt)
579 {
580         BL_InterpolatorList **listp = m_map_blender_to_gameAdtList[CHashedPtr(for_adt)];
581                 
582         return listp?*listp:NULL;
583 }
584
585
586
587 void KX_BlenderSceneConverter::RegisterGameActuator(
588                                                                         SCA_IActuator *act,
589                                                                         struct bActuator *for_actuator)
590 {
591         m_map_blender_to_gameactuator.insert(CHashedPtr(for_actuator), act);
592 }
593
594
595
596 SCA_IActuator *KX_BlenderSceneConverter::FindGameActuator(
597                                                                         struct bActuator *for_actuator)
598 {
599         SCA_IActuator **actp = m_map_blender_to_gameactuator[CHashedPtr(for_actuator)];
600         
601         return actp?*actp:NULL;
602 }
603
604
605
606 void KX_BlenderSceneConverter::RegisterGameController(
607                                                                         SCA_IController *cont,
608                                                                         struct bController *for_controller)
609 {
610         m_map_blender_to_gamecontroller.insert(CHashedPtr(for_controller), cont);
611 }
612
613
614
615 SCA_IController *KX_BlenderSceneConverter::FindGameController(
616                                                                         struct bController *for_controller)
617 {
618         SCA_IController **contp = m_map_blender_to_gamecontroller[CHashedPtr(for_controller)];
619         
620         return contp?*contp:NULL;
621 }
622
623
624
625 void KX_BlenderSceneConverter::RegisterWorldInfo(
626                                                                         KX_WorldInfo *worldinfo)
627 {
628         m_worldinfos.push_back(pair<KX_Scene*,KX_WorldInfo*>(m_currentScene,worldinfo));
629 }
630
631 void    KX_BlenderSceneConverter::ResetPhysicsObjectsAnimationIpo(bool clearIpo)
632 {
633
634         KX_SceneList* scenes = m_ketsjiEngine->CurrentScenes();
635         int numScenes = scenes->size();
636         int i;
637         for (i=0;i<numScenes;i++)
638         {
639                 KX_Scene* scene = scenes->at(i);
640                 //PHY_IPhysicsEnvironment* physEnv = scene->GetPhysicsEnvironment();
641                 CListValue* parentList = scene->GetRootParentList();
642                 int numObjects = parentList->GetCount();
643                 int g;
644                 for (g=0;g<numObjects;g++)
645                 {
646                         KX_GameObject* gameObj = (KX_GameObject*)parentList->GetValue(g);
647                         if (gameObj->IsDynamic())
648                         {
649                                 //KX_IPhysicsController* physCtrl = gameObj->GetPhysicsController();
650                                 
651                                 Object* blenderObject = gameObj->GetBlenderObject();
652                                 if (blenderObject)
653                                 {
654 #if 0
655                                         //erase existing ipo's
656                                         Ipo* ipo = blenderObject->ipo;//findIpoForName(blenderObject->id.name+2);
657                                         if (ipo)
658                                         {       //clear the curve data
659                                                 if (clearIpo){//rcruiz
660                                                         IpoCurve *icu1;
661                                                                                                                 
662                                                         int numCurves = 0;
663                                                         for( icu1 = (IpoCurve*)ipo->curve.first; icu1;  ) {
664                                                         
665                                                                 IpoCurve* tmpicu = icu1;
666                                                                 
667                                                                 /*int i;
668                                                                 BezTriple *bezt;
669                                                                 for( bezt = tmpicu->bezt, i = 0;        i < tmpicu->totvert; i++, bezt++){
670                                                                         printf("(%f,%f,%f),(%f,%f,%f),(%f,%f,%f)\n",bezt->vec[0][0],bezt->vec[0][1],bezt->vec[0][2],bezt->vec[1][0],bezt->vec[1][1],bezt->vec[1][2],bezt->vec[2][0],bezt->vec[2][1],bezt->vec[2][2]);
671                                                                 }*/
672                                                                 
673                                                                 icu1 = icu1->next;
674                                                                 numCurves++;
675                         
676                                                                 BLI_remlink( &( blenderObject->ipo->curve ), tmpicu );
677                                                                 if( tmpicu->bezt )
678                                                                         MEM_freeN( tmpicu->bezt );
679                                                                 MEM_freeN( tmpicu );
680                                                                 localDel_ipoCurve( tmpicu );
681                                                         }
682                                                 }
683                                         } else
684                                         {       ipo = NULL; // XXX add_ipo(blenderObject->id.name+2, ID_OB);
685                                                 blenderObject->ipo = ipo;
686
687                                         }
688 #endif
689                                 }
690                         }
691
692                 }
693                 
694         
695         }
696
697
698
699 }
700
701 void    KX_BlenderSceneConverter::resetNoneDynamicObjectToIpo(){
702         
703         if (addInitFromFrame){          
704                 KX_SceneList* scenes = m_ketsjiEngine->CurrentScenes();
705                 int numScenes = scenes->size();
706                 if (numScenes>=0){
707                         KX_Scene* scene = scenes->at(0);
708                         CListValue* parentList = scene->GetRootParentList();
709                         for (int ix=0;ix<parentList->GetCount();ix++){
710                                 KX_GameObject* gameobj = (KX_GameObject*)parentList->GetValue(ix);
711                                 if (!gameobj->IsDynamic()){
712                                         Object* blenderobject = gameobj->GetBlenderObject();
713                                         if (!blenderobject)
714                                                 continue;
715                                         if (blenderobject->type==OB_ARMATURE)
716                                                 continue;
717                                         float eu[3];
718                                         mat4_to_eul(eu,blenderobject->obmat);                                   
719                                         MT_Point3 pos = MT_Point3(
720                                                 blenderobject->obmat[3][0],
721                                                 blenderobject->obmat[3][1],
722                                                 blenderobject->obmat[3][2]
723                                         );
724                                         MT_Vector3 eulxyz = MT_Vector3(
725                                                 eu[0],
726                                                 eu[1],
727                                                 eu[2]
728                                         );
729                                         MT_Vector3 scale = MT_Vector3(
730                                                 blenderobject->size[0],
731                                                 blenderobject->size[1],
732                                                 blenderobject->size[2]
733                                         );
734                                         gameobj->NodeSetLocalPosition(pos);
735                                         gameobj->NodeSetLocalOrientation(MT_Matrix3x3(eulxyz));
736                                         gameobj->NodeSetLocalScale(scale);
737                                         gameobj->NodeUpdateGS(0);
738                                 }
739                         }
740                 }
741         }
742 }
743
744
745         ///this generates ipo curves for position, rotation, allowing to use game physics in animation
746 void    KX_BlenderSceneConverter::WritePhysicsObjectToAnimationIpo(int frameNumber)
747 {
748
749         KX_SceneList* scenes = m_ketsjiEngine->CurrentScenes();
750         int numScenes = scenes->size();
751         int i;
752         for (i=0;i<numScenes;i++)
753         {
754                 KX_Scene* scene = scenes->at(i);
755                 //PHY_IPhysicsEnvironment* physEnv = scene->GetPhysicsEnvironment();
756                 CListValue* parentList = scene->GetObjectList();
757                 int numObjects = parentList->GetCount();
758                 int g;
759                 for (g=0;g<numObjects;g++)
760                 {
761                         KX_GameObject* gameObj = (KX_GameObject*)parentList->GetValue(g);
762                         Object* blenderObject = gameObj->GetBlenderObject();
763                         if (blenderObject && blenderObject->parent==NULL && gameObj->GetPhysicsController() != NULL)
764                         {
765                                 //KX_IPhysicsController* physCtrl = gameObj->GetPhysicsController();
766
767                                 if(blenderObject->adt==NULL)
768                                         BKE_id_add_animdata(&blenderObject->id);
769
770                                 if (blenderObject->adt)
771                                 {
772                                         const MT_Point3& position = gameObj->NodeGetWorldPosition();
773                                         //const MT_Vector3& scale = gameObj->NodeGetWorldScaling();
774                                         const MT_Matrix3x3& orn = gameObj->NodeGetWorldOrientation();
775
776                                         position.getValue(blenderObject->loc);
777
778                                         float tmat[3][3];
779                                         for (int r=0;r<3;r++)
780                                                 for (int c=0;c<3;c++)
781                                                         tmat[r][c] = orn[c][r];
782
783                                         mat3_to_compatible_eul(blenderObject->rot, blenderObject->rot, tmat);
784
785                                         insert_keyframe(NULL, &blenderObject->id, NULL, NULL, "location", -1, frameNumber, INSERTKEY_FAST);
786                                         insert_keyframe(NULL, &blenderObject->id, NULL, NULL, "rotation_euler", -1, frameNumber, INSERTKEY_FAST);
787
788 #if 0
789                                         const MT_Point3& position = gameObj->NodeGetWorldPosition();
790                                         //const MT_Vector3& scale = gameObj->NodeGetWorldScaling();
791                                         const MT_Matrix3x3& orn = gameObj->NodeGetWorldOrientation();
792                                         
793                                         float eulerAngles[3];   
794                                         float eulerAnglesOld[3] = {0.0f, 0.0f, 0.0f};                                           
795                                         float tmat[3][3];
796                                         
797                                         // XXX animato
798                                         Ipo* ipo = blenderObject->ipo;
799
800                                         //create the curves, if not existing, set linear if new
801
802                                         IpoCurve *icu_lx = findIpoCurve((IpoCurve *)ipo->curve.first,"LocX");
803                                         if (!icu_lx) {
804                                                 icu_lx = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_X, 1);
805                                                 if(icu_lx) icu_lx->ipo = IPO_LIN;
806                                         }
807                                         IpoCurve *icu_ly = findIpoCurve((IpoCurve *)ipo->curve.first,"LocY");
808                                         if (!icu_ly) {
809                                                 icu_ly = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Y, 1);
810                                                 if(icu_ly) icu_ly->ipo = IPO_LIN;
811                                         }
812                                         IpoCurve *icu_lz = findIpoCurve((IpoCurve *)ipo->curve.first,"LocZ");
813                                         if (!icu_lz) {
814                                                 icu_lz = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Z, 1);
815                                                 if(icu_lz) icu_lz->ipo = IPO_LIN;
816                                         }
817                                         IpoCurve *icu_rx = findIpoCurve((IpoCurve *)ipo->curve.first,"RotX");
818                                         if (!icu_rx) {
819                                                 icu_rx = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_X, 1);
820                                                 if(icu_rx) icu_rx->ipo = IPO_LIN;
821                                         }
822                                         IpoCurve *icu_ry = findIpoCurve((IpoCurve *)ipo->curve.first,"RotY");
823                                         if (!icu_ry) {
824                                                 icu_ry = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Y, 1);
825                                                 if(icu_ry) icu_ry->ipo = IPO_LIN;
826                                         }
827                                         IpoCurve *icu_rz = findIpoCurve((IpoCurve *)ipo->curve.first,"RotZ");
828                                         if (!icu_rz) {
829                                                 icu_rz = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Z, 1);
830                                                 if(icu_rz) icu_rz->ipo = IPO_LIN;
831                                         }
832                                         
833                                         if(icu_rx) eulerAnglesOld[0]= eval_icu( icu_rx, frameNumber - 1 ) / ((180 / 3.14159265f) / 10);
834                                         if(icu_ry) eulerAnglesOld[1]= eval_icu( icu_ry, frameNumber - 1 ) / ((180 / 3.14159265f) / 10);
835                                         if(icu_rz) eulerAnglesOld[2]= eval_icu( icu_rz, frameNumber - 1 ) / ((180 / 3.14159265f) / 10);
836                                         
837                                         // orn.getValue((float *)tmat); // uses the wrong ordering, cant use this
838                                         for (int r=0;r<3;r++)
839                                                 for (int c=0;c<3;c++)
840                                                         tmat[r][c] = orn[c][r];
841                                         
842                                         // mat3_to_eul( eulerAngles,tmat); // better to use Mat3ToCompatibleEul
843                                         mat3_to_compatible_eul( eulerAngles, eulerAnglesOld,tmat);
844                                         
845                                         //eval_icu
846                                         for(int x = 0; x < 3; x++)
847                                                 eulerAngles[x] *= (float) ((180 / 3.14159265f) / 10.0);
848                                         
849                                         //fill the curves with data
850                                         if (icu_lx) insert_vert_icu(icu_lx, frameNumber, position.x(), 1);
851                                         if (icu_ly) insert_vert_icu(icu_ly, frameNumber, position.y(), 1);
852                                         if (icu_lz) insert_vert_icu(icu_lz, frameNumber, position.z(), 1);
853                                         if (icu_rx) insert_vert_icu(icu_rx, frameNumber, eulerAngles[0], 1);
854                                         if (icu_ry) insert_vert_icu(icu_ry, frameNumber, eulerAngles[1], 1);
855                                         if (icu_rz) insert_vert_icu(icu_rz, frameNumber, eulerAngles[2], 1);
856                                         
857                                         // Handles are corrected at the end, testhandles_ipocurve isnt needed yet
858 #endif
859                                 }
860                         }
861                 }
862         }
863 }
864
865
866 void    KX_BlenderSceneConverter::TestHandlesPhysicsObjectToAnimationIpo()
867 {
868
869         KX_SceneList* scenes = m_ketsjiEngine->CurrentScenes();
870         int numScenes = scenes->size();
871         int i;
872         for (i=0;i<numScenes;i++)
873         {
874                 KX_Scene* scene = scenes->at(i);
875                 //PHY_IPhysicsEnvironment* physEnv = scene->GetPhysicsEnvironment();
876                 CListValue* parentList = scene->GetRootParentList();
877                 int numObjects = parentList->GetCount();
878                 int g;
879                 for (g=0;g<numObjects;g++)
880                 {
881                         KX_GameObject* gameObj = (KX_GameObject*)parentList->GetValue(g);
882                         if (gameObj->IsDynamic())
883                         {
884                                 //KX_IPhysicsController* physCtrl = gameObj->GetPhysicsController();
885                                 
886                                 Object* blenderObject = gameObj->GetBlenderObject();
887                                 if (blenderObject && blenderObject->ipo)
888                                 {
889                                         // XXX animato
890 #if 0
891                                         Ipo* ipo = blenderObject->ipo;
892                                         
893                                         //create the curves, if not existing
894                                         //testhandles_ipocurve checks for NULL
895                                         testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"LocX"));
896                                         testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"LocY"));
897                                         testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"LocZ"));
898                                         testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"RotX"));
899                                         testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"RotY"));
900                                         testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"RotZ"));
901 #endif
902                                 }
903                         }
904
905                 }
906                 
907         
908         }
909
910
911
912 }
913
914 #ifdef WITH_PYTHON
915 PyObject *KX_BlenderSceneConverter::GetPyNamespace()
916 {
917         return m_ketsjiEngine->GetPyNamespace();
918 }
919 #endif
920
921 vector<Main*> &KX_BlenderSceneConverter::GetMainDynamic()
922 {
923         return m_DynamicMaggie;
924 }
925
926 Main* KX_BlenderSceneConverter::GetMainDynamicPath(const char *path)
927 {
928         for (vector<Main*>::iterator it=m_DynamicMaggie.begin(); !(it==m_DynamicMaggie.end()); it++)
929                 if(BLI_path_cmp((*it)->name, path) == 0)
930                         return *it;
931         
932         return NULL;
933 }
934
935 bool KX_BlenderSceneConverter::LinkBlendFileMemory(void *data, int length, const char *path, char *group, KX_Scene *scene_merge, char **err_str, short options)
936 {
937         BlendHandle *bpy_openlib = BLO_blendhandle_from_memory(data, length);
938
939         // Error checking is done in LinkBlendFile
940         return LinkBlendFile(bpy_openlib, path, group, scene_merge, err_str, options);
941 }
942
943 bool KX_BlenderSceneConverter::LinkBlendFilePath(const char *path, char *group, KX_Scene *scene_merge, char **err_str, short options)
944 {
945         BlendHandle *bpy_openlib = BLO_blendhandle_from_file((char *)path, NULL);
946
947         // Error checking is done in LinkBlendFile
948         return LinkBlendFile(bpy_openlib, path, group, scene_merge, err_str, options);
949 }
950
951 bool KX_BlenderSceneConverter::LinkBlendFile(BlendHandle *bpy_openlib, const char *path, char *group, KX_Scene *scene_merge, char **err_str, short options)
952 {
953         bContext *C;
954         Main *main_newlib; /* stored as a dynamic 'main' until we free it */
955         Main *main_tmp= NULL; /* created only for linking, then freed */
956         LinkNode *names = NULL;
957         int idcode= BKE_idcode_from_name(group);
958         short flag= 0; /* dont need any special options */
959         ReportList reports;
960         static char err_local[255];
961         
962         /* only scene and mesh supported right now */
963         if(idcode!=ID_SCE && idcode!=ID_ME &&idcode!=ID_AC) {
964                 snprintf(err_local, sizeof(err_local), "invalid ID type given \"%s\"\n", group);
965                 *err_str= err_local;
966                 BLO_blendhandle_close(bpy_openlib);
967                 return false;
968         }
969         
970         if(GetMainDynamicPath(path)) {
971                 snprintf(err_local, sizeof(err_local), "blend file already open \"%s\"\n", path);
972                 *err_str= err_local;
973                 BLO_blendhandle_close(bpy_openlib);
974                 return false;
975         }
976
977         if(bpy_openlib==NULL) {
978                 snprintf(err_local, sizeof(err_local), "could not open blendfile \"%s\"\n", path);
979                 *err_str= err_local;
980                 return false;
981         }
982         
983         main_newlib= (Main *)MEM_callocN( sizeof(Main), "BgeMain");
984         C= CTX_create();
985         CTX_data_main_set(C, main_newlib);
986         BKE_reports_init(&reports, RPT_STORE);  
987
988         /* here appending/linking starts */
989         main_tmp = BLO_library_append_begin(C, &bpy_openlib, (char *)path);
990
991         int totnames_dummy;
992         names = BLO_blendhandle_get_datablock_names( bpy_openlib, idcode, &totnames_dummy);
993         
994         int i=0;
995         LinkNode *n= names;
996         while(n) {
997                 BLO_library_append_named_part(C, main_tmp, &bpy_openlib, (char *)n->link, idcode, 0);
998                 n= (LinkNode *)n->next;
999                 i++;
1000         }
1001         BLI_linklist_free(names, free); /* free linklist *and* each node's data */
1002         
1003         BLO_library_append_end(C, main_tmp, &bpy_openlib, idcode, flag);
1004
1005         /* now do another round of linking for Scenes so all actions are properly loaded */
1006         if (idcode==ID_SCE && options & LIB_LOAD_LOAD_ACTIONS) {
1007                 main_tmp = BLO_library_append_begin(C, &bpy_openlib, (char *)path);
1008
1009                 int totnames_dummy;
1010                 names = BLO_blendhandle_get_datablock_names( bpy_openlib, ID_AC, &totnames_dummy);
1011         
1012                 int i=0;
1013                 LinkNode *n= names;
1014                 while(n) {
1015                         BLO_library_append_named_part(C, main_tmp, &bpy_openlib, (char *)n->link, ID_AC, 0);
1016                         n= (LinkNode *)n->next;
1017                         i++;
1018                 }
1019                 BLI_linklist_free(names, free); /* free linklist *and* each node's data */
1020         
1021                 BLO_library_append_end(C, main_tmp, &bpy_openlib, ID_AC, flag);
1022         }
1023         
1024         BLO_blendhandle_close(bpy_openlib);
1025         
1026         CTX_free(C);
1027         BKE_reports_clear(&reports);
1028         /* done linking */      
1029         
1030         /* needed for lookups*/
1031         GetMainDynamic().push_back(main_newlib);
1032         strncpy(main_newlib->name, path, sizeof(main_newlib->name));    
1033         
1034         
1035         if(idcode==ID_ME) {
1036                 /* Convert all new meshes into BGE meshes */
1037                 ID* mesh;
1038         
1039                 for(mesh= (ID *)main_newlib->mesh.first; mesh; mesh= (ID *)mesh->next ) {
1040                         if (options & LIB_LOAD_VERBOSE)
1041                                 printf("MeshName: %s\n", mesh->name+2);
1042                         RAS_MeshObject *meshobj = BL_ConvertMesh((Mesh *)mesh, NULL, scene_merge, this);
1043                         scene_merge->GetLogicManager()->RegisterMeshName(meshobj->GetName(),meshobj);
1044                 }
1045         }
1046         else if(idcode==ID_AC) {
1047                 /* Convert all actions */
1048                 ID *action;
1049
1050                 for(action= (ID *)main_newlib->action.first; action; action= (ID *)action->next) {
1051                         if (options & LIB_LOAD_VERBOSE)
1052                                 printf("ActionName: %s\n", action->name+2);
1053                         scene_merge->GetLogicManager()->RegisterActionName(action->name+2, action);
1054                 }
1055         }
1056         else if(idcode==ID_SCE) {               
1057                 /* Merge all new linked in scene into the existing one */
1058                 ID *scene;
1059                 for(scene= (ID *)main_newlib->scene.first; scene; scene= (ID *)scene->next ) {
1060                         if (options & LIB_LOAD_VERBOSE)
1061                                 printf("SceneName: %s\n", scene->name+2);
1062                         
1063                         /* merge into the base  scene */
1064                         KX_Scene* other= m_ketsjiEngine->CreateScene((Scene *)scene);
1065                         scene_merge->MergeScene(other);
1066                         
1067                         // RemoveScene(other); // Dont run this, it frees the entire scene converter data, just delete the scene
1068                         delete other;
1069                 }
1070
1071                 /* Now handle all the actions */
1072                 if (options & LIB_LOAD_LOAD_ACTIONS) {
1073                         ID *action;
1074
1075                         for(action= (ID *)main_newlib->action.first; action; action= (ID *)action->next) {
1076                                 if (options & LIB_LOAD_VERBOSE)
1077                                         printf("ActionName: %s\n", action->name+2);
1078                                 scene_merge->GetLogicManager()->RegisterActionName(action->name+2, action);
1079                         }
1080                 }
1081         }
1082         
1083         return true;
1084 }
1085
1086 /* Note m_map_*** are all ok and dont need to be freed
1087  * most are temp and NewRemoveObject frees m_map_gameobject_to_blender */
1088 bool KX_BlenderSceneConverter::FreeBlendFile(struct Main *maggie)
1089 {
1090         int maggie_index;
1091         int i=0;
1092
1093         if(maggie==NULL)
1094                 return false;
1095         
1096         /* tag all false except the one we remove */
1097         for (vector<Main*>::iterator it=m_DynamicMaggie.begin(); !(it==m_DynamicMaggie.end()); it++) {
1098                 Main *main= *it;
1099                 if(main != maggie) {
1100                         tag_main(main, 0);
1101                 }
1102                 else {
1103                         maggie_index= i;
1104                 }
1105                 i++;
1106         }
1107
1108         m_DynamicMaggie.erase(m_DynamicMaggie.begin() + maggie_index);
1109         tag_main(maggie, 1);
1110
1111
1112         /* free all tagged objects */
1113         KX_SceneList* scenes = m_ketsjiEngine->CurrentScenes();
1114         int numScenes = scenes->size();
1115
1116
1117         for (int scene_idx=0;scene_idx<numScenes;scene_idx++)
1118         {
1119                 KX_Scene* scene = scenes->at(scene_idx);
1120                 if(IS_TAGGED(scene->GetBlenderScene())) {
1121                         RemoveScene(scene); // XXX - not tested yet
1122                         scene_idx--;
1123                         numScenes--;
1124                 }
1125                 else {
1126                         
1127                         /* incase the mesh might be refered to later */
1128                         {
1129                                 GEN_Map<STR_HashedString,void*> &mapStringToMeshes = scene->GetLogicManager()->GetMeshMap();
1130                                 
1131                                 for(int i=0; i<mapStringToMeshes.size(); i++)
1132                                 {
1133                                         RAS_MeshObject *meshobj= (RAS_MeshObject *) *mapStringToMeshes.at(i);
1134                                         if(meshobj && IS_TAGGED(meshobj->GetMesh()))
1135                                         {       
1136                                                 STR_HashedString mn = meshobj->GetName();
1137                                                 mapStringToMeshes.remove(mn);
1138                                                 m_map_mesh_to_gamemesh.remove(CHashedPtr(meshobj->GetMesh()));
1139                                                 i--;
1140                                         }
1141                                 }
1142                         }
1143
1144                         /* Now unregister actions */
1145                         {
1146                                 GEN_Map<STR_HashedString,void*> &mapStringToActions = scene->GetLogicManager()->GetActionMap();
1147
1148                                 for(int i=0; i<mapStringToActions.size(); i++)
1149                                 {
1150                                         ID *action= (ID*) *mapStringToActions.at(i);
1151
1152                                         if(IS_TAGGED(action))
1153                                         {
1154                                                 STR_HashedString an = action->name+2;
1155                                                 mapStringToActions.remove(an);
1156                                                 i--;
1157                                         }
1158                                 }
1159                         }
1160                         
1161                         //scene->FreeTagged(); /* removed tagged objects and meshes*/
1162                         CListValue *obj_lists[] = {scene->GetObjectList(), scene->GetInactiveList(), NULL};
1163
1164                         for(int ob_ls_idx=0; obj_lists[ob_ls_idx]; ob_ls_idx++)
1165                         {
1166                                 CListValue *obs= obj_lists[ob_ls_idx];
1167                                 RAS_MeshObject* mesh;
1168
1169                                 for (int ob_idx = 0; ob_idx < obs->GetCount(); ob_idx++)
1170                                 {
1171                                         KX_GameObject* gameobj = (KX_GameObject*)obs->GetValue(ob_idx);
1172                                         if(IS_TAGGED(gameobj->GetBlenderObject())) {
1173
1174                                                 int size_before = obs->GetCount();
1175
1176                                                 /* Eventually calls RemoveNodeDestructObject
1177                                                  * frees m_map_gameobject_to_blender from UnregisterGameObject */
1178                                                 scene->RemoveObject(gameobj);
1179
1180                                                 if(size_before != obs->GetCount())
1181                                                         ob_idx--;
1182                                                 else {
1183                                                         printf("ERROR COULD NOT REMOVE \"%s\"\n", gameobj->GetName().ReadPtr());
1184                                                 }
1185                                         }
1186                                         else {
1187                                                 /* free the mesh, we could be referecing a linked one! */
1188                                                 int mesh_index= gameobj->GetMeshCount();
1189                                                 while(mesh_index--) {
1190                                                         mesh= gameobj->GetMesh(mesh_index);
1191                                                         if(IS_TAGGED(mesh->GetMesh())) {
1192                                                                 gameobj->RemoveMeshes(); /* XXX - slack, should only remove meshes that are library items but mostly objects only have 1 mesh */
1193                                                                 break;
1194                                                         }
1195                                                 }
1196
1197                                                 /* make sure action actuators are not referencing tagged actions */
1198                                                 for (int act_idx=0; act_idx<gameobj->GetActuators().size(); act_idx++)
1199                                                 {
1200                                                         if (gameobj->GetActuators()[act_idx]->IsType(SCA_IActuator::KX_ACT_ACTION))
1201                                                         {
1202                                                                 BL_ActionActuator *act = (BL_ActionActuator*)gameobj->GetActuators()[act_idx];
1203                                                                 if(IS_TAGGED(act->GetAction()))
1204                                                                         act->SetAction(NULL);
1205                                                         }
1206                                                 }
1207                                         }
1208                                 }
1209                         }
1210                 }
1211         }
1212
1213
1214         int size;
1215
1216         // delete the entities of this scene
1217         /* TODO - */
1218         /*
1219         vector<pair<KX_Scene*,KX_WorldInfo*> >::iterator worldit;
1220         size = m_worldinfos.size();
1221         for (i=0, worldit=m_worldinfos.begin(); i<size; ) {
1222                 if ((*worldit).second) {
1223                         delete (*worldit).second;
1224                         *worldit = m_worldinfos.back();
1225                         m_worldinfos.pop_back();
1226                         size--;
1227                 } else {
1228                         i++;
1229                         worldit++;
1230                 }
1231         }*/
1232
1233
1234         /* Worlds dont reference original blender data so we need to make a set from them */
1235         typedef std::set<KX_WorldInfo*> KX_WorldInfoSet;
1236         KX_WorldInfoSet worldset;
1237         for (int scene_idx=0;scene_idx<numScenes;scene_idx++)
1238         {
1239                 KX_Scene* scene = scenes->at(scene_idx);
1240                 if(scene->GetWorldInfo())
1241                         worldset.insert( scene->GetWorldInfo() );
1242         }
1243
1244         vector<pair<KX_Scene*,KX_WorldInfo*> >::iterator worldit;
1245         size = m_worldinfos.size();
1246         for (i=0, worldit=m_worldinfos.begin(); i<size; ) {
1247                 if ((*worldit).second && (worldset.count((*worldit).second)) == 0) {
1248                         delete (*worldit).second;
1249                         *worldit = m_worldinfos.back();
1250                         m_worldinfos.pop_back();
1251                         size--;
1252                 } else {
1253                         i++;
1254                         worldit++;
1255                 }
1256         }
1257         worldset.clear();
1258         /* done freeing the worlds */
1259
1260
1261
1262
1263         vector<pair<KX_Scene*,RAS_IPolyMaterial*> >::iterator polymit;
1264         size = m_polymaterials.size();
1265
1266
1267
1268         for (i=0, polymit=m_polymaterials.begin(); i<size; ) {
1269                 RAS_IPolyMaterial *mat= (*polymit).second;
1270                 Material *bmat= NULL;
1271
1272                 /* Why do we need to check for RAS_BLENDERMAT if both are cast to a (PyObject*)? - Campbell */
1273                 if(mat->GetFlag() & RAS_BLENDERMAT) {
1274                         KX_BlenderMaterial *bl_mat = static_cast<KX_BlenderMaterial*>(mat);
1275                         bmat= bl_mat->GetBlenderMaterial();
1276
1277                 } else {
1278                         KX_PolygonMaterial *kx_mat = static_cast<KX_PolygonMaterial*>(mat);
1279                         bmat= kx_mat->GetBlenderMaterial();
1280                 }
1281
1282                 if (IS_TAGGED(bmat)) {
1283                         /* only remove from bucket */
1284                         ((*polymit).first)->GetBucketManager()->RemoveMaterial(mat);
1285                 }
1286
1287                 i++;
1288                 polymit++;
1289         }
1290
1291
1292
1293         for (i=0, polymit=m_polymaterials.begin(); i<size; ) {
1294                 RAS_IPolyMaterial *mat= (*polymit).second;
1295                 Material *bmat= NULL;
1296
1297                 /* Why do we need to check for RAS_BLENDERMAT if both are cast to a (PyObject*)? - Campbell */
1298                 if(mat->GetFlag() & RAS_BLENDERMAT) {
1299                         KX_BlenderMaterial *bl_mat = static_cast<KX_BlenderMaterial*>(mat);
1300                         bmat= bl_mat->GetBlenderMaterial();
1301
1302                 } else {
1303                         KX_PolygonMaterial *kx_mat = static_cast<KX_PolygonMaterial*>(mat);
1304                         bmat= kx_mat->GetBlenderMaterial();
1305                 }
1306
1307                 if(bmat) {
1308                         //printf("FOUND MAT '%s' !!! ", ((ID*)bmat)->name+2);
1309                 }
1310                 else {
1311                         //printf("LOST MAT  !!!");
1312                 }
1313
1314                 if (IS_TAGGED(bmat)) {
1315
1316                         delete (*polymit).second;
1317                         *polymit = m_polymaterials.back();
1318                         m_polymaterials.pop_back();
1319                         size--;
1320                         //printf("tagged !\n");
1321                 } else {
1322                         i++;
1323                         polymit++;
1324                         //printf("(un)tagged !\n");
1325                 }
1326         }
1327
1328         vector<pair<KX_Scene*,BL_Material*> >::iterator matit;
1329         size = m_materials.size();
1330         for (i=0, matit=m_materials.begin(); i<size; ) {
1331                 BL_Material *mat= (*matit).second;
1332                 if (IS_TAGGED(mat->material)) {
1333                         delete (*matit).second;
1334                         *matit = m_materials.back();
1335                         m_materials.pop_back();
1336                         size--;
1337                 } else {
1338                         i++;
1339                         matit++;
1340                 }
1341         }
1342
1343         vector<pair<KX_Scene*,RAS_MeshObject*> >::iterator meshit;
1344         size = m_meshobjects.size();
1345         for (i=0, meshit=m_meshobjects.begin(); i<size; ) {
1346                 RAS_MeshObject *me= (*meshit).second;
1347                 if (IS_TAGGED(me->GetMesh())) {
1348                         delete (*meshit).second;
1349                         *meshit = m_meshobjects.back();
1350                         m_meshobjects.pop_back();
1351                         size--;
1352                 } else {
1353                         i++;
1354                         meshit++;
1355                 }
1356         }
1357
1358         free_main(maggie);
1359
1360         return true;
1361 }
1362
1363 bool KX_BlenderSceneConverter::FreeBlendFile(const char *path)
1364 {
1365         return FreeBlendFile(GetMainDynamicPath(path));
1366 }
1367
1368 bool KX_BlenderSceneConverter::MergeScene(KX_Scene *to, KX_Scene *from)
1369 {
1370
1371         {
1372                 vector<pair<KX_Scene*,KX_WorldInfo*> >::iterator itp = m_worldinfos.begin();
1373                 while (itp != m_worldinfos.end()) {
1374                         if ((*itp).first==from)
1375                                 (*itp).first= to;
1376                         itp++;
1377                 }
1378         }
1379
1380         {
1381                 vector<pair<KX_Scene*,RAS_IPolyMaterial*> >::iterator itp = m_polymaterials.begin();
1382                 while (itp != m_polymaterials.end()) {
1383                         if ((*itp).first==from) {
1384                                 (*itp).first= to;
1385
1386                                 /* also switch internal data */
1387                                 RAS_IPolyMaterial*mat= (*itp).second;
1388                                 mat->Replace_IScene(to);
1389                         }
1390                         itp++;
1391                 }
1392         }
1393
1394         {
1395                 vector<pair<KX_Scene*,RAS_MeshObject*> >::iterator itp = m_meshobjects.begin();
1396                 while (itp != m_meshobjects.end()) {
1397                         if ((*itp).first==from)
1398                                 (*itp).first= to;
1399                         itp++;
1400                 }
1401         }
1402
1403         {
1404                 vector<pair<KX_Scene*,BL_Material*> >::iterator itp = m_materials.begin();
1405                 while (itp != m_materials.end()) {
1406                         if ((*itp).first==from)
1407                                 (*itp).first= to;
1408                         itp++;
1409                 }
1410         }
1411         
1412         return true;
1413 }
1414
1415 /* This function merges a mesh from the current scene into another main
1416  * it does not convert */
1417 RAS_MeshObject *KX_BlenderSceneConverter::ConvertMeshSpecial(KX_Scene* kx_scene, Main *maggie, const char *name)
1418 {
1419         /* Find a mesh in the current main */
1420         ID *me= static_cast<ID *>(BLI_findstring(&m_maggie->mesh, name, offsetof(ID, name) + 2));
1421         
1422         if(me==NULL) {
1423                 printf("Could not be found \"%s\"\n", name);
1424                 return NULL;
1425         }
1426         
1427         /* Watch this!, if its used in the original scene can cause big troubles */
1428         if(me->us > 0) {
1429                 printf("Mesh has a user \"%s\"\n", name);
1430                 me = (ID*)copy_mesh((Mesh*)me);
1431                 me->us--;
1432         }
1433         BLI_remlink(&m_maggie->mesh, me); /* even if we made the copy it needs to be removed */
1434         BLI_addtail(&maggie->mesh, me);
1435
1436         
1437         /* Must copy the materials this uses else we cant free them */
1438         {
1439                 Mesh *mesh= (Mesh *)me;
1440                 
1441                 /* ensure all materials are tagged */
1442                 for(int i=0; i<mesh->totcol; i++)
1443                         if(mesh->mat[i])
1444                                 mesh->mat[i]->id.flag &= ~LIB_DOIT;
1445                 
1446                 for(int i=0; i<mesh->totcol; i++)
1447                 {
1448                         Material *mat_old= mesh->mat[i];
1449                         
1450                         /* if its tagged its a replaced material */
1451                         if(mat_old && (mat_old->id.flag & LIB_DOIT)==0)
1452                         {
1453                                 Material *mat_old= mesh->mat[i];
1454                                 Material *mat_new= copy_material( mat_old );
1455                                 
1456                                 mat_new->id.flag |= LIB_DOIT;
1457                                 mat_old->id.us--;
1458                                 
1459                                 BLI_remlink(&m_maggie->mat, mat_new);
1460                                 BLI_addtail(&maggie->mat, mat_new);
1461                                 
1462                                 mesh->mat[i]= mat_new;
1463                                 
1464                                 /* the same material may be used twice */
1465                                 for(int j=i+1; j<mesh->totcol; j++)
1466                                 {
1467                                         if(mesh->mat[j]==mat_old)
1468                                         {
1469                                                 mesh->mat[j]= mat_new;
1470                                                 mat_new->id.us++;
1471                                                 mat_old->id.us--;
1472                                         }
1473                                 }
1474                         }
1475                 }
1476         }
1477         
1478         RAS_MeshObject *meshobj = BL_ConvertMesh((Mesh *)me, NULL, kx_scene, this);
1479         kx_scene->GetLogicManager()->RegisterMeshName(meshobj->GetName(),meshobj);
1480         m_map_mesh_to_gamemesh.clear(); /* This is at runtime so no need to keep this, BL_ConvertMesh adds */
1481         return meshobj;
1482 }