svn merge -r40197:40311 ^/trunk/blender
[blender.git] / source / gameengine / Ketsji / KX_Scene.cpp
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  * Ketsji scene. Holds references to all scene data.
29  */
30
31 /** \file gameengine/Ketsji/KX_Scene.cpp
32  *  \ingroup ketsji
33  */
34
35
36 #if defined(WIN32) && !defined(FREE_WINDOWS)
37 #pragma warning (disable : 4786)
38 #endif //WIN32
39
40 #include "KX_Scene.h"
41 #include "KX_PythonInit.h"
42 #include "MT_assert.h"
43 #include "KX_KetsjiEngine.h"
44 #include "KX_BlenderMaterial.h"
45 #include "RAS_IPolygonMaterial.h"
46 #include "ListValue.h"
47 #include "SCA_LogicManager.h"
48 #include "SCA_TimeEventManager.h"
49 //#include "SCA_AlwaysEventManager.h"
50 //#include "SCA_RandomEventManager.h"
51 //#include "KX_RayEventManager.h"
52 #include "KX_TouchEventManager.h"
53 #include "SCA_KeyboardManager.h"
54 #include "SCA_MouseManager.h"
55 //#include "SCA_PropertyEventManager.h"
56 #include "SCA_ActuatorEventManager.h"
57 #include "SCA_BasicEventManager.h"
58 #include "KX_Camera.h"
59 #include "SCA_JoystickManager.h"
60
61 #include "RAS_MeshObject.h"
62
63 #include "RAS_IRasterizer.h"
64 #include "RAS_BucketManager.h"
65
66 #include "FloatValue.h"
67 #include "SCA_IController.h"
68 #include "SCA_IActuator.h"
69 #include "SG_Node.h"
70 #include "BL_System.h"
71 #include "SG_Controller.h"
72 #include "SG_IObject.h"
73 #include "SG_Tree.h"
74 #include "DNA_group_types.h"
75 #include "DNA_scene_types.h"
76
77 #include "KX_SG_NodeRelationships.h"
78
79 #include "KX_NetworkEventManager.h"
80 #include "NG_NetworkScene.h"
81 #include "PHY_IPhysicsEnvironment.h"
82 #include "KX_IPhysicsController.h"
83 #include "PHY_IGraphicController.h"
84 #include "KX_BlenderSceneConverter.h"
85 #include "KX_MotionState.h"
86
87 #include "BL_ModifierDeformer.h"
88 #include "BL_ShapeDeformer.h"
89 #include "BL_DeformableGameObject.h"
90 #include "KX_ObstacleSimulation.h"
91
92 #ifdef USE_BULLET
93 #include "KX_SoftBodyDeformer.h"
94 #include "KX_ConvertPhysicsObject.h"
95 #include "CcdPhysicsEnvironment.h"
96 #include "CcdPhysicsController.h"
97 #endif
98
99 #include "KX_Light.h"
100
101 #include <stdio.h>
102
103 void* KX_SceneReplicationFunc(SG_IObject* node,void* gameobj,void* scene)
104 {
105         KX_GameObject* replica = ((KX_Scene*)scene)->AddNodeReplicaObject(node,(KX_GameObject*)gameobj);
106
107         if(replica)
108                 replica->Release();
109
110         return (void*)replica;
111 }
112
113 void* KX_SceneDestructionFunc(SG_IObject* node,void* gameobj,void* scene)
114 {
115         ((KX_Scene*)scene)->RemoveNodeDestructObject(node,(KX_GameObject*)gameobj);
116
117         return NULL;
118 };
119
120 bool KX_Scene::KX_ScenegraphUpdateFunc(SG_IObject* node,void* gameobj,void* scene)
121 {
122         return ((SG_Node*)node)->Schedule(((KX_Scene*)scene)->m_sghead);
123 }
124
125 bool KX_Scene::KX_ScenegraphRescheduleFunc(SG_IObject* node,void* gameobj,void* scene)
126 {
127         return ((SG_Node*)node)->Reschedule(((KX_Scene*)scene)->m_sghead);
128 }
129
130 SG_Callbacks KX_Scene::m_callbacks = SG_Callbacks(
131         KX_SceneReplicationFunc,
132         KX_SceneDestructionFunc,
133         KX_GameObject::UpdateTransformFunc,
134         KX_Scene::KX_ScenegraphUpdateFunc,
135         KX_Scene::KX_ScenegraphRescheduleFunc);
136
137 // temporarily var until there is a button in the userinterface
138 // (defined in KX_PythonInit.cpp)
139 extern bool gUseVisibilityTemp;
140
141 KX_Scene::KX_Scene(class SCA_IInputDevice* keyboarddevice,
142                                    class SCA_IInputDevice* mousedevice,
143                                    class NG_NetworkDeviceInterface *ndi,
144                                    const STR_String& sceneName,
145                                    Scene *scene,
146                                    class RAS_ICanvas* canvas): 
147         PyObjectPlus(),
148         m_keyboardmgr(NULL),
149         m_mousemgr(NULL),
150         m_sceneConverter(NULL),
151         m_physicsEnvironment(0),
152         m_sceneName(sceneName),
153         m_networkDeviceInterface(ndi),
154         m_active_camera(NULL),
155         m_ueberExecutionPriority(0),
156         m_blenderScene(scene)
157 {
158         m_suspendedtime = 0.0;
159         m_suspendeddelta = 0.0;
160
161         m_dbvt_culling = false;
162         m_dbvt_occlusion_res = 0;
163         m_activity_culling = false;
164         m_suspend = false;
165         m_isclearingZbuffer = true;
166         m_tempObjectList = new CListValue();
167         m_objectlist = new CListValue();
168         m_parentlist = new CListValue();
169         m_lightlist= new CListValue();
170         m_inactivelist = new CListValue();
171         m_euthanasyobjects = new CListValue();
172         m_animatedlist = new CListValue();
173
174         m_logicmgr = new SCA_LogicManager();
175         
176         m_timemgr = new SCA_TimeEventManager(m_logicmgr);
177         m_keyboardmgr = new SCA_KeyboardManager(m_logicmgr,keyboarddevice);
178         m_mousemgr = new SCA_MouseManager(m_logicmgr,mousedevice, canvas);
179         
180         //SCA_AlwaysEventManager* alwaysmgr = new SCA_AlwaysEventManager(m_logicmgr);
181         //SCA_PropertyEventManager* propmgr = new SCA_PropertyEventManager(m_logicmgr);
182         SCA_ActuatorEventManager* actmgr = new SCA_ActuatorEventManager(m_logicmgr);
183         //SCA_RandomEventManager* rndmgr = new SCA_RandomEventManager(m_logicmgr);
184         SCA_BasicEventManager* basicmgr = new SCA_BasicEventManager(m_logicmgr);
185         //KX_RayEventManager* raymgr = new KX_RayEventManager(m_logicmgr);
186
187         KX_NetworkEventManager* netmgr = new KX_NetworkEventManager(m_logicmgr, ndi);
188         
189         
190
191         //m_logicmgr->RegisterEventManager(alwaysmgr);
192         //m_logicmgr->RegisterEventManager(propmgr);
193         m_logicmgr->RegisterEventManager(actmgr);
194         m_logicmgr->RegisterEventManager(m_keyboardmgr);
195         m_logicmgr->RegisterEventManager(m_mousemgr);
196         m_logicmgr->RegisterEventManager(m_timemgr);
197         //m_logicmgr->RegisterEventManager(rndmgr);
198         //m_logicmgr->RegisterEventManager(raymgr);
199         m_logicmgr->RegisterEventManager(netmgr);
200         m_logicmgr->RegisterEventManager(basicmgr);
201
202
203         SYS_SystemHandle hSystem = SYS_GetSystem();
204         bool nojoystick= SYS_GetCommandLineInt(hSystem,"nojoystick",0);
205         if (!nojoystick)
206         {
207                 SCA_JoystickManager *joymgr     = new SCA_JoystickManager(m_logicmgr);
208                 m_logicmgr->RegisterEventManager(joymgr);
209         }
210
211         MT_assert (m_networkDeviceInterface != NULL);
212         m_networkScene = new NG_NetworkScene(m_networkDeviceInterface);
213         
214         m_rootnode = NULL;
215
216         m_bucketmanager=new RAS_BucketManager();
217         
218         bool showObstacleSimulation = scene->gm.flag & GAME_SHOW_OBSTACLE_SIMULATION;
219         switch (scene->gm.obstacleSimulation)
220         {
221         case OBSTSIMULATION_TOI_rays:
222                 m_obstacleSimulation = new KX_ObstacleSimulationTOI_rays((MT_Scalar)scene->gm.levelHeight, showObstacleSimulation);
223                 break;
224         case OBSTSIMULATION_TOI_cells:
225                 m_obstacleSimulation = new KX_ObstacleSimulationTOI_cells((MT_Scalar)scene->gm.levelHeight, showObstacleSimulation);
226                 break;
227         default:
228                 m_obstacleSimulation = NULL;
229         }
230         
231 #ifdef WITH_PYTHON
232         m_attr_dict = PyDict_New(); /* new ref */
233         m_draw_call_pre = NULL;
234         m_draw_call_post = NULL;
235 #endif
236 }
237
238
239
240 KX_Scene::~KX_Scene()
241 {
242         // The release of debug properties used to be in SCA_IScene::~SCA_IScene
243         // It's still there but we remove all properties here otherwise some
244         // reference might be hanging and causing late release of objects
245         RemoveAllDebugProperties();
246
247         while (GetRootParentList()->GetCount() > 0) 
248         {
249                 KX_GameObject* parentobj = (KX_GameObject*) GetRootParentList()->GetValue(0);
250                 this->RemoveObject(parentobj);
251         }
252
253         if (m_obstacleSimulation)
254                 delete m_obstacleSimulation;
255
256         if(m_objectlist)
257                 m_objectlist->Release();
258
259         if (m_parentlist)
260                 m_parentlist->Release();
261         
262         if (m_inactivelist)
263                 m_inactivelist->Release();
264
265         if (m_lightlist)
266                 m_lightlist->Release();
267         
268         if (m_tempObjectList)
269                 m_tempObjectList->Release();
270
271         if (m_euthanasyobjects)
272                 m_euthanasyobjects->Release();
273
274         if (m_animatedlist)
275                 m_animatedlist->Release();
276
277         if (m_logicmgr)
278                 delete m_logicmgr;
279
280         if (m_physicsEnvironment)
281                 delete m_physicsEnvironment;
282
283         if (m_networkScene)
284                 delete m_networkScene;
285         
286         if (m_bucketmanager)
287         {
288                 delete m_bucketmanager;
289         }
290
291 #ifdef WITH_PYTHON
292         PyDict_Clear(m_attr_dict);
293         /* Py_CLEAR: Py_DECREF's and NULL's */
294         Py_CLEAR(m_attr_dict);
295
296         /* these may be NULL but the macro checks */
297         Py_CLEAR(m_draw_call_pre);
298         Py_CLEAR(m_draw_call_post);
299 #endif
300 }
301
302 RAS_BucketManager* KX_Scene::GetBucketManager()
303 {
304         return m_bucketmanager;
305 }
306
307
308 CListValue* KX_Scene::GetTempObjectList()
309 {
310         return m_tempObjectList;
311 }
312
313 CListValue* KX_Scene::GetObjectList()
314 {
315         return m_objectlist;
316 }
317
318
319 CListValue* KX_Scene::GetRootParentList()
320 {
321         return m_parentlist;
322 }
323
324 CListValue* KX_Scene::GetInactiveList()
325 {
326         return m_inactivelist;
327 }
328
329
330
331 CListValue* KX_Scene::GetLightList()
332 {
333         return m_lightlist;
334 }
335
336 SCA_LogicManager* KX_Scene::GetLogicManager()
337 {
338         return m_logicmgr;
339 }
340
341 SCA_TimeEventManager* KX_Scene::GetTimeEventManager()
342 {
343         return m_timemgr;
344 }
345
346
347
348  
349 list<class KX_Camera*>* KX_Scene::GetCameras()
350 {
351         return &m_cameras;
352 }
353
354 list<class KX_FontObject*>* KX_Scene::GetFonts()
355 {
356         return &m_fonts;
357 }
358
359 void KX_Scene::SetFramingType(RAS_FrameSettings & frame_settings)
360 {
361         m_frame_settings = frame_settings;
362 };
363
364 /**
365  * Return a const reference to the framing 
366  * type set by the above call.
367  * The contents are not guarenteed to be sensible
368  * if you don't call the above function.
369  */
370 const RAS_FrameSettings& KX_Scene::GetFramingType() const 
371 {
372         return m_frame_settings;
373 };      
374
375
376
377 /**
378  * Store the current scene's viewport on the 
379  * game engine canvas.
380  */
381 void KX_Scene::SetSceneViewport(const RAS_Rect &viewport)
382 {
383         m_viewport = viewport;
384 }
385
386
387
388 const RAS_Rect& KX_Scene::GetSceneViewport() const 
389 {
390         return m_viewport;
391 }
392
393
394
395 void KX_Scene::SetWorldInfo(class KX_WorldInfo* worldinfo)
396 {
397         m_worldinfo = worldinfo;
398 }
399
400
401
402 class KX_WorldInfo* KX_Scene::GetWorldInfo()
403 {
404         return m_worldinfo;
405 }
406
407
408 const STR_String& KX_Scene::GetName()
409 {
410         return m_sceneName;
411 }
412
413
414 void KX_Scene::Suspend()
415 {
416         m_suspend = true;
417 }
418
419 void KX_Scene::Resume()
420 {
421         m_suspend = false;
422 }
423
424 void KX_Scene::SetActivityCulling(bool b)
425 {
426         m_activity_culling = b;
427 }
428
429 bool KX_Scene::IsSuspended()
430 {
431         return m_suspend;
432 }
433
434 bool KX_Scene::IsClearingZBuffer()
435 {
436         return m_isclearingZbuffer;
437 }
438
439 void KX_Scene::EnableZBufferClearing(bool isclearingZbuffer)
440 {
441         m_isclearingZbuffer = isclearingZbuffer;
442 }
443
444 void KX_Scene::RemoveNodeDestructObject(class SG_IObject* node,class CValue* gameobj)
445 {
446         KX_GameObject* orgobj = (KX_GameObject*)gameobj;        
447         if (NewRemoveObject(orgobj) != 0)
448         {
449                 // object is not yet deleted because a reference is hanging somewhere.
450                 // This should not happen anymore since we use proxy object for Python
451                 // confident enough to put an assert?
452                 //assert(false);
453                 printf("Zombie object! name=%s\n", orgobj->GetName().ReadPtr());
454                 orgobj->SetSGNode(NULL);
455                 PHY_IGraphicController* ctrl = orgobj->GetGraphicController();
456                 if (ctrl)
457                 {
458                         // a graphic controller is set, we must delete it as the node will be deleted
459                         delete ctrl;
460                         orgobj->SetGraphicController(NULL);
461                 }
462         }
463         if (node)
464                 delete node;
465 }
466
467 KX_GameObject* KX_Scene::AddNodeReplicaObject(class SG_IObject* node, class CValue* gameobj)
468 {
469         // for group duplication, limit the duplication of the hierarchy to the
470         // objects that are part of the group. 
471         if (!IsObjectInGroup(gameobj))
472                 return NULL;
473         
474         KX_GameObject* orgobj = (KX_GameObject*)gameobj;
475         KX_GameObject* newobj = (KX_GameObject*)orgobj->GetReplica();
476         m_map_gameobject_to_replica.insert(orgobj, newobj);
477
478         // also register 'timers' (time properties) of the replica
479         int numprops = newobj->GetPropertyCount();
480
481         for (int i = 0; i < numprops; i++)
482         {
483                 CValue* prop = newobj->GetProperty(i);
484
485                 if (prop->GetProperty("timer"))
486                         this->m_timemgr->AddTimeProperty(prop);
487         }
488
489         if (node)
490         {
491                 newobj->SetSGNode((SG_Node*)node);
492         }
493         else
494         {
495                 m_rootnode = new SG_Node(newobj,this,KX_Scene::m_callbacks);
496         
497                 // this fixes part of the scaling-added object bug
498                 SG_Node* orgnode = orgobj->GetSGNode();
499                 m_rootnode->SetLocalScale(orgnode->GetLocalScale());
500                 m_rootnode->SetLocalPosition(orgnode->GetLocalPosition());
501                 m_rootnode->SetLocalOrientation(orgnode->GetLocalOrientation());
502
503                 // define the relationship between this node and it's parent.
504                 KX_NormalParentRelation * parent_relation = 
505                         KX_NormalParentRelation::New();
506                 m_rootnode->SetParentRelation(parent_relation);
507
508                 newobj->SetSGNode(m_rootnode);
509         }
510         
511         SG_IObject* replicanode = newobj->GetSGNode();
512 //      SG_Node* rootnode = (replicanode == m_rootnode ? NULL : m_rootnode);
513
514         replicanode->SetSGClientObject(newobj);
515
516         // this is the list of object that are send to the graphics pipeline
517         m_objectlist->Add(newobj->AddRef());
518         if (newobj->GetGameObjectType()==SCA_IObject::OBJ_LIGHT)
519                 m_lightlist->Add(newobj->AddRef());
520         newobj->AddMeshUser();
521
522         // logic cannot be replicated, until the whole hierarchy is replicated.
523         m_logicHierarchicalGameObjects.push_back(newobj);
524         //replicate controllers of this node
525         SGControllerList        scenegraphcontrollers = orgobj->GetSGNode()->GetSGControllerList();
526         replicanode->RemoveAllControllers();
527         SGControllerList::iterator cit;
528         //int numcont = scenegraphcontrollers.size();
529         
530         for (cit = scenegraphcontrollers.begin();!(cit==scenegraphcontrollers.end());++cit)
531         {
532                 // controller replication is quite complicated
533                 // only replicate ipo and physics controller for now
534
535                 SG_Controller* replicacontroller = (*cit)->GetReplica((SG_Node*) replicanode);
536                 if (replicacontroller)
537                 {
538                         replicacontroller->SetObject(replicanode);
539                         replicanode->AddSGController(replicacontroller);
540                 }
541         }
542         // replicate graphic controller
543         if (orgobj->GetGraphicController())
544         {
545                 PHY_IMotionState* motionstate = new KX_MotionState(newobj->GetSGNode());
546                 PHY_IGraphicController* newctrl = orgobj->GetGraphicController()->GetReplica(motionstate);
547                 newctrl->setNewClientInfo(newobj->getClientInfo());
548                 newobj->SetGraphicController(newctrl);
549         }
550         return newobj;
551 }
552
553
554
555 // before calling this method KX_Scene::ReplicateLogic(), make sure to
556 // have called 'GameObject::ReParentLogic' for each object this
557 // hierarchy that's because first ALL bricks must exist in the new
558 // replica of the hierarchy in order to make cross-links work properly
559 // !
560 // It is VERY important that the order of sensors and actuators in
561 // the replicated object is preserved: it is used to reconnect the logic.
562 // This method is more robust then using the bricks name in case of complex 
563 // group replication. The replication of logic bricks is done in 
564 // SCA_IObject::ReParentLogic(), make sure it preserves the order of the bricks.
565 void KX_Scene::ReplicateLogic(KX_GameObject* newobj)
566 {
567         // also relink the controller to sensors/actuators
568         SCA_ControllerList& controllers = newobj->GetControllers();
569         //SCA_SensorList&     sensors     = newobj->GetSensors();
570         //SCA_ActuatorList&   actuators   = newobj->GetActuators();
571
572         for (SCA_ControllerList::iterator itc = controllers.begin(); !(itc==controllers.end());itc++)
573         {
574                 SCA_IController* cont = (*itc);
575                 cont->SetUeberExecutePriority(m_ueberExecutionPriority);
576                 vector<SCA_ISensor*> linkedsensors = cont->GetLinkedSensors();
577                 vector<SCA_IActuator*> linkedactuators = cont->GetLinkedActuators();
578
579                 // disconnect the sensors and actuators
580                 // do it directly on the list at this controller is not connected to anything at this stage
581                 cont->GetLinkedSensors().clear();
582                 cont->GetLinkedActuators().clear();
583                 
584                 // now relink each sensor
585                 for (vector<SCA_ISensor*>::iterator its = linkedsensors.begin();!(its==linkedsensors.end());its++)
586                 {
587                         SCA_ISensor* oldsensor = (*its);
588                         SCA_IObject* oldsensorobj = oldsensor->GetParent();
589                         SCA_IObject* newsensorobj = NULL;
590                 
591                         // the original owner of the sensor has been replicated?
592                         void **h_obj = m_map_gameobject_to_replica[oldsensorobj];
593                         if (h_obj)
594                                 newsensorobj = (SCA_IObject*)(*h_obj);
595                         if (!newsensorobj)
596                         {
597                                 // no, then the sensor points outside the hierachy, keep it the same
598                                 if (m_objectlist->SearchValue(oldsensorobj))
599                                         // only replicate links that points to active objects
600                                         m_logicmgr->RegisterToSensor(cont,oldsensor);
601                         }
602                         else
603                         {
604                                 // yes, then the new sensor has the same position
605                                 SCA_SensorList& sensorlist = oldsensorobj->GetSensors();
606                                 SCA_SensorList::iterator sit;
607                                 SCA_ISensor* newsensor = NULL;
608                                 int sensorpos;
609
610                                 for (sensorpos=0, sit=sensorlist.begin(); sit!=sensorlist.end(); sit++, sensorpos++)
611                                 {
612                                         if ((*sit) == oldsensor) 
613                                         {
614                                                 newsensor = newsensorobj->GetSensors().at(sensorpos);
615                                                 break;
616                                         }
617                                 }
618                                 assert(newsensor != NULL);
619                                 m_logicmgr->RegisterToSensor(cont,newsensor);
620                         }
621                 }
622                 
623                 // now relink each actuator
624                 for (vector<SCA_IActuator*>::iterator ita = linkedactuators.begin();!(ita==linkedactuators.end());ita++)
625                 {
626                         SCA_IActuator* oldactuator = (*ita);
627                         SCA_IObject* oldactuatorobj = oldactuator->GetParent();
628                         SCA_IObject* newactuatorobj = NULL;
629
630                         // the original owner of the sensor has been replicated?
631                         void **h_obj = m_map_gameobject_to_replica[oldactuatorobj];
632                         if (h_obj)
633                                 newactuatorobj = (SCA_IObject*)(*h_obj);
634
635                         if (!newactuatorobj)
636                         {
637                                 // no, then the sensor points outside the hierachy, keep it the same
638                                 if (m_objectlist->SearchValue(oldactuatorobj))
639                                         // only replicate links that points to active objects
640                                         m_logicmgr->RegisterToActuator(cont,oldactuator);
641                         }
642                         else
643                         {
644                                 // yes, then the new sensor has the same position
645                                 SCA_ActuatorList& actuatorlist = oldactuatorobj->GetActuators();
646                                 SCA_ActuatorList::iterator ait;
647                                 SCA_IActuator* newactuator = NULL;
648                                 int actuatorpos;
649
650                                 for (actuatorpos=0, ait=actuatorlist.begin(); ait!=actuatorlist.end(); ait++, actuatorpos++)
651                                 {
652                                         if ((*ait) == oldactuator) 
653                                         {
654                                                 newactuator = newactuatorobj->GetActuators().at(actuatorpos);
655                                                 break;
656                                         }
657                                 }
658                                 assert(newactuator != NULL);
659                                 m_logicmgr->RegisterToActuator(cont,newactuator);
660                                 newactuator->SetUeberExecutePriority(m_ueberExecutionPriority);
661                         }
662                 }
663         }
664         // ready to set initial state
665         newobj->ResetState();
666 }
667
668 void KX_Scene::DupliGroupRecurse(CValue* obj, int level)
669 {
670         KX_GameObject* groupobj = (KX_GameObject*) obj;
671         KX_GameObject* replica;
672         KX_GameObject* gameobj;
673         Object* blgroupobj = groupobj->GetBlenderObject();
674         Group* group;
675         GroupObject *go;
676         vector<KX_GameObject*> duplilist;
677
678         if (!groupobj->GetSGNode() ||
679                 !groupobj->IsDupliGroup() ||
680                 level>MAX_DUPLI_RECUR)
681                 return;
682
683         // we will add one group at a time
684         m_logicHierarchicalGameObjects.clear();
685         m_map_gameobject_to_replica.clear();
686         m_ueberExecutionPriority++;
687         // for groups will do something special: 
688         // we will force the creation of objects to those in the group only
689         // Again, this is match what Blender is doing (it doesn't care of parent relationship)
690         m_groupGameObjects.clear();
691
692         group = blgroupobj->dup_group;
693         for(go=(GroupObject*)group->gobject.first; go; go=(GroupObject*)go->next) 
694         {
695                 Object* blenderobj = go->ob;
696                 if (blgroupobj == blenderobj)
697                         // this check is also in group_duplilist()
698                         continue;
699
700                 gameobj = (KX_GameObject*)m_logicmgr->FindGameObjByBlendObj(blenderobj);
701                 if (gameobj == NULL) 
702                 {
703                         // this object has not been converted!!!
704                         // Should not happen as dupli group are created automatically 
705                         continue;
706                 }
707
708                 gameobj->SetBlenderGroupObject(blgroupobj);
709
710                 if ((blenderobj->lay & group->layer)==0)
711                 {
712                         // object is not visible in the 3D view, will not be instantiated
713                         continue;
714                 }
715                 m_groupGameObjects.insert(gameobj);
716         }
717
718         set<CValue*>::iterator oit;
719         for (oit=m_groupGameObjects.begin(); oit != m_groupGameObjects.end(); oit++)
720         {
721                 gameobj = (KX_GameObject*)(*oit);
722
723                 KX_GameObject *parent = gameobj->GetParent();
724                 if (parent != NULL)
725                 {
726                         parent->Release(); // GetParent() increased the refcount
727
728                         // this object is not a top parent. Either it is the child of another
729                         // object in the group and it will be added automatically when the parent
730                         // is added. Or it is the child of an object outside the group and the group
731                         // is inconsistent, skip it anyway
732                         continue;
733                 }
734                 replica = (KX_GameObject*) AddNodeReplicaObject(NULL,gameobj);
735                 // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame)
736                 m_parentlist->Add(replica->AddRef());
737
738                 // recurse replication into children nodes
739                 NodeList& children = gameobj->GetSGNode()->GetSGChildren();
740
741                 replica->GetSGNode()->ClearSGChildren();
742                 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
743                 {
744                         SG_Node* orgnode = (*childit);
745                         SG_Node* childreplicanode = orgnode->GetSGReplica();
746                         if (childreplicanode)
747                                 replica->GetSGNode()->AddChild(childreplicanode);
748                 }
749                 // don't replicate logic now: we assume that the objects in the group can have
750                 // logic relationship, even outside parent relationship
751                 // In order to match 3D view, the position of groupobj is used as a 
752                 // transformation matrix instead of the new position. This means that 
753                 // the group reference point is 0,0,0
754
755                 // get the rootnode's scale
756                 MT_Vector3 newscale = groupobj->NodeGetWorldScaling();
757                 // set the replica's relative scale with the rootnode's scale
758                 replica->NodeSetRelativeScale(newscale);
759
760                 MT_Point3 offset(group->dupli_ofs);
761                 MT_Point3 newpos = groupobj->NodeGetWorldPosition() + 
762                         newscale*(groupobj->NodeGetWorldOrientation() * (gameobj->NodeGetWorldPosition()-offset));
763                 replica->NodeSetLocalPosition(newpos);
764                 // set the orientation after position for softbody!
765                 MT_Matrix3x3 newori = groupobj->NodeGetWorldOrientation() * gameobj->NodeGetWorldOrientation();
766                 replica->NodeSetLocalOrientation(newori);
767                 // update scenegraph for entire tree of children
768                 replica->GetSGNode()->UpdateWorldData(0);
769                 replica->GetSGNode()->SetBBox(gameobj->GetSGNode()->BBox());
770                 replica->GetSGNode()->SetRadius(gameobj->GetSGNode()->Radius());
771                 // we can now add the graphic controller to the physic engine
772                 replica->ActivateGraphicController(true);
773
774                 // done with replica
775                 replica->Release();
776         }
777
778         // the logic must be replicated first because we need
779         // the new logic bricks before relinking
780         vector<KX_GameObject*>::iterator git;
781         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
782         {
783                 (*git)->ReParentLogic();
784         }
785         
786         //      relink any pointers as necessary, sort of a temporary solution
787         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
788         {
789                 // this will also relink the actuator to objects within the hierarchy
790                 (*git)->Relink(&m_map_gameobject_to_replica);
791                 // add the object in the layer of the parent
792                 (*git)->SetLayer(groupobj->GetLayer());
793                 // If the object was a light, we need to update it's RAS_LightObject as well
794                 if ((*git)->GetGameObjectType()==SCA_IObject::OBJ_LIGHT)
795                 {
796                         KX_LightObject* lightobj = static_cast<KX_LightObject*>(*git);
797                         lightobj->GetLightData()->m_layer = groupobj->GetLayer();
798                 }
799         }
800
801         // replicate crosslinks etc. between logic bricks
802         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
803         {
804                 ReplicateLogic((*git));
805         }
806         
807         // now look if object in the hierarchy have dupli group and recurse
808         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
809         {
810                 if ((*git) != groupobj && (*git)->IsDupliGroup())
811                         // can't instantiate group immediately as it destroys m_logicHierarchicalGameObjects
812                         duplilist.push_back((*git));
813         }
814
815         for (git = duplilist.begin(); !(git == duplilist.end()); ++git)
816         {
817                 DupliGroupRecurse((*git), level+1);
818         }
819 }
820
821
822 SCA_IObject* KX_Scene::AddReplicaObject(class CValue* originalobject,
823                                                                                 class CValue* parentobject,
824                                                                                 int lifespan)
825 {
826
827         m_logicHierarchicalGameObjects.clear();
828         m_map_gameobject_to_replica.clear();
829         m_groupGameObjects.clear();
830
831         // todo: place a timebomb in the object, for temporarily objects :)
832         // lifespan of zero means 'this object lives forever'
833         KX_GameObject* originalobj = (KX_GameObject*) originalobject;
834         KX_GameObject* parentobj = (KX_GameObject*) parentobject;
835
836         m_ueberExecutionPriority++;
837
838         // lets create a replica
839         KX_GameObject* replica = (KX_GameObject*) AddNodeReplicaObject(NULL,originalobj);
840
841         if (lifespan > 0)
842         {
843                 // add a timebomb to this object
844                 // for now, convert between so called frames and realtime
845                 m_tempObjectList->Add(replica->AddRef());
846                 // this convert the life from frames to sort-of seconds, hard coded 0.02 that assumes we have 50 frames per second
847                 // if you change this value, make sure you change it in KX_GameObject::pyattr_get_life property too
848                 CValue *fval = new CFloatValue(lifespan*0.02);
849                 replica->SetProperty("::timebomb",fval);
850                 fval->Release();
851         }
852
853         // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame)
854         m_parentlist->Add(replica->AddRef());
855
856         // recurse replication into children nodes
857
858         NodeList& children = originalobj->GetSGNode()->GetSGChildren();
859
860         replica->GetSGNode()->ClearSGChildren();
861         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
862         {
863                 SG_Node* orgnode = (*childit);
864                 SG_Node* childreplicanode = orgnode->GetSGReplica();
865                 if (childreplicanode)
866                         replica->GetSGNode()->AddChild(childreplicanode);
867         }
868
869         // At this stage all the objects in the hierarchy have been duplicated,
870         // we can update the scenegraph, we need it for the duplication of logic
871         MT_Point3 newpos = ((KX_GameObject*) parentobject)->NodeGetWorldPosition();
872         replica->NodeSetLocalPosition(newpos);
873
874         MT_Matrix3x3 newori = ((KX_GameObject*) parentobject)->NodeGetWorldOrientation();
875         replica->NodeSetLocalOrientation(newori);
876         
877         // get the rootnode's scale
878         MT_Vector3 newscale = parentobj->GetSGNode()->GetRootSGParent()->GetLocalScale();
879
880         // set the replica's relative scale with the rootnode's scale
881         replica->NodeSetRelativeScale(newscale);
882
883         replica->GetSGNode()->UpdateWorldData(0);
884         replica->GetSGNode()->SetBBox(originalobj->GetSGNode()->BBox());
885         replica->GetSGNode()->SetRadius(originalobj->GetSGNode()->Radius());
886         // the size is correct, we can add the graphic controller to the physic engine
887         replica->ActivateGraphicController(true);
888
889         // now replicate logic
890         vector<KX_GameObject*>::iterator git;
891         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
892         {
893                 (*git)->ReParentLogic();
894         }
895         
896         //      relink any pointers as necessary, sort of a temporary solution
897         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
898         {
899                 // this will also relink the actuators in the hierarchy
900                 (*git)->Relink(&m_map_gameobject_to_replica);
901                 // add the object in the layer of the parent
902                 (*git)->SetLayer(parentobj->GetLayer());
903                 // If the object was a light, we need to update it's RAS_LightObject as well
904                 if ((*git)->GetGameObjectType()==SCA_IObject::OBJ_LIGHT)
905                 {
906                         KX_LightObject* lightobj = static_cast<KX_LightObject*>(*git);
907                         lightobj->GetLightData()->m_layer = parentobj->GetLayer();
908                 }
909         }
910
911         // replicate crosslinks etc. between logic bricks
912         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
913         {
914                 ReplicateLogic((*git));
915         }
916         
917         // check if there are objects with dupligroup in the hierarchy
918         vector<KX_GameObject*> duplilist;
919         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
920         {
921                 if ((*git)->IsDupliGroup())
922                 {
923                         // separate list as m_logicHierarchicalGameObjects is also used by DupliGroupRecurse()
924                         duplilist.push_back(*git);
925                 }
926         }
927         for (git = duplilist.begin();!(git==duplilist.end());++git)
928         {
929                 DupliGroupRecurse(*git, 0);
930         }
931         //      don't release replica here because we are returning it, not done with it...
932         return replica;
933 }
934
935
936
937 void KX_Scene::RemoveObject(class CValue* gameobj)
938 {
939         KX_GameObject* newobj = (KX_GameObject*) gameobj;
940
941         // disconnect child from parent
942         SG_Node* node = newobj->GetSGNode();
943
944         if (node)
945         {
946                 node->DisconnectFromParent();
947
948                 // recursively destruct
949                 node->Destruct();
950         }
951         //no need to do that: the object is destroyed and memory released 
952         //newobj->SetSGNode(0);
953 }
954
955 void KX_Scene::DelayedRemoveObject(class CValue* gameobj)
956 {
957         //KX_GameObject* newobj = (KX_GameObject*) gameobj;
958         if (!m_euthanasyobjects->SearchValue(gameobj))
959         {
960                 m_euthanasyobjects->Add(gameobj->AddRef());
961         } 
962 }
963
964
965
966 int KX_Scene::NewRemoveObject(class CValue* gameobj)
967 {
968         int ret;
969         KX_GameObject* newobj = (KX_GameObject*) gameobj;
970
971         /* Invalidate the python reference, since the object may exist in script lists
972          * its possible that it wont be automatically invalidated, so do it manually here,
973          * 
974          * if for some reason the object is added back into the scene python can always get a new Proxy
975          */
976         newobj->InvalidateProxy();
977
978         // keep the blender->game object association up to date
979         // note that all the replicas of an object will have the same
980         // blender object, that's why we need to check the game object
981         // as only the deletion of the original object must be recorded
982         m_logicmgr->UnregisterGameObj(newobj->GetBlenderObject(), gameobj);
983
984         //todo: look at this
985         //GetPhysicsEnvironment()->RemovePhysicsController(gameobj->getPhysicsController());
986
987         // remove all sensors/controllers/actuators from logicsystem...
988         
989         SCA_SensorList& sensors = newobj->GetSensors();
990         for (SCA_SensorList::iterator its = sensors.begin();
991                  !(its==sensors.end());its++)
992         {
993                 m_logicmgr->RemoveSensor(*its);
994         }
995
996         SCA_ControllerList& controllers = newobj->GetControllers();
997         for (SCA_ControllerList::iterator itc = controllers.begin();
998                  !(itc==controllers.end());itc++)
999         {
1000                 m_logicmgr->RemoveController(*itc);
1001         }
1002
1003         SCA_ActuatorList& actuators = newobj->GetActuators();
1004         for (SCA_ActuatorList::iterator ita = actuators.begin();
1005                  !(ita==actuators.end());ita++)
1006         {
1007                 m_logicmgr->RemoveActuator(*ita);
1008         }
1009         // the sensors/controllers/actuators must also be released, this is done in ~SCA_IObject
1010
1011         // now remove the timer properties from the time manager
1012         int numprops = newobj->GetPropertyCount();
1013
1014         for (int i = 0; i < numprops; i++)
1015         {
1016                 CValue* propval = newobj->GetProperty(i);
1017                 if (propval->GetProperty("timer"))
1018                 {
1019                         m_timemgr->RemoveTimeProperty(propval);
1020                 }
1021         }
1022         
1023         newobj->RemoveMeshes();
1024         ret = 1;
1025         if (newobj->GetGameObjectType()==SCA_IObject::OBJ_LIGHT && m_lightlist->RemoveValue(newobj))
1026                 ret = newobj->Release();
1027         if (m_objectlist->RemoveValue(newobj))
1028                 ret = newobj->Release();
1029         if (m_tempObjectList->RemoveValue(newobj))
1030                 ret = newobj->Release();
1031         if (m_parentlist->RemoveValue(newobj))
1032                 ret = newobj->Release();
1033         if (m_inactivelist->RemoveValue(newobj))
1034                 ret = newobj->Release();
1035         if (m_euthanasyobjects->RemoveValue(newobj))
1036                 ret = newobj->Release();
1037         if (m_animatedlist->RemoveValue(newobj))
1038                 ret = newobj->Release();
1039                 
1040         if (newobj == m_active_camera)
1041         {
1042                 //no AddRef done on m_active_camera so no Release
1043                 //m_active_camera->Release();
1044                 m_active_camera = NULL;
1045         }
1046
1047         // in case this is a camera
1048         m_cameras.remove((KX_Camera*)newobj);
1049
1050         // in case this is a font
1051         m_fonts.remove((KX_FontObject*)newobj);
1052
1053         /* currently does nothing, keep incase we need to Unregister something */
1054 #if 0
1055         if (m_sceneConverter)
1056                 m_sceneConverter->UnregisterGameObject(newobj);
1057 #endif
1058         
1059         // return value will be 0 if the object is actually deleted (all reference gone)
1060         
1061         return ret;
1062 }
1063
1064
1065
1066 void KX_Scene::ReplaceMesh(class CValue* obj,void* meshobj, bool use_gfx, bool use_phys)
1067 {
1068         KX_GameObject* gameobj = static_cast<KX_GameObject*>(obj);
1069         RAS_MeshObject* mesh = static_cast<RAS_MeshObject*>(meshobj);
1070
1071         if(!gameobj) {
1072                 std::cout << "KX_Scene::ReplaceMesh Warning: invalid object, doing nothing" << std::endl;
1073                 return;
1074         }
1075
1076         if(use_gfx && mesh != NULL)
1077         {               
1078         gameobj->RemoveMeshes();
1079         gameobj->AddMesh(mesh);
1080         
1081         if (gameobj->m_isDeformable)
1082         {
1083                 BL_DeformableGameObject* newobj = static_cast<BL_DeformableGameObject*>( gameobj );
1084                 
1085                 if (newobj->GetDeformer())
1086                 {
1087                         delete newobj->GetDeformer();
1088                         newobj->SetDeformer(NULL);
1089                 }
1090
1091                 if (mesh->GetMesh()) 
1092                 {
1093                         // we must create a new deformer but which one?
1094                         KX_GameObject* parentobj = newobj->GetParent();
1095                         // this always return the original game object (also for replicate)
1096                         Object* blendobj = newobj->GetBlenderObject();
1097                         // object that owns the new mesh
1098                         Object* oldblendobj = static_cast<struct Object*>(m_logicmgr->FindBlendObjByGameMeshName(mesh->GetName()));
1099                         Mesh* blendmesh = mesh->GetMesh();
1100
1101                         bool bHasModifier = BL_ModifierDeformer::HasCompatibleDeformer(blendobj);
1102                         bool bHasShapeKey = blendmesh->key != NULL && blendmesh->key->type==KEY_RELATIVE;
1103                         bool bHasDvert = blendmesh->dvert != NULL;
1104                         bool bHasArmature = 
1105                                 BL_ModifierDeformer::HasArmatureDeformer(blendobj) &&
1106                                 parentobj &&                                                            // current parent is armature
1107                                 parentobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE &&
1108                                 oldblendobj &&                                                          // needed for mesh deform
1109                                 blendobj->parent &&                                                     // original object had armature (not sure this test is needed)
1110                                 blendobj->parent->type == OB_ARMATURE &&
1111                                 blendmesh->dvert!=NULL;                                         // mesh has vertex group
1112 #ifdef USE_BULLET
1113                         bool bHasSoftBody = (!parentobj && (blendobj->gameflag & OB_SOFT_BODY));
1114 #endif
1115                         bool releaseParent = true;
1116
1117                         
1118                         if (oldblendobj==NULL) {
1119                                 if (bHasModifier || bHasShapeKey || bHasDvert || bHasArmature) {
1120                                         std::cout << "warning: ReplaceMesh() new mesh is not used in an object from the current scene, you will get incorrect behavior" << std::endl;
1121                                         bHasShapeKey= bHasDvert= bHasArmature=bHasModifier= false;
1122                                 }
1123                         }
1124                         
1125                         if (bHasModifier)
1126                         {
1127                                 BL_ModifierDeformer* modifierDeformer;
1128                                 if (bHasShapeKey || bHasArmature)
1129                                 {
1130                                         modifierDeformer = new BL_ModifierDeformer(
1131                                                 newobj,
1132                                                 m_blenderScene,
1133                                                 oldblendobj, blendobj,
1134                                                 mesh,
1135                                                 true,
1136                                                 static_cast<BL_ArmatureObject*>( parentobj )
1137                                         );
1138                                         releaseParent= false;
1139                                         modifierDeformer->LoadShapeDrivers(blendobj->parent);
1140                                 }
1141                                 else
1142                                 {
1143                                         modifierDeformer = new BL_ModifierDeformer(
1144                                                 newobj,
1145                                                 m_blenderScene,
1146                                                 oldblendobj, blendobj,
1147                                                 mesh,
1148                                                 false,
1149                                                 NULL
1150                                         );
1151                                 }
1152                                 newobj->SetDeformer(modifierDeformer);
1153                         } 
1154                         else    if (bHasShapeKey)
1155                         {
1156                                 BL_ShapeDeformer* shapeDeformer;
1157                                 if (bHasArmature) 
1158                                 {
1159                                         shapeDeformer = new BL_ShapeDeformer(
1160                                                 newobj,
1161                                                 oldblendobj, blendobj,
1162                                                 mesh,
1163                                                 true,
1164                                                 true,
1165                                                 static_cast<BL_ArmatureObject*>( parentobj )
1166                                         );
1167                                         releaseParent= false;
1168                                         shapeDeformer->LoadShapeDrivers(blendobj->parent);
1169                                 }
1170                                 else
1171                                 {
1172                                         shapeDeformer = new BL_ShapeDeformer(
1173                                                 newobj,
1174                                                 oldblendobj, blendobj,
1175                                                 mesh,
1176                                                 false,
1177                                                 true,
1178                                                 NULL
1179                                         );
1180                                 }
1181                                 newobj->SetDeformer( shapeDeformer);
1182                         }
1183                         else if (bHasArmature) 
1184                         {
1185                                 BL_SkinDeformer* skinDeformer = new BL_SkinDeformer(
1186                                         newobj,
1187                                         oldblendobj, blendobj,
1188                                         mesh,
1189                                         true,
1190                                         true,
1191                                         static_cast<BL_ArmatureObject*>( parentobj )
1192                                 );
1193                                 releaseParent= false;
1194                                 newobj->SetDeformer(skinDeformer);
1195                         }
1196                         else if (bHasDvert)
1197                         {
1198                                 BL_MeshDeformer* meshdeformer = new BL_MeshDeformer(
1199                                         newobj, oldblendobj, mesh
1200                                 );
1201                                 newobj->SetDeformer(meshdeformer);
1202                         }
1203 #ifdef USE_BULLET
1204                         else if (bHasSoftBody)
1205                         {
1206                                 KX_SoftBodyDeformer *softdeformer = new KX_SoftBodyDeformer(mesh, newobj);
1207                                 newobj->SetDeformer(softdeformer);
1208                         }
1209 #endif
1210
1211                         // release parent reference if its not being used 
1212                         if( releaseParent && parentobj)
1213                                 parentobj->Release();
1214                 }
1215         }
1216
1217         gameobj->AddMeshUser();
1218         }
1219
1220 #ifdef USE_BULLET
1221         if(use_phys) { /* update the new assigned mesh with the physics mesh */
1222                 KX_ReInstanceBulletShapeFromMesh(gameobj, NULL, use_gfx?NULL:mesh);
1223         }
1224 #endif
1225 }
1226
1227 /* Font Object routines */
1228 void KX_Scene::AddFont(KX_FontObject* font)
1229 {
1230         if (!FindFont(font))
1231                 m_fonts.push_back(font);
1232 }
1233
1234 KX_FontObject* KX_Scene::FindFont(KX_FontObject* font)
1235 {
1236         list<KX_FontObject*>::iterator it = m_fonts.begin();
1237
1238         while ( (it != m_fonts.end()) 
1239                         && ((*it) != font) ) {
1240           ++it;
1241         }
1242
1243         return ((it == m_fonts.end()) ? NULL : (*it));
1244 }
1245
1246
1247 /* Camera Object routines */
1248 KX_Camera* KX_Scene::FindCamera(KX_Camera* cam)
1249 {
1250         list<KX_Camera*>::iterator it = m_cameras.begin();
1251
1252         while ( (it != m_cameras.end()) 
1253                         && ((*it) != cam) ) {
1254           it++;
1255         }
1256
1257         return ((it == m_cameras.end()) ? NULL : (*it));
1258 }
1259
1260
1261 KX_Camera* KX_Scene::FindCamera(STR_String& name)
1262 {
1263         list<KX_Camera*>::iterator it = m_cameras.begin();
1264
1265         while ( (it != m_cameras.end()) 
1266                         && ((*it)->GetName() != name) ) {
1267           it++;
1268         }
1269
1270         return ((it == m_cameras.end()) ? NULL : (*it));
1271 }
1272
1273 void KX_Scene::AddCamera(KX_Camera* cam)
1274 {
1275         if (!FindCamera(cam))
1276                 m_cameras.push_back(cam);
1277 }
1278
1279
1280 KX_Camera* KX_Scene::GetActiveCamera()
1281 {       
1282         // NULL if not defined
1283         return m_active_camera;
1284 }
1285
1286
1287 void KX_Scene::SetActiveCamera(KX_Camera* cam)
1288 {
1289         // only set if the cam is in the active list? Or add it otherwise?
1290         if (!FindCamera(cam)){
1291                 AddCamera(cam);
1292                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
1293         } 
1294
1295         m_active_camera = cam;
1296 }
1297
1298 void KX_Scene::SetCameraOnTop(KX_Camera* cam)
1299 {
1300         if (!FindCamera(cam)){
1301                 // adding is always done at the back, so that's all that needs to be done
1302                 AddCamera(cam);
1303                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
1304         } else {
1305                 m_cameras.remove(cam);
1306                 m_cameras.push_back(cam);
1307         }
1308 }
1309
1310
1311 void KX_Scene::UpdateMeshTransformations()
1312 {
1313         // do this incrementally in the future
1314         for (int i = 0; i < m_objectlist->GetCount(); i++)
1315         {
1316                 KX_GameObject* gameobj = (KX_GameObject*)m_objectlist->GetValue(i);
1317                 gameobj->GetOpenGLMatrix();
1318         }
1319 }
1320
1321 void KX_Scene::MarkVisible(SG_Tree *node, RAS_IRasterizer* rasty, KX_Camera* cam, int layer)
1322 {
1323         int intersect = KX_Camera::INTERSECT;
1324         KX_GameObject *gameobj = node->Client()?(KX_GameObject*) node->Client()->GetSGClientObject():NULL;
1325         bool visible = (gameobj && gameobj->GetVisible() && (!layer || (gameobj->GetLayer() & layer)));
1326         bool dotest = visible || node->Left() || node->Right();
1327
1328         /* If the camera is inside the box, assume intersect. */
1329         if (dotest && !node->inside( cam->NodeGetWorldPosition()))
1330         {
1331                 MT_Scalar radius = node->Radius();
1332                 MT_Point3 center = node->Center();
1333                 
1334                 intersect =  cam->SphereInsideFrustum(center, radius); 
1335                 
1336                 if (intersect == KX_Camera::INTERSECT)
1337                 {
1338                         MT_Point3 box[8];
1339                         node->get(box);
1340                         intersect = cam->BoxInsideFrustum(box);
1341                 }
1342         }
1343
1344         switch (intersect)
1345         {
1346                 case KX_Camera::OUTSIDE:
1347                         MarkSubTreeVisible(node, rasty, false, cam);
1348                         break;
1349                 case KX_Camera::INTERSECT:
1350                         if (gameobj)
1351                                 MarkVisible(rasty, gameobj, cam, layer);
1352                         if (node->Left())
1353                                 MarkVisible(node->Left(), rasty, cam, layer);
1354                         if (node->Right())
1355                                 MarkVisible(node->Right(), rasty, cam, layer);
1356                         break;
1357                 case KX_Camera::INSIDE:
1358                         MarkSubTreeVisible(node, rasty, true, cam, layer);
1359                         break;
1360         }
1361 }
1362
1363 void KX_Scene::MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool visible, KX_Camera* cam, int layer)
1364 {
1365         if (node->Client())
1366         {
1367                 KX_GameObject *gameobj = (KX_GameObject*) node->Client()->GetSGClientObject();
1368                 if (gameobj->GetVisible())
1369                 {
1370                         if (visible)
1371                         {
1372                                 int nummeshes = gameobj->GetMeshCount();
1373                                 
1374                                 // this adds the vertices to the display list
1375                                 for (int m=0;m<nummeshes;m++)
1376                                         (gameobj->GetMesh(m))->SchedulePolygons(rasty->GetDrawingMode());
1377                         }
1378
1379                         gameobj->SetCulled(!visible);
1380                         gameobj->UpdateBuckets(false);
1381                 }
1382         }
1383         if (node->Left())
1384                 MarkSubTreeVisible(node->Left(), rasty, visible, cam, layer);
1385         if (node->Right())
1386                 MarkSubTreeVisible(node->Right(), rasty, visible, cam, layer);
1387 }
1388
1389 void KX_Scene::MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj,KX_Camera*  cam,int layer)
1390 {
1391         // User (Python/Actuator) has forced object invisible...
1392         if (!gameobj->GetSGNode() || !gameobj->GetVisible())
1393                 return;
1394         
1395         // Shadow lamp layers
1396         if(layer && !(gameobj->GetLayer() & layer)) {
1397                 gameobj->SetCulled(true);
1398                 gameobj->UpdateBuckets(false);
1399                 return;
1400         }
1401
1402         // If Frustum culling is off, the object is always visible.
1403         bool vis = !cam->GetFrustumCulling();
1404         
1405         // If the camera is inside this node, then the object is visible.
1406         if (!vis)
1407         {
1408                 vis = gameobj->GetSGNode()->inside( cam->GetCameraLocation() );
1409         }
1410                 
1411         // Test the object's bound sphere against the view frustum.
1412         if (!vis)
1413         {
1414                 MT_Vector3 scale = gameobj->GetSGNode()->GetWorldScaling();
1415                 MT_Scalar radius = fabs(scale[scale.closestAxis()] * gameobj->GetSGNode()->Radius());
1416                 switch (cam->SphereInsideFrustum(gameobj->NodeGetWorldPosition(), radius))
1417                 {
1418                         case KX_Camera::INSIDE:
1419                                 vis = true;
1420                                 break;
1421                         case KX_Camera::OUTSIDE:
1422                                 vis = false;
1423                                 break;
1424                         case KX_Camera::INTERSECT:
1425                                 // Test the object's bound box against the view frustum.
1426                                 MT_Point3 box[8];
1427                                 gameobj->GetSGNode()->getBBox(box); 
1428                                 vis = cam->BoxInsideFrustum(box) != KX_Camera::OUTSIDE;
1429                                 break;
1430                 }
1431         }
1432         
1433         if (vis)
1434         {
1435                 int nummeshes = gameobj->GetMeshCount();
1436                 
1437                 for (int m=0;m<nummeshes;m++)
1438                 {
1439                         // this adds the vertices to the display list
1440                         (gameobj->GetMesh(m))->SchedulePolygons(rasty->GetDrawingMode());
1441                 }
1442                 // Visibility/ non-visibility are marked
1443                 // elsewhere now.
1444                 gameobj->SetCulled(false);
1445                 gameobj->UpdateBuckets(false);
1446         } else {
1447                 gameobj->SetCulled(true);
1448                 gameobj->UpdateBuckets(false);
1449         }
1450 }
1451
1452 void KX_Scene::PhysicsCullingCallback(KX_ClientObjectInfo* objectInfo, void* cullingInfo)
1453 {
1454         KX_GameObject* gameobj = objectInfo->m_gameobject;
1455         if (!gameobj->GetVisible())
1456                 // ideally, invisible objects should be removed from the culling tree temporarily
1457                 return;
1458         if(((CullingInfo*)cullingInfo)->m_layer && !(gameobj->GetLayer() & ((CullingInfo*)cullingInfo)->m_layer))
1459                 // used for shadow: object is not in shadow layer
1460                 return;
1461
1462         // make object visible
1463         gameobj->SetCulled(false);
1464         gameobj->UpdateBuckets(false);
1465 }
1466
1467 void KX_Scene::CalculateVisibleMeshes(RAS_IRasterizer* rasty,KX_Camera* cam, int layer)
1468 {
1469         bool dbvt_culling = false;
1470         if (m_dbvt_culling) 
1471         {
1472                 // test culling through Bullet
1473                 PHY__Vector4 planes[6];
1474                 // get the clip planes
1475                 MT_Vector4* cplanes = cam->GetNormalizedClipPlanes();
1476                 // and convert
1477                 planes[0].setValue(cplanes[4].getValue());      // near
1478                 planes[1].setValue(cplanes[5].getValue());      // far
1479                 planes[2].setValue(cplanes[0].getValue());      // left
1480                 planes[3].setValue(cplanes[1].getValue());      // right
1481                 planes[4].setValue(cplanes[2].getValue());      // top
1482                 planes[5].setValue(cplanes[3].getValue());      // bottom
1483                 CullingInfo info(layer);
1484                 dbvt_culling = m_physicsEnvironment->cullingTest(PhysicsCullingCallback,&info,planes,5,m_dbvt_occlusion_res);
1485         }
1486         if (!dbvt_culling) {
1487                 // the physics engine couldn't help us, do it the hard way
1488                 for (int i = 0; i < m_objectlist->GetCount(); i++)
1489                 {
1490                         MarkVisible(rasty, static_cast<KX_GameObject*>(m_objectlist->GetValue(i)), cam, layer);
1491                 }
1492         }
1493 }
1494
1495 // logic stuff
1496 void KX_Scene::LogicBeginFrame(double curtime)
1497 {
1498         // have a look at temp objects ...
1499         int lastobj = m_tempObjectList->GetCount() - 1;
1500         
1501         for (int i = lastobj; i >= 0; i--)
1502         {
1503                 CValue* objval = m_tempObjectList->GetValue(i);
1504                 CFloatValue* propval = (CFloatValue*) objval->GetProperty("::timebomb");
1505                 
1506                 if (propval)
1507                 {
1508                         float timeleft = propval->GetNumber() - 1.0/KX_KetsjiEngine::GetTicRate();
1509                         
1510                         if (timeleft > 0)
1511                         {
1512                                 propval->SetFloat(timeleft);
1513                         }
1514                         else
1515                         {
1516                                 DelayedRemoveObject(objval);
1517                                 // remove obj
1518                         }
1519                 }
1520                 else
1521                 {
1522                         // all object is the tempObjectList should have a clock
1523                 }
1524         }
1525         m_logicmgr->BeginFrame(curtime, 1.0/KX_KetsjiEngine::GetTicRate());
1526 }
1527
1528 void KX_Scene::AddAnimatedObject(CValue* gameobj)
1529 {
1530         gameobj->AddRef();
1531         m_animatedlist->Add(gameobj);
1532 }
1533
1534 void KX_Scene::RemoveAnimatedObject(CValue* gameobj)
1535 {
1536         m_animatedlist->RemoveValue(gameobj);
1537 }
1538
1539 void KX_Scene::UpdateAnimations(double curtime)
1540 {
1541         // Update any animations
1542         for (int i=0; i<m_animatedlist->GetCount(); ++i)
1543                 ((KX_GameObject*)m_animatedlist->GetValue(i))->UpdateActionManager(curtime);
1544 }
1545
1546 void KX_Scene::LogicUpdateFrame(double curtime, bool frame)
1547 {
1548         m_logicmgr->UpdateFrame(curtime, frame);
1549 }
1550
1551
1552
1553 void KX_Scene::LogicEndFrame()
1554 {
1555         m_logicmgr->EndFrame();
1556         int numobj;
1557
1558         KX_GameObject* obj;
1559
1560         while ((numobj = m_euthanasyobjects->GetCount()) > 0)
1561         {
1562                 // remove the object from this list to make sure we will not hit it again
1563                 obj = (KX_GameObject*)m_euthanasyobjects->GetValue(numobj-1);
1564                 m_euthanasyobjects->Remove(numobj-1);
1565                 obj->Release();
1566                 RemoveObject(obj);
1567         }
1568
1569         //prepare obstacle simulation for new frame
1570         if (m_obstacleSimulation)
1571                 m_obstacleSimulation->UpdateObstacles();
1572 }
1573
1574
1575
1576 /**
1577   * UpdateParents: SceneGraph transformation update.
1578   */
1579 void KX_Scene::UpdateParents(double curtime)
1580 {
1581         // we use the SG dynamic list
1582         SG_Node* node;
1583
1584         while ((node = SG_Node::GetNextScheduled(m_sghead)) != NULL)
1585         {
1586                 node->UpdateWorldData(curtime);
1587         }
1588
1589         //for (int i=0; i<GetRootParentList()->GetCount(); i++)
1590         //{
1591         //      KX_GameObject* parentobj = (KX_GameObject*)GetRootParentList()->GetValue(i);
1592         //      parentobj->NodeUpdateGS(curtime);
1593         //}
1594
1595         // the list must be empty here
1596         assert(m_sghead.Empty());
1597         // some nodes may be ready for reschedule, move them to schedule list for next time
1598         while ((node = SG_Node::GetNextRescheduled(m_sghead)) != NULL)
1599         {
1600                 node->Schedule(m_sghead);
1601         }
1602 }
1603
1604
1605 RAS_MaterialBucket* KX_Scene::FindBucket(class RAS_IPolyMaterial* polymat, bool &bucketCreated)
1606 {
1607         return m_bucketmanager->FindBucket(polymat, bucketCreated);
1608 }
1609
1610
1611
1612 void KX_Scene::RenderBuckets(const MT_Transform & cameratransform,
1613                                                          class RAS_IRasterizer* rasty,
1614                                                          class RAS_IRenderTools* rendertools)
1615 {
1616         m_bucketmanager->Renderbuckets(cameratransform,rasty,rendertools);
1617         KX_BlenderMaterial::EndFrame();
1618 }
1619
1620 void KX_Scene::UpdateObjectActivity(void) 
1621 {
1622         if (m_activity_culling) {
1623                 /* determine the activity criterium and set objects accordingly */
1624                 int i=0;
1625                 
1626                 MT_Point3 camloc = GetActiveCamera()->NodeGetWorldPosition(); //GetCameraLocation();
1627                 
1628                 for (i=0;i<GetObjectList()->GetCount();i++)
1629                 {
1630                         KX_GameObject* ob = (KX_GameObject*) GetObjectList()->GetValue(i);
1631                         
1632                         if (!ob->GetIgnoreActivityCulling()) {
1633                                 /* Simple test: more than 10 away from the camera, count
1634                                  * Manhattan distance. */
1635                                 MT_Point3 obpos = ob->NodeGetWorldPosition();
1636                                 
1637                                 if ( (fabs(camloc[0] - obpos[0]) > m_activity_box_radius)
1638                                          || (fabs(camloc[1] - obpos[1]) > m_activity_box_radius)
1639                                          || (fabs(camloc[2] - obpos[2]) > m_activity_box_radius) )
1640                                 {                       
1641                                         ob->Suspend();
1642                                 } else {
1643                                         ob->Resume();
1644                                 }
1645                         }
1646                 }               
1647         }
1648 }
1649
1650 void KX_Scene::SetActivityCullingRadius(float f)
1651 {
1652         if (f < 0.5)
1653                 f = 0.5;
1654         m_activity_box_radius = f;
1655 }
1656         
1657 NG_NetworkDeviceInterface* KX_Scene::GetNetworkDeviceInterface()
1658 {
1659         return m_networkDeviceInterface;
1660 }
1661
1662 NG_NetworkScene* KX_Scene::GetNetworkScene()
1663 {
1664         return m_networkScene;
1665 }
1666
1667 void KX_Scene::SetNetworkDeviceInterface(NG_NetworkDeviceInterface* newInterface)
1668 {
1669         m_networkDeviceInterface = newInterface;
1670 }
1671
1672 void KX_Scene::SetNetworkScene(NG_NetworkScene *newScene)
1673 {
1674         m_networkScene = newScene;
1675 }
1676
1677
1678 void    KX_Scene::SetGravity(const MT_Vector3& gravity)
1679 {
1680         GetPhysicsEnvironment()->setGravity(gravity[0],gravity[1],gravity[2]);
1681 }
1682
1683 void KX_Scene::SetSceneConverter(class KX_BlenderSceneConverter* sceneConverter)
1684 {
1685         m_sceneConverter = sceneConverter;
1686 }
1687
1688 void KX_Scene::SetPhysicsEnvironment(class PHY_IPhysicsEnvironment* physEnv)
1689 {
1690         m_physicsEnvironment = physEnv;
1691         if(m_physicsEnvironment) {
1692                 KX_TouchEventManager* touchmgr = new KX_TouchEventManager(m_logicmgr, physEnv);
1693                 m_logicmgr->RegisterEventManager(touchmgr);
1694         }
1695 }
1696  
1697 void KX_Scene::setSuspendedTime(double suspendedtime)
1698 {
1699         m_suspendedtime = suspendedtime;
1700 }
1701 double KX_Scene::getSuspendedTime()
1702 {
1703         return m_suspendedtime;
1704 }
1705 void KX_Scene::setSuspendedDelta(double suspendeddelta)
1706 {
1707         m_suspendeddelta = suspendeddelta;
1708 }
1709 double KX_Scene::getSuspendedDelta()
1710 {
1711         return m_suspendeddelta;
1712 }
1713
1714 short KX_Scene::GetAnimationFPS()
1715 {
1716         return m_blenderScene->r.frs_sec;
1717 }
1718
1719 #ifdef USE_BULLET
1720 #include "KX_BulletPhysicsController.h"
1721 #endif
1722
1723 static void MergeScene_LogicBrick(SCA_ILogicBrick* brick, KX_Scene *to)
1724 {
1725         SCA_LogicManager *logicmgr= to->GetLogicManager();
1726
1727         brick->Replace_IScene(to);
1728         brick->Replace_NetworkScene(to->GetNetworkScene());
1729
1730         SCA_ISensor *sensor=  dynamic_cast<class SCA_ISensor *>(brick);
1731         if(sensor) {
1732                 sensor->Replace_EventManager(logicmgr);
1733         }
1734
1735         /* near sensors have physics controllers */
1736 #ifdef USE_BULLET
1737         KX_TouchSensor *touch_sensor = dynamic_cast<class KX_TouchSensor *>(brick);
1738         if(touch_sensor) {
1739                 touch_sensor->GetPhysicsController()->SetPhysicsEnvironment(to->GetPhysicsEnvironment());
1740         }
1741 #endif
1742 }
1743
1744 #ifdef USE_BULLET
1745 #include "CcdGraphicController.h" // XXX  ctrl->SetPhysicsEnvironment(to->GetPhysicsEnvironment());
1746 #include "CcdPhysicsEnvironment.h" // XXX  ctrl->SetPhysicsEnvironment(to->GetPhysicsEnvironment());
1747 #include "KX_BulletPhysicsController.h"
1748 #endif
1749
1750 static void MergeScene_GameObject(KX_GameObject* gameobj, KX_Scene *to, KX_Scene *from)
1751 {
1752         {
1753                 SCA_ActuatorList& actuators= gameobj->GetActuators();
1754                 SCA_ActuatorList::iterator ita;
1755
1756                 for (ita = actuators.begin(); !(ita==actuators.end()); ++ita)
1757                 {
1758                         MergeScene_LogicBrick(*ita, to);
1759                 }
1760         }
1761
1762
1763         {
1764                 SCA_SensorList& sensors= gameobj->GetSensors();
1765                 SCA_SensorList::iterator its;
1766
1767                 for (its = sensors.begin(); !(its==sensors.end()); ++its)
1768                 {
1769                         MergeScene_LogicBrick(*its, to);
1770                 }
1771         }
1772
1773         {
1774                 SCA_ControllerList& controllers= gameobj->GetControllers();
1775                 SCA_ControllerList::iterator itc;
1776
1777                 for (itc = controllers.begin(); !(itc==controllers.end()); ++itc)
1778                 {
1779                         SCA_IController *cont= *itc;
1780                         MergeScene_LogicBrick(cont, to);
1781
1782                         vector<SCA_ISensor*> linkedsensors = cont->GetLinkedSensors();
1783                         vector<SCA_IActuator*> linkedactuators = cont->GetLinkedActuators();
1784
1785                         for (vector<SCA_IActuator*>::iterator ita = linkedactuators.begin();!(ita==linkedactuators.end());++ita) {
1786                                 MergeScene_LogicBrick(*ita, to);
1787                         }
1788
1789                         for (vector<SCA_ISensor*>::iterator its = linkedsensors.begin();!(its==linkedsensors.end());++its) {
1790                                 MergeScene_LogicBrick(*its, to);
1791                         }
1792                 }
1793         }
1794
1795         /* graphics controller */
1796         PHY_IGraphicController *ctrl = gameobj->GetGraphicController();
1797         if(ctrl) {
1798                 /* SHOULD update the m_cullingTree */
1799                 ctrl->SetPhysicsEnvironment(to->GetPhysicsEnvironment());
1800         }
1801
1802         /* SG_Node can hold a scene reference */
1803         SG_Node *sg= gameobj->GetSGNode();
1804         if(sg) {
1805                 if(sg->GetSGClientInfo() == from) {
1806                         sg->SetSGClientInfo(to);
1807
1808                         /* Make sure to grab the children too since they might not be tied to a game object */
1809                         NodeList children = sg->GetSGChildren();
1810                         for (int i=0; i<children.size(); i++)
1811                                         children[i]->SetSGClientInfo(to);
1812                 }
1813 #ifdef USE_BULLET
1814                 SGControllerList::iterator contit;
1815                 SGControllerList& controllers = sg->GetSGControllerList();
1816                 for (contit = controllers.begin();contit!=controllers.end();++contit)
1817                 {
1818                         KX_BulletPhysicsController *phys_ctrl= dynamic_cast<KX_BulletPhysicsController *>(*contit);
1819                         if (phys_ctrl)
1820                                 phys_ctrl->SetPhysicsEnvironment(to->GetPhysicsEnvironment());
1821                 }
1822 #endif // USE_BULLET
1823         }
1824         /* If the object is a light, update it's scene */
1825         if (gameobj->GetGameObjectType() == SCA_IObject::OBJ_LIGHT)
1826                 ((KX_LightObject*)gameobj)->UpdateScene(to);
1827
1828         /* Add the object to the scene's logic manager */
1829         to->GetLogicManager()->RegisterGameObjectName(gameobj->GetName(), gameobj);
1830         to->GetLogicManager()->RegisterGameObj(gameobj->GetBlenderObject(), gameobj);
1831
1832         for (int i=0; i<gameobj->GetMeshCount(); ++i)
1833                 to->GetLogicManager()->RegisterGameMeshName(gameobj->GetMesh(i)->GetName(), gameobj->GetBlenderObject());
1834 }
1835
1836 bool KX_Scene::MergeScene(KX_Scene *other)
1837 {
1838 #ifdef USE_BULLET
1839         CcdPhysicsEnvironment *env=                     dynamic_cast<CcdPhysicsEnvironment *>(this->GetPhysicsEnvironment());
1840         CcdPhysicsEnvironment *env_other=       dynamic_cast<CcdPhysicsEnvironment *>(other->GetPhysicsEnvironment());
1841
1842         if((env==NULL) != (env_other==NULL)) /* TODO - even when both scenes have NONE physics, the other is loaded with bullet enabled, ??? */
1843         {
1844                 printf("KX_Scene::MergeScene: physics scenes type differ, aborting\n");
1845                 printf("\tsource %d, terget %d\n", (int)(env!=NULL), (int)(env_other!=NULL));
1846                 return false;
1847         }
1848 #endif // USE_BULLET
1849
1850         if(GetSceneConverter() != other->GetSceneConverter()) {
1851                 printf("KX_Scene::MergeScene: converters differ, aborting\n");
1852                 return false;
1853         }
1854
1855
1856         GetBucketManager()->MergeBucketManager(other->GetBucketManager(), this);
1857
1858         /* move materials across, assume they both use the same scene-converters */
1859         GetSceneConverter()->MergeScene(this, other);
1860
1861         /* active + inactive == all ??? - lets hope so */
1862         for (int i = 0; i < other->GetObjectList()->GetCount(); i++)
1863         {
1864                 KX_GameObject* gameobj = (KX_GameObject*)other->GetObjectList()->GetValue(i);
1865                 MergeScene_GameObject(gameobj, this, other);
1866
1867                 gameobj->UpdateBuckets(false); /* only for active objects */
1868         }
1869
1870         for (int i = 0; i < other->GetInactiveList()->GetCount(); i++)
1871         {
1872                 KX_GameObject* gameobj = (KX_GameObject*)other->GetInactiveList()->GetValue(i);
1873                 MergeScene_GameObject(gameobj, this, other);
1874         }
1875
1876         GetTempObjectList()->MergeList(other->GetTempObjectList());
1877         other->GetTempObjectList()->ReleaseAndRemoveAll();
1878
1879         GetObjectList()->MergeList(other->GetObjectList());
1880         other->GetObjectList()->ReleaseAndRemoveAll();
1881
1882         GetInactiveList()->MergeList(other->GetInactiveList());
1883         other->GetInactiveList()->ReleaseAndRemoveAll();
1884
1885         GetRootParentList()->MergeList(other->GetRootParentList());
1886         other->GetRootParentList()->ReleaseAndRemoveAll();
1887
1888         GetLightList()->MergeList(other->GetLightList());
1889         other->GetLightList()->ReleaseAndRemoveAll();
1890
1891 #ifdef USE_BULLET
1892         if(env) /* bullet scene? - dummy scenes dont need touching */
1893                 env->MergeEnvironment(env_other);
1894 #endif
1895         
1896         /* merge logic */
1897         {
1898                 SCA_LogicManager *logicmgr=                     GetLogicManager();
1899                 SCA_LogicManager *logicmgr_other=       other->GetLogicManager();
1900
1901                 vector<class SCA_EventManager*>evtmgrs= logicmgr->GetEventManagers();
1902                 //vector<class SCA_EventManager*>evtmgrs_others= logicmgr_other->GetEventManagers();
1903
1904                 //SCA_EventManager *evtmgr;
1905                 SCA_EventManager *evtmgr_other;
1906
1907                 for(unsigned int i= 0; i < evtmgrs.size(); i++) {
1908                         evtmgr_other= logicmgr_other->FindEventManager(evtmgrs[i]->GetType());
1909
1910                         if(evtmgr_other) /* unlikely but possible one scene has a joystick and not the other */
1911                                 evtmgr_other->Replace_LogicManager(logicmgr);
1912
1913                         /* when merging objects sensors are moved across into the new manager, dont need to do this here */
1914                 }
1915
1916                 /* grab any timer properties from the other scene */
1917                 SCA_TimeEventManager *timemgr=          GetTimeEventManager();
1918                 SCA_TimeEventManager *timemgr_other=    other->GetTimeEventManager();
1919                 vector<CValue*> times = timemgr_other->GetTimeValues();
1920
1921                 for(unsigned int i= 0; i < times.size(); i++) {
1922                         timemgr->AddTimeProperty(times[i]);
1923                 }
1924                 
1925         }
1926         return true;
1927 }
1928
1929 void KX_Scene::Update2DFilter(vector<STR_String>& propNames, void* gameObj, RAS_2DFilterManager::RAS_2DFILTER_MODE filtermode, int pass, STR_String& text)
1930 {
1931         m_filtermanager.EnableFilter(propNames, gameObj, filtermode, pass, text);
1932 }
1933
1934 void KX_Scene::Render2DFilters(RAS_ICanvas* canvas)
1935 {
1936         m_filtermanager.RenderFilters(canvas);
1937 }
1938
1939 #ifdef WITH_PYTHON
1940
1941 void KX_Scene::RunDrawingCallbacks(PyObject* cb_list)
1942 {
1943         Py_ssize_t len;
1944
1945         if (cb_list && (len=PyList_GET_SIZE(cb_list)))
1946         {
1947                 PyObject* args= PyTuple_New(0); // save python creating each call
1948                 PyObject* func;
1949                 PyObject* ret;
1950
1951                 // Iterate the list and run the callbacks
1952                 for (Py_ssize_t pos=0; pos < len; pos++)
1953                 {
1954                         func= PyList_GET_ITEM(cb_list, pos);
1955                         ret= PyObject_Call(func, args, NULL);
1956                         if (ret==NULL) {
1957                                 PyErr_Print();
1958                                 PyErr_Clear();
1959                         }
1960                         else {
1961                                 Py_DECREF(ret);
1962                         }
1963                 }
1964
1965                 Py_DECREF(args);
1966         }
1967 }
1968
1969 //----------------------------------------------------------------------------
1970 //Python
1971
1972 PyTypeObject KX_Scene::Type = {
1973         PyVarObject_HEAD_INIT(NULL, 0)
1974         "KX_Scene",
1975         sizeof(PyObjectPlus_Proxy),
1976         0,
1977         py_base_dealloc,
1978         0,
1979         0,
1980         0,
1981         0,
1982         py_base_repr,
1983         0,
1984         &Sequence,
1985         &Mapping,
1986         0,0,0,0,0,0,
1987         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
1988         0,0,0,0,0,0,0,
1989         Methods,
1990         0,
1991         0,
1992         &CValue::Type,
1993         0,0,0,0,0,0,
1994         py_base_new
1995 };
1996
1997 PyMethodDef KX_Scene::Methods[] = {
1998         KX_PYMETHODTABLE(KX_Scene, addObject),
1999         KX_PYMETHODTABLE(KX_Scene, end),
2000         KX_PYMETHODTABLE(KX_Scene, restart),
2001         KX_PYMETHODTABLE(KX_Scene, replace),
2002         KX_PYMETHODTABLE(KX_Scene, suspend),
2003         KX_PYMETHODTABLE(KX_Scene, resume),
2004         KX_PYMETHODTABLE(KX_Scene, drawObstacleSimulation),
2005
2006         
2007         /* dict style access */
2008         KX_PYMETHODTABLE(KX_Scene, get),
2009         
2010         {NULL,NULL} //Sentinel
2011 };
2012 static PyObject *Map_GetItem(PyObject *self_v, PyObject *item)
2013 {
2014         KX_Scene* self= static_cast<KX_Scene*>BGE_PROXY_REF(self_v);
2015         const char *attr_str= _PyUnicode_AsString(item);
2016         PyObject* pyconvert;
2017         
2018         if (self==NULL) {
2019                 PyErr_SetString(PyExc_SystemError, "val = scene[key]: KX_Scene, "BGE_PROXY_ERROR_MSG);
2020                 return NULL;
2021         }
2022         
2023         if (self->m_attr_dict && (pyconvert=PyDict_GetItem(self->m_attr_dict, item))) {
2024                 
2025                 if (attr_str)
2026                         PyErr_Clear();
2027                 Py_INCREF(pyconvert);
2028                 return pyconvert;
2029         }
2030         else {
2031                 if(attr_str)    PyErr_Format(PyExc_KeyError, "value = scene[key]: KX_Scene, key \"%s\" does not exist", attr_str);
2032                 else                    PyErr_SetString(PyExc_KeyError, "value = scene[key]: KX_Scene, key does not exist");
2033                 return NULL;
2034         }
2035                 
2036 }
2037
2038 static int Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val)
2039 {
2040         KX_Scene* self= static_cast<KX_Scene*>BGE_PROXY_REF(self_v);
2041         const char *attr_str= _PyUnicode_AsString(key);
2042         if(attr_str==NULL)
2043                 PyErr_Clear();
2044         
2045         if (self==NULL) {
2046                 PyErr_SetString(PyExc_SystemError, "scene[key] = value: KX_Scene, "BGE_PROXY_ERROR_MSG);
2047                 return -1;
2048         }
2049         
2050         if (val==NULL) { /* del ob["key"] */
2051                 int del= 0;
2052                 
2053                 if(self->m_attr_dict)
2054                         del |= (PyDict_DelItem(self->m_attr_dict, key)==0) ? 1:0;
2055                 
2056                 if (del==0) {
2057                         if(attr_str)    PyErr_Format(PyExc_KeyError, "scene[key] = value: KX_Scene, key \"%s\" could not be set", attr_str);
2058                         else                    PyErr_SetString(PyExc_KeyError, "del scene[key]: KX_Scene, key could not be deleted");
2059                         return -1;
2060                 }
2061                 else if (self->m_attr_dict) {
2062                         PyErr_Clear(); /* PyDict_DelItem sets an error when it fails */
2063                 }
2064         }
2065         else { /* ob["key"] = value */
2066                 int set = 0;
2067
2068                 if (self->m_attr_dict==NULL) /* lazy init */
2069                         self->m_attr_dict= PyDict_New();
2070                 
2071                 
2072                 if(PyDict_SetItem(self->m_attr_dict, key, val)==0)
2073                         set= 1;
2074                 else
2075                         PyErr_SetString(PyExc_KeyError, "scene[key] = value: KX_Scene, key not be added to internal dictionary");
2076         
2077                 if(set==0)
2078                         return -1; /* pythons error value */
2079                 
2080         }
2081         
2082         return 0; /* success */
2083 }
2084
2085 static int Seq_Contains(PyObject *self_v, PyObject *value)
2086 {
2087         KX_Scene* self= static_cast<KX_Scene*>BGE_PROXY_REF(self_v);
2088         
2089         if (self==NULL) {
2090                 PyErr_SetString(PyExc_SystemError, "val in scene: KX_Scene, "BGE_PROXY_ERROR_MSG);
2091                 return -1;
2092         }
2093         
2094         if (self->m_attr_dict && PyDict_GetItem(self->m_attr_dict, value))
2095                 return 1;
2096         
2097         return 0;
2098 }
2099
2100 PyMappingMethods KX_Scene::Mapping = {
2101         (lenfunc)NULL                                   ,                       /*inquiry mp_length */
2102         (binaryfunc)Map_GetItem,                /*binaryfunc mp_subscript */
2103         (objobjargproc)Map_SetItem,     /*objobjargproc mp_ass_subscript */
2104 };
2105
2106 PySequenceMethods KX_Scene::Sequence = {
2107         NULL,           /* Cant set the len otherwise it can evaluate as false */
2108         NULL,           /* sq_concat */
2109         NULL,           /* sq_repeat */
2110         NULL,           /* sq_item */
2111         NULL,           /* sq_slice */
2112         NULL,           /* sq_ass_item */
2113         NULL,           /* sq_ass_slice */
2114         (objobjproc)Seq_Contains,       /* sq_contains */
2115         (binaryfunc) NULL, /* sq_inplace_concat */
2116         (ssizeargfunc) NULL, /* sq_inplace_repeat */
2117 };
2118
2119 PyObject* KX_Scene::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2120 {
2121         KX_Scene* self= static_cast<KX_Scene*>(self_v);
2122         return PyUnicode_FromString(self->GetName().ReadPtr());
2123 }
2124
2125 PyObject* KX_Scene::pyattr_get_objects(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2126 {
2127         KX_Scene* self= static_cast<KX_Scene*>(self_v);
2128         return self->GetObjectList()->GetProxy();
2129 }
2130
2131 PyObject* KX_Scene::pyattr_get_objects_inactive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2132 {
2133         KX_Scene* self= static_cast<KX_Scene*>(self_v);
2134         return self->GetInactiveList()->GetProxy();
2135 }
2136
2137 PyObject* KX_Scene::pyattr_get_lights(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2138 {
2139         KX_Scene* self= static_cast<KX_Scene*>(self_v);
2140         return self->GetLightList()->GetProxy();
2141 }
2142
2143 PyObject* KX_Scene::pyattr_get_cameras(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2144 {
2145         /* With refcounts in this case...
2146          * the new CListValue is owned by python, so its possible python holds onto it longer then the BGE
2147          * however this is the same with "scene.objects + []", when you make a copy by adding lists.
2148          */
2149         
2150         KX_Scene* self= static_cast<KX_Scene*>(self_v);
2151         CListValue* clist = new CListValue();
2152         
2153         /* return self->GetCameras()->GetProxy(); */
2154         
2155         list<KX_Camera*>::iterator it = self->GetCameras()->begin();
2156         while (it != self->GetCameras()->end()) {
2157                 clist->Add((*it)->AddRef());
2158                 it++;
2159         }
2160         
2161         return clist->NewProxy(true);
2162 }
2163
2164 PyObject* KX_Scene::pyattr_get_active_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2165 {
2166         KX_Scene* self= static_cast<KX_Scene*>(self_v);
2167         return self->GetActiveCamera()->GetProxy();
2168 }
2169
2170
2171 int KX_Scene::pyattr_set_active_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2172 {
2173         KX_Scene* self= static_cast<KX_Scene*>(self_v);
2174         KX_Camera *camOb;
2175         
2176         if (!ConvertPythonToCamera(value, &camOb, false, "scene.active_camera = value: KX_Scene"))
2177                 return PY_SET_ATTR_FAIL;
2178         
2179         self->SetActiveCamera(camOb);
2180         return PY_SET_ATTR_SUCCESS;
2181 }
2182
2183 PyObject* KX_Scene::pyattr_get_drawing_callback_pre(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2184 {
2185         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2186
2187         if(self->m_draw_call_pre==NULL)
2188                 self->m_draw_call_pre= PyList_New(0);
2189         Py_INCREF(self->m_draw_call_pre);
2190         return self->m_draw_call_pre;
2191 }
2192
2193 PyObject* KX_Scene::pyattr_get_drawing_callback_post(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2194 {
2195         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2196
2197         if(self->m_draw_call_post==NULL)
2198                 self->m_draw_call_post= PyList_New(0);
2199         Py_INCREF(self->m_draw_call_post);
2200         return self->m_draw_call_post;
2201 }
2202
2203 int KX_Scene::pyattr_set_drawing_callback_pre(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2204 {
2205         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2206
2207         if (!PyList_CheckExact(value))
2208         {
2209                 PyErr_SetString(PyExc_ValueError, "Expected a list");
2210                 return PY_SET_ATTR_FAIL;
2211         }
2212         Py_XDECREF(self->m_draw_call_pre);
2213
2214         Py_INCREF(value);
2215         self->m_draw_call_pre = value;
2216
2217         return PY_SET_ATTR_SUCCESS;
2218 }
2219
2220 int KX_Scene::pyattr_set_drawing_callback_post(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2221 {
2222         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2223
2224         if (!PyList_CheckExact(value))
2225         {
2226                 PyErr_SetString(PyExc_ValueError, "Expected a list");
2227                 return PY_SET_ATTR_FAIL;
2228         }
2229         Py_XDECREF(self->m_draw_call_post);
2230
2231         Py_INCREF(value);
2232         self->m_draw_call_post = value;
2233
2234         return PY_SET_ATTR_SUCCESS;
2235 }
2236
2237 PyAttributeDef KX_Scene::Attributes[] = {
2238         KX_PYATTRIBUTE_RO_FUNCTION("name",                              KX_Scene, pyattr_get_name),
2239         KX_PYATTRIBUTE_RO_FUNCTION("objects",                   KX_Scene, pyattr_get_objects),
2240         KX_PYATTRIBUTE_RO_FUNCTION("objectsInactive",   KX_Scene, pyattr_get_objects_inactive),
2241         KX_PYATTRIBUTE_RO_FUNCTION("lights",                    KX_Scene, pyattr_get_lights),
2242         KX_PYATTRIBUTE_RO_FUNCTION("cameras",                   KX_Scene, pyattr_get_cameras),
2243         KX_PYATTRIBUTE_RO_FUNCTION("lights",                    KX_Scene, pyattr_get_lights),
2244         KX_PYATTRIBUTE_RW_FUNCTION("active_camera",             KX_Scene, pyattr_get_active_camera, pyattr_set_active_camera),
2245         KX_PYATTRIBUTE_RW_FUNCTION("pre_draw",                  KX_Scene, pyattr_get_drawing_callback_pre, pyattr_set_drawing_callback_pre),
2246         KX_PYATTRIBUTE_RW_FUNCTION("post_draw",                 KX_Scene, pyattr_get_drawing_callback_post, pyattr_set_drawing_callback_post),
2247         KX_PYATTRIBUTE_BOOL_RO("suspended",                             KX_Scene, m_suspend),
2248         KX_PYATTRIBUTE_BOOL_RO("activity_culling",              KX_Scene, m_activity_culling),
2249         KX_PYATTRIBUTE_FLOAT_RW("activity_culling_radius", 0.5f, FLT_MAX, KX_Scene, m_activity_box_radius),
2250         KX_PYATTRIBUTE_BOOL_RO("dbvt_culling",                  KX_Scene, m_dbvt_culling),
2251         { NULL }        //Sentinel
2252 };
2253
2254 KX_PYMETHODDEF_DOC(KX_Scene, addObject,
2255 "addObject(object, other, time=0)\n"
2256 "Returns the added object.\n")
2257 {
2258         PyObject *pyob, *pyother;
2259         KX_GameObject *ob, *other;
2260
2261         int time = 0;
2262
2263         if (!PyArg_ParseTuple(args, "OO|i:addObject", &pyob, &pyother, &time))
2264                 return NULL;
2265
2266         if (    !ConvertPythonToGameObject(pyob, &ob, false, "scene.addObject(object, other, time): KX_Scene (first argument)") ||
2267                         !ConvertPythonToGameObject(pyother, &other, false, "scene.addObject(object, other, time): KX_Scene (second argument)") )
2268                 return NULL;
2269
2270
2271         SCA_IObject* replica = AddReplicaObject((SCA_IObject*)ob, other, time);
2272         
2273         // release here because AddReplicaObject AddRef's
2274         // the object is added to the scene so we dont want python to own a reference
2275         replica->Release();
2276         return replica->GetProxy();
2277 }
2278
2279 KX_PYMETHODDEF_DOC(KX_Scene, end,
2280 "end()\n"
2281 "Removes this scene from the game.\n")
2282 {
2283         
2284         KX_GetActiveEngine()->RemoveScene(m_sceneName);
2285         
2286         Py_RETURN_NONE;
2287 }
2288
2289 KX_PYMETHODDEF_DOC(KX_Scene, restart,
2290                                    "restart()\n"
2291                                    "Restarts this scene.\n")
2292 {
2293         KX_GetActiveEngine()->ReplaceScene(m_sceneName, m_sceneName);
2294         
2295         Py_RETURN_NONE;
2296 }
2297
2298 KX_PYMETHODDEF_DOC(KX_Scene, replace,
2299                                    "replace(newScene)\n"
2300                                    "Replaces this scene with another one.\n")
2301 {
2302         char* name;
2303         
2304         if (!PyArg_ParseTuple(args, "s:replace", &name))
2305                 return NULL;
2306         
2307         KX_GetActiveEngine()->ReplaceScene(m_sceneName, name);
2308         
2309         Py_RETURN_NONE;
2310 }
2311
2312 KX_PYMETHODDEF_DOC(KX_Scene, suspend,
2313                                         "suspend()\n"
2314                                         "Suspends this scene.\n")
2315 {
2316         Suspend();
2317         
2318         Py_RETURN_NONE;
2319 }
2320
2321 KX_PYMETHODDEF_DOC(KX_Scene, resume,
2322                                         "resume()\n"
2323                                         "Resumes this scene.\n")
2324 {
2325         Resume();
2326         
2327         Py_RETURN_NONE;
2328 }
2329
2330 KX_PYMETHODDEF_DOC(KX_Scene, drawObstacleSimulation,
2331                                    "drawObstacleSimulation()\n"
2332                                    "Draw debug visualization of obstacle simulation.\n")
2333 {
2334         if (GetObstacleSimulation())
2335                 GetObstacleSimulation()->DrawObstacles();
2336
2337         Py_RETURN_NONE;
2338 }
2339
2340 /* Matches python dict.get(key, [default]) */
2341 KX_PYMETHODDEF_DOC(KX_Scene, get, "")
2342 {
2343         PyObject *key;
2344         PyObject* def = Py_None;
2345         PyObject* ret;
2346
2347         if (!PyArg_ParseTuple(args, "O|O:get", &key, &def))
2348                 return NULL;
2349         
2350         if (m_attr_dict && (ret=PyDict_GetItem(m_attr_dict, key))) {
2351                 Py_INCREF(ret);
2352                 return ret;
2353         }
2354         
2355         Py_INCREF(def);
2356         return def;
2357 }
2358
2359 #endif // WITH_PYTHON