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