style cleanup: comment blocks
[blender-staging.git] / source / gameengine / Ketsji / KX_Scene.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  * Ketsji scene. Holds references to all scene data.
27  */
28
29 /** \file gameengine/Ketsji/KX_Scene.cpp
30  *  \ingroup ketsji
31  */
32
33
34 #if defined(WIN32) && !defined(FREE_WINDOWS)
35 #pragma warning (disable : 4786)
36 #endif //WIN32
37
38 #include "KX_Scene.h"
39 #include "KX_PythonInit.h"
40 #include "MT_assert.h"
41 #include "KX_KetsjiEngine.h"
42 #include "KX_BlenderMaterial.h"
43 #include "RAS_IPolygonMaterial.h"
44 #include "ListValue.h"
45 #include "SCA_LogicManager.h"
46 #include "SCA_TimeEventManager.h"
47 //#include "SCA_AlwaysEventManager.h"
48 //#include "SCA_RandomEventManager.h"
49 //#include "KX_RayEventManager.h"
50 #include "KX_TouchEventManager.h"
51 #include "SCA_KeyboardManager.h"
52 #include "SCA_MouseManager.h"
53 //#include "SCA_PropertyEventManager.h"
54 #include "SCA_ActuatorEventManager.h"
55 #include "SCA_BasicEventManager.h"
56 #include "KX_Camera.h"
57 #include "SCA_JoystickManager.h"
58
59 #include "RAS_MeshObject.h"
60
61 #include "RAS_IRasterizer.h"
62 #include "RAS_BucketManager.h"
63
64 #include "FloatValue.h"
65 #include "SCA_IController.h"
66 #include "SCA_IActuator.h"
67 #include "SG_Node.h"
68 #include "BL_System.h"
69 #include "SG_Controller.h"
70 #include "SG_IObject.h"
71 #include "SG_Tree.h"
72 #include "DNA_group_types.h"
73 #include "DNA_scene_types.h"
74
75 #include "KX_SG_NodeRelationships.h"
76
77 #include "KX_NetworkEventManager.h"
78 #include "NG_NetworkScene.h"
79 #include "PHY_IPhysicsEnvironment.h"
80 #include "KX_IPhysicsController.h"
81 #include "PHY_IGraphicController.h"
82 #include "KX_BlenderSceneConverter.h"
83 #include "KX_MotionState.h"
84
85 #include "BL_ModifierDeformer.h"
86 #include "BL_ShapeDeformer.h"
87 #include "BL_DeformableGameObject.h"
88 #include "KX_ObstacleSimulation.h"
89
90 #ifdef USE_BULLET
91 #include "KX_SoftBodyDeformer.h"
92 #include "KX_ConvertPhysicsObject.h"
93 #include "CcdPhysicsEnvironment.h"
94 #include "CcdPhysicsController.h"
95 #endif
96
97 #include "KX_Light.h"
98
99 #include <stdio.h>
100
101 void* KX_SceneReplicationFunc(SG_IObject* node,void* gameobj,void* scene)
102 {
103         KX_GameObject* replica = ((KX_Scene*)scene)->AddNodeReplicaObject(node,(KX_GameObject*)gameobj);
104
105         if(replica)
106                 replica->Release();
107
108         return (void*)replica;
109 }
110
111 void* KX_SceneDestructionFunc(SG_IObject* node,void* gameobj,void* scene)
112 {
113         ((KX_Scene*)scene)->RemoveNodeDestructObject(node,(KX_GameObject*)gameobj);
114
115         return NULL;
116 };
117
118 bool KX_Scene::KX_ScenegraphUpdateFunc(SG_IObject* node,void* gameobj,void* scene)
119 {
120         return ((SG_Node*)node)->Schedule(((KX_Scene*)scene)->m_sghead);
121 }
122
123 bool KX_Scene::KX_ScenegraphRescheduleFunc(SG_IObject* node,void* gameobj,void* scene)
124 {
125         return ((SG_Node*)node)->Reschedule(((KX_Scene*)scene)->m_sghead);
126 }
127
128 SG_Callbacks KX_Scene::m_callbacks = SG_Callbacks(
129         KX_SceneReplicationFunc,
130         KX_SceneDestructionFunc,
131         KX_GameObject::UpdateTransformFunc,
132         KX_Scene::KX_ScenegraphUpdateFunc,
133         KX_Scene::KX_ScenegraphRescheduleFunc);
134
135 // temporarily var until there is a button in the userinterface
136 // (defined in KX_PythonInit.cpp)
137 extern bool gUseVisibilityTemp;
138
139 KX_Scene::KX_Scene(class SCA_IInputDevice* keyboarddevice,
140                                    class SCA_IInputDevice* mousedevice,
141                                    class NG_NetworkDeviceInterface *ndi,
142                                    const STR_String& sceneName,
143                                    Scene *scene,
144                                    class RAS_ICanvas* canvas): 
145         PyObjectPlus(),
146         m_keyboardmgr(NULL),
147         m_mousemgr(NULL),
148         m_sceneConverter(NULL),
149         m_physicsEnvironment(0),
150         m_sceneName(sceneName),
151         m_networkDeviceInterface(ndi),
152         m_active_camera(NULL),
153         m_ueberExecutionPriority(0),
154         m_blenderScene(scene)
155 {
156         m_suspendedtime = 0.0;
157         m_suspendeddelta = 0.0;
158
159         m_dbvt_culling = false;
160         m_dbvt_occlusion_res = 0;
161         m_activity_culling = false;
162         m_suspend = false;
163         m_isclearingZbuffer = true;
164         m_tempObjectList = new CListValue();
165         m_objectlist = new CListValue();
166         m_parentlist = new CListValue();
167         m_lightlist= new CListValue();
168         m_inactivelist = new CListValue();
169         m_euthanasyobjects = new CListValue();
170         m_animatedlist = new CListValue();
171
172         m_logicmgr = new SCA_LogicManager();
173         
174         m_timemgr = new SCA_TimeEventManager(m_logicmgr);
175         m_keyboardmgr = new SCA_KeyboardManager(m_logicmgr,keyboarddevice);
176         m_mousemgr = new SCA_MouseManager(m_logicmgr,mousedevice, canvas);
177         
178         //SCA_AlwaysEventManager* alwaysmgr = new SCA_AlwaysEventManager(m_logicmgr);
179         //SCA_PropertyEventManager* propmgr = new SCA_PropertyEventManager(m_logicmgr);
180         SCA_ActuatorEventManager* actmgr = new SCA_ActuatorEventManager(m_logicmgr);
181         //SCA_RandomEventManager* rndmgr = new SCA_RandomEventManager(m_logicmgr);
182         SCA_BasicEventManager* basicmgr = new SCA_BasicEventManager(m_logicmgr);
183         //KX_RayEventManager* raymgr = new KX_RayEventManager(m_logicmgr);
184
185         KX_NetworkEventManager* netmgr = new KX_NetworkEventManager(m_logicmgr, ndi);
186         
187         
188
189         //m_logicmgr->RegisterEventManager(alwaysmgr);
190         //m_logicmgr->RegisterEventManager(propmgr);
191         m_logicmgr->RegisterEventManager(actmgr);
192         m_logicmgr->RegisterEventManager(m_keyboardmgr);
193         m_logicmgr->RegisterEventManager(m_mousemgr);
194         m_logicmgr->RegisterEventManager(m_timemgr);
195         //m_logicmgr->RegisterEventManager(rndmgr);
196         //m_logicmgr->RegisterEventManager(raymgr);
197         m_logicmgr->RegisterEventManager(netmgr);
198         m_logicmgr->RegisterEventManager(basicmgr);
199
200
201         SYS_SystemHandle hSystem = SYS_GetSystem();
202         bool nojoystick= SYS_GetCommandLineInt(hSystem,"nojoystick",0);
203         if (!nojoystick)
204         {
205                 SCA_JoystickManager *joymgr     = new SCA_JoystickManager(m_logicmgr);
206                 m_logicmgr->RegisterEventManager(joymgr);
207         }
208
209         MT_assert (m_networkDeviceInterface != NULL);
210         m_networkScene = new NG_NetworkScene(m_networkDeviceInterface);
211         
212         m_rootnode = NULL;
213
214         m_bucketmanager=new RAS_BucketManager();
215         
216         bool showObstacleSimulation = scene->gm.flag & GAME_SHOW_OBSTACLE_SIMULATION;
217         switch (scene->gm.obstacleSimulation)
218         {
219         case OBSTSIMULATION_TOI_rays:
220                 m_obstacleSimulation = new KX_ObstacleSimulationTOI_rays((MT_Scalar)scene->gm.levelHeight, showObstacleSimulation);
221                 break;
222         case OBSTSIMULATION_TOI_cells:
223                 m_obstacleSimulation = new KX_ObstacleSimulationTOI_cells((MT_Scalar)scene->gm.levelHeight, showObstacleSimulation);
224                 break;
225         default:
226                 m_obstacleSimulation = NULL;
227         }
228         
229 #ifdef WITH_PYTHON
230         m_attr_dict = PyDict_New(); /* new ref */
231         m_draw_call_pre = NULL;
232         m_draw_call_post = NULL;
233 #endif
234 }
235
236
237
238 KX_Scene::~KX_Scene()
239 {
240         // The release of debug properties used to be in SCA_IScene::~SCA_IScene
241         // It's still there but we remove all properties here otherwise some
242         // reference might be hanging and causing late release of objects
243         RemoveAllDebugProperties();
244
245         while (GetRootParentList()->GetCount() > 0) 
246         {
247                 KX_GameObject* parentobj = (KX_GameObject*) GetRootParentList()->GetValue(0);
248                 this->RemoveObject(parentobj);
249         }
250
251         if (m_obstacleSimulation)
252                 delete m_obstacleSimulation;
253
254         if(m_objectlist)
255                 m_objectlist->Release();
256
257         if (m_parentlist)
258                 m_parentlist->Release();
259         
260         if (m_inactivelist)
261                 m_inactivelist->Release();
262
263         if (m_lightlist)
264                 m_lightlist->Release();
265         
266         if (m_tempObjectList)
267                 m_tempObjectList->Release();
268
269         if (m_euthanasyobjects)
270                 m_euthanasyobjects->Release();
271
272         if (m_animatedlist)
273                 m_animatedlist->Release();
274
275         if (m_logicmgr)
276                 delete m_logicmgr;
277
278         if (m_physicsEnvironment)
279                 delete m_physicsEnvironment;
280
281         if (m_networkScene)
282                 delete m_networkScene;
283         
284         if (m_bucketmanager)
285         {
286                 delete m_bucketmanager;
287         }
288
289 #ifdef WITH_PYTHON
290         PyDict_Clear(m_attr_dict);
291         /* Py_CLEAR: Py_DECREF's and NULL's */
292         Py_CLEAR(m_attr_dict);
293
294         /* these may be NULL but the macro checks */
295         Py_CLEAR(m_draw_call_pre);
296         Py_CLEAR(m_draw_call_post);
297 #endif
298 }
299
300 RAS_BucketManager* KX_Scene::GetBucketManager()
301 {
302         return m_bucketmanager;
303 }
304
305
306 CListValue* KX_Scene::GetTempObjectList()
307 {
308         return m_tempObjectList;
309 }
310
311 CListValue* KX_Scene::GetObjectList()
312 {
313         return m_objectlist;
314 }
315
316
317 CListValue* KX_Scene::GetRootParentList()
318 {
319         return m_parentlist;
320 }
321
322 CListValue* KX_Scene::GetInactiveList()
323 {
324         return m_inactivelist;
325 }
326
327
328
329 CListValue* KX_Scene::GetLightList()
330 {
331         return m_lightlist;
332 }
333
334 SCA_LogicManager* KX_Scene::GetLogicManager()
335 {
336         return m_logicmgr;
337 }
338
339 SCA_TimeEventManager* KX_Scene::GetTimeEventManager()
340 {
341         return m_timemgr;
342 }
343
344
345
346  
347 list<class KX_Camera*>* KX_Scene::GetCameras()
348 {
349         return &m_cameras;
350 }
351
352 list<class KX_FontObject*>* KX_Scene::GetFonts()
353 {
354         return &m_fonts;
355 }
356
357 void KX_Scene::SetFramingType(RAS_FrameSettings & frame_settings)
358 {
359         m_frame_settings = frame_settings;
360 };
361
362 /**
363  * Return a const reference to the framing 
364  * type set by the above call.
365  * The contents are not guaranteed to be sensible
366  * if you don't call the above function.
367  */
368 const RAS_FrameSettings& KX_Scene::GetFramingType() const 
369 {
370         return m_frame_settings;
371 };      
372
373
374
375 /**
376  * Store the current scene's viewport on the 
377  * game engine canvas.
378  */
379 void KX_Scene::SetSceneViewport(const RAS_Rect &viewport)
380 {
381         m_viewport = viewport;
382 }
383
384
385
386 const RAS_Rect& KX_Scene::GetSceneViewport() const 
387 {
388         return m_viewport;
389 }
390
391
392
393 void KX_Scene::SetWorldInfo(class KX_WorldInfo* worldinfo)
394 {
395         m_worldinfo = worldinfo;
396 }
397
398
399
400 class KX_WorldInfo* KX_Scene::GetWorldInfo()
401 {
402         return m_worldinfo;
403 }
404
405
406 const STR_String& KX_Scene::GetName()
407 {
408         return m_sceneName;
409 }
410
411
412 void KX_Scene::Suspend()
413 {
414         m_suspend = true;
415 }
416
417 void KX_Scene::Resume()
418 {
419         m_suspend = false;
420 }
421
422 void KX_Scene::SetActivityCulling(bool b)
423 {
424         m_activity_culling = b;
425 }
426
427 bool KX_Scene::IsSuspended()
428 {
429         return m_suspend;
430 }
431
432 bool KX_Scene::IsClearingZBuffer()
433 {
434         return m_isclearingZbuffer;
435 }
436
437 void KX_Scene::EnableZBufferClearing(bool isclearingZbuffer)
438 {
439         m_isclearingZbuffer = isclearingZbuffer;
440 }
441
442 void KX_Scene::RemoveNodeDestructObject(class SG_IObject* node,class CValue* gameobj)
443 {
444         KX_GameObject* orgobj = (KX_GameObject*)gameobj;        
445         if (NewRemoveObject(orgobj) != 0)
446         {
447                 // object is not yet deleted because a reference is hanging somewhere.
448                 // This should not happen anymore since we use proxy object for Python
449                 // confident enough to put an assert?
450                 //assert(false);
451                 printf("Zombie object! name=%s\n", orgobj->GetName().ReadPtr());
452                 orgobj->SetSGNode(NULL);
453                 PHY_IGraphicController* ctrl = orgobj->GetGraphicController();
454                 if (ctrl)
455                 {
456                         // a graphic controller is set, we must delete it as the node will be deleted
457                         delete ctrl;
458                         orgobj->SetGraphicController(NULL);
459                 }
460         }
461         if (node)
462                 delete node;
463 }
464
465 KX_GameObject* KX_Scene::AddNodeReplicaObject(class SG_IObject* node, class CValue* gameobj)
466 {
467         // for group duplication, limit the duplication of the hierarchy to the
468         // objects that are part of the group. 
469         if (!IsObjectInGroup(gameobj))
470                 return NULL;
471         
472         KX_GameObject* orgobj = (KX_GameObject*)gameobj;
473         KX_GameObject* newobj = (KX_GameObject*)orgobj->GetReplica();
474         m_map_gameobject_to_replica.insert(orgobj, newobj);
475
476         // also register 'timers' (time properties) of the replica
477         int numprops = newobj->GetPropertyCount();
478
479         for (int i = 0; i < numprops; i++)
480         {
481                 CValue* prop = newobj->GetProperty(i);
482
483                 if (prop->GetProperty("timer"))
484                         this->m_timemgr->AddTimeProperty(prop);
485         }
486
487         if (node)
488         {
489                 newobj->SetSGNode((SG_Node*)node);
490         }
491         else
492         {
493                 m_rootnode = new SG_Node(newobj,this,KX_Scene::m_callbacks);
494         
495                 // this fixes part of the scaling-added object bug
496                 SG_Node* orgnode = orgobj->GetSGNode();
497                 m_rootnode->SetLocalScale(orgnode->GetLocalScale());
498                 m_rootnode->SetLocalPosition(orgnode->GetLocalPosition());
499                 m_rootnode->SetLocalOrientation(orgnode->GetLocalOrientation());
500
501                 // define the relationship between this node and it's parent.
502                 KX_NormalParentRelation * parent_relation = 
503                         KX_NormalParentRelation::New();
504                 m_rootnode->SetParentRelation(parent_relation);
505
506                 newobj->SetSGNode(m_rootnode);
507         }
508         
509         SG_IObject* replicanode = newobj->GetSGNode();
510 //      SG_Node* rootnode = (replicanode == m_rootnode ? NULL : m_rootnode);
511
512         replicanode->SetSGClientObject(newobj);
513
514         // this is the list of object that are send to the graphics pipeline
515         m_objectlist->Add(newobj->AddRef());
516         if (newobj->GetGameObjectType()==SCA_IObject::OBJ_LIGHT)
517                 m_lightlist->Add(newobj->AddRef());
518         newobj->AddMeshUser();
519
520         // logic cannot be replicated, until the whole hierarchy is replicated.
521         m_logicHierarchicalGameObjects.push_back(newobj);
522         //replicate controllers of this node
523         SGControllerList        scenegraphcontrollers = orgobj->GetSGNode()->GetSGControllerList();
524         replicanode->RemoveAllControllers();
525         SGControllerList::iterator cit;
526         //int numcont = scenegraphcontrollers.size();
527         
528         for (cit = scenegraphcontrollers.begin();!(cit==scenegraphcontrollers.end());++cit)
529         {
530                 // controller replication is quite complicated
531                 // only replicate ipo and physics controller for now
532
533                 SG_Controller* replicacontroller = (*cit)->GetReplica((SG_Node*) replicanode);
534                 if (replicacontroller)
535                 {
536                         replicacontroller->SetObject(replicanode);
537                         replicanode->AddSGController(replicacontroller);
538                 }
539         }
540         // replicate graphic controller
541         if (orgobj->GetGraphicController())
542         {
543                 PHY_IMotionState* motionstate = new KX_MotionState(newobj->GetSGNode());
544                 PHY_IGraphicController* newctrl = orgobj->GetGraphicController()->GetReplica(motionstate);
545                 newctrl->setNewClientInfo(newobj->getClientInfo());
546                 newobj->SetGraphicController(newctrl);
547         }
548         return newobj;
549 }
550
551
552
553 // before calling this method KX_Scene::ReplicateLogic(), make sure to
554 // have called 'GameObject::ReParentLogic' for each object this
555 // hierarchy that's because first ALL bricks must exist in the new
556 // replica of the hierarchy in order to make cross-links work properly
557 // !
558 // It is VERY important that the order of sensors and actuators in
559 // the replicated object is preserved: it is used to reconnect the logic.
560 // This method is more robust then using the bricks name in case of complex 
561 // group replication. The replication of logic bricks is done in 
562 // SCA_IObject::ReParentLogic(), make sure it preserves the order of the bricks.
563 void KX_Scene::ReplicateLogic(KX_GameObject* newobj)
564 {
565         // also relink the controller to sensors/actuators
566         SCA_ControllerList& controllers = newobj->GetControllers();
567         //SCA_SensorList&     sensors     = newobj->GetSensors();
568         //SCA_ActuatorList&   actuators   = newobj->GetActuators();
569
570         for (SCA_ControllerList::iterator itc = controllers.begin(); !(itc==controllers.end());itc++)
571         {
572                 SCA_IController* cont = (*itc);
573                 cont->SetUeberExecutePriority(m_ueberExecutionPriority);
574                 vector<SCA_ISensor*> linkedsensors = cont->GetLinkedSensors();
575                 vector<SCA_IActuator*> linkedactuators = cont->GetLinkedActuators();
576
577                 // disconnect the sensors and actuators
578                 // do it directly on the list at this controller is not connected to anything at this stage
579                 cont->GetLinkedSensors().clear();
580                 cont->GetLinkedActuators().clear();
581                 
582                 // now relink each sensor
583                 for (vector<SCA_ISensor*>::iterator its = linkedsensors.begin();!(its==linkedsensors.end());its++)
584                 {
585                         SCA_ISensor* oldsensor = (*its);
586                         SCA_IObject* oldsensorobj = oldsensor->GetParent();
587                         SCA_IObject* newsensorobj = NULL;
588                 
589                         // the original owner of the sensor has been replicated?
590                         void **h_obj = m_map_gameobject_to_replica[oldsensorobj];
591                         if (h_obj)
592                                 newsensorobj = (SCA_IObject*)(*h_obj);
593                         if (!newsensorobj)
594                         {
595                                 // no, then the sensor points outside the hierachy, keep it the same
596                                 if (m_objectlist->SearchValue(oldsensorobj))
597                                         // only replicate links that points to active objects
598                                         m_logicmgr->RegisterToSensor(cont,oldsensor);
599                         }
600                         else
601                         {
602                                 // yes, then the new sensor has the same position
603                                 SCA_SensorList& sensorlist = oldsensorobj->GetSensors();
604                                 SCA_SensorList::iterator sit;
605                                 SCA_ISensor* newsensor = NULL;
606                                 int sensorpos;
607
608                                 for (sensorpos=0, sit=sensorlist.begin(); sit!=sensorlist.end(); sit++, sensorpos++)
609                                 {
610                                         if ((*sit) == oldsensor) 
611                                         {
612                                                 newsensor = newsensorobj->GetSensors().at(sensorpos);
613                                                 break;
614                                         }
615                                 }
616                                 assert(newsensor != NULL);
617                                 m_logicmgr->RegisterToSensor(cont,newsensor);
618                         }
619                 }
620                 
621                 // now relink each actuator
622                 for (vector<SCA_IActuator*>::iterator ita = linkedactuators.begin();!(ita==linkedactuators.end());ita++)
623                 {
624                         SCA_IActuator* oldactuator = (*ita);
625                         SCA_IObject* oldactuatorobj = oldactuator->GetParent();
626                         SCA_IObject* newactuatorobj = NULL;
627
628                         // the original owner of the sensor has been replicated?
629                         void **h_obj = m_map_gameobject_to_replica[oldactuatorobj];
630                         if (h_obj)
631                                 newactuatorobj = (SCA_IObject*)(*h_obj);
632
633                         if (!newactuatorobj)
634                         {
635                                 // no, then the sensor points outside the hierachy, keep it the same
636                                 if (m_objectlist->SearchValue(oldactuatorobj))
637                                         // only replicate links that points to active objects
638                                         m_logicmgr->RegisterToActuator(cont,oldactuator);
639                         }
640                         else
641                         {
642                                 // yes, then the new sensor has the same position
643                                 SCA_ActuatorList& actuatorlist = oldactuatorobj->GetActuators();
644                                 SCA_ActuatorList::iterator ait;
645                                 SCA_IActuator* newactuator = NULL;
646                                 int actuatorpos;
647
648                                 for (actuatorpos=0, ait=actuatorlist.begin(); ait!=actuatorlist.end(); ait++, actuatorpos++)
649                                 {
650                                         if ((*ait) == oldactuator) 
651                                         {
652                                                 newactuator = newactuatorobj->GetActuators().at(actuatorpos);
653                                                 break;
654                                         }
655                                 }
656                                 assert(newactuator != NULL);
657                                 m_logicmgr->RegisterToActuator(cont,newactuator);
658                                 newactuator->SetUeberExecutePriority(m_ueberExecutionPriority);
659                         }
660                 }
661         }
662         // ready to set initial state
663         newobj->ResetState();
664 }
665
666 void KX_Scene::DupliGroupRecurse(CValue* obj, int level)
667 {
668         KX_GameObject* groupobj = (KX_GameObject*) obj;
669         KX_GameObject* replica;
670         KX_GameObject* gameobj;
671         Object* blgroupobj = groupobj->GetBlenderObject();
672         Group* group;
673         GroupObject *go;
674         vector<KX_GameObject*> duplilist;
675
676         if (!groupobj->GetSGNode() ||
677                 !groupobj->IsDupliGroup() ||
678                 level>MAX_DUPLI_RECUR)
679                 return;
680
681         // we will add one group at a time
682         m_logicHierarchicalGameObjects.clear();
683         m_map_gameobject_to_replica.clear();
684         m_ueberExecutionPriority++;
685         // for groups will do something special: 
686         // we will force the creation of objects to those in the group only
687         // Again, this is match what Blender is doing (it doesn't care of parent relationship)
688         m_groupGameObjects.clear();
689
690         group = blgroupobj->dup_group;
691         for(go=(GroupObject*)group->gobject.first; go; go=(GroupObject*)go->next) 
692         {
693                 Object* blenderobj = go->ob;
694                 if (blgroupobj == blenderobj)
695                         // this check is also in group_duplilist()
696                         continue;
697
698                 gameobj = (KX_GameObject*)m_logicmgr->FindGameObjByBlendObj(blenderobj);
699                 if (gameobj == NULL) 
700                 {
701                         // this object has not been converted!!!
702                         // Should not happen as dupli group are created automatically 
703                         continue;
704                 }
705
706                 gameobj->SetBlenderGroupObject(blgroupobj);
707
708                 if ((blenderobj->lay & group->layer)==0)
709                 {
710                         // object is not visible in the 3D view, will not be instantiated
711                         continue;
712                 }
713                 m_groupGameObjects.insert(gameobj);
714         }
715
716         set<CValue*>::iterator oit;
717         for (oit=m_groupGameObjects.begin(); oit != m_groupGameObjects.end(); oit++)
718         {
719                 gameobj = (KX_GameObject*)(*oit);
720
721                 KX_GameObject *parent = gameobj->GetParent();
722                 if (parent != NULL)
723                 {
724                         parent->Release(); // GetParent() increased the refcount
725
726                         // this object is not a top parent. Either it is the child of another
727                         // object in the group and it will be added automatically when the parent
728                         // is added. Or it is the child of an object outside the group and the group
729                         // is inconsistent, skip it anyway
730                         continue;
731                 }
732                 replica = (KX_GameObject*) AddNodeReplicaObject(NULL,gameobj);
733                 // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame)
734                 m_parentlist->Add(replica->AddRef());
735
736                 // recurse replication into children nodes
737                 NodeList& children = gameobj->GetSGNode()->GetSGChildren();
738
739                 replica->GetSGNode()->ClearSGChildren();
740                 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
741                 {
742                         SG_Node* orgnode = (*childit);
743                         SG_Node* childreplicanode = orgnode->GetSGReplica();
744                         if (childreplicanode)
745                                 replica->GetSGNode()->AddChild(childreplicanode);
746                 }
747                 // don't replicate logic now: we assume that the objects in the group can have
748                 // logic relationship, even outside parent relationship
749                 // In order to match 3D view, the position of groupobj is used as a 
750                 // transformation matrix instead of the new position. This means that 
751                 // the group reference point is 0,0,0
752
753                 // get the rootnode's scale
754                 MT_Vector3 newscale = groupobj->NodeGetWorldScaling();
755                 // set the replica's relative scale with the rootnode's scale
756                 replica->NodeSetRelativeScale(newscale);
757
758                 MT_Point3 offset(group->dupli_ofs);
759                 MT_Point3 newpos = groupobj->NodeGetWorldPosition() + 
760                         newscale*(groupobj->NodeGetWorldOrientation() * (gameobj->NodeGetWorldPosition()-offset));
761                 replica->NodeSetLocalPosition(newpos);
762                 // set the orientation after position for softbody!
763                 MT_Matrix3x3 newori = groupobj->NodeGetWorldOrientation() * gameobj->NodeGetWorldOrientation();
764                 replica->NodeSetLocalOrientation(newori);
765                 // update scenegraph for entire tree of children
766                 replica->GetSGNode()->UpdateWorldData(0);
767                 replica->GetSGNode()->SetBBox(gameobj->GetSGNode()->BBox());
768                 replica->GetSGNode()->SetRadius(gameobj->GetSGNode()->Radius());
769                 // we can now add the graphic controller to the physic engine
770                 replica->ActivateGraphicController(true);
771
772                 // done with replica
773                 replica->Release();
774         }
775
776         // the logic must be replicated first because we need
777         // the new logic bricks before relinking
778         vector<KX_GameObject*>::iterator git;
779         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
780         {
781                 (*git)->ReParentLogic();
782         }
783         
784         //      relink any pointers as necessary, sort of a temporary solution
785         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
786         {
787                 // this will also relink the actuator to objects within the hierarchy
788                 (*git)->Relink(&m_map_gameobject_to_replica);
789                 // add the object in the layer of the parent
790                 (*git)->SetLayer(groupobj->GetLayer());
791                 // If the object was a light, we need to update it's RAS_LightObject as well
792                 if ((*git)->GetGameObjectType()==SCA_IObject::OBJ_LIGHT)
793                 {
794                         KX_LightObject* lightobj = static_cast<KX_LightObject*>(*git);
795                         lightobj->GetLightData()->m_layer = groupobj->GetLayer();
796                 }
797         }
798
799         // replicate crosslinks etc. between logic bricks
800         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
801         {
802                 ReplicateLogic((*git));
803         }
804         
805         // now look if object in the hierarchy have dupli group and recurse
806         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
807         {
808                 if ((*git) != groupobj && (*git)->IsDupliGroup())
809                         // can't instantiate group immediately as it destroys m_logicHierarchicalGameObjects
810                         duplilist.push_back((*git));
811         }
812
813         for (git = duplilist.begin(); !(git == duplilist.end()); ++git)
814         {
815                 DupliGroupRecurse((*git), level+1);
816         }
817 }
818
819
820 SCA_IObject* KX_Scene::AddReplicaObject(class CValue* originalobject,
821                                                                                 class CValue* parentobject,
822                                                                                 int lifespan)
823 {
824
825         m_logicHierarchicalGameObjects.clear();
826         m_map_gameobject_to_replica.clear();
827         m_groupGameObjects.clear();
828
829         // todo: place a timebomb in the object, for temporarily objects :)
830         // lifespan of zero means 'this object lives forever'
831         KX_GameObject* originalobj = (KX_GameObject*) originalobject;
832         KX_GameObject* parentobj = (KX_GameObject*) parentobject;
833
834         m_ueberExecutionPriority++;
835
836         // lets create a replica
837         KX_GameObject* replica = (KX_GameObject*) AddNodeReplicaObject(NULL,originalobj);
838
839         if (lifespan > 0)
840         {
841                 // add a timebomb to this object
842                 // for now, convert between so called frames and realtime
843                 m_tempObjectList->Add(replica->AddRef());
844                 // this convert the life from frames to sort-of seconds, hard coded 0.02 that assumes we have 50 frames per second
845                 // if you change this value, make sure you change it in KX_GameObject::pyattr_get_life property too
846                 CValue *fval = new CFloatValue(lifespan*0.02);
847                 replica->SetProperty("::timebomb",fval);
848                 fval->Release();
849         }
850
851         // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame)
852         m_parentlist->Add(replica->AddRef());
853
854         // recurse replication into children nodes
855
856         NodeList& children = originalobj->GetSGNode()->GetSGChildren();
857
858         replica->GetSGNode()->ClearSGChildren();
859         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
860         {
861                 SG_Node* orgnode = (*childit);
862                 SG_Node* childreplicanode = orgnode->GetSGReplica();
863                 if (childreplicanode)
864                         replica->GetSGNode()->AddChild(childreplicanode);
865         }
866
867         // At this stage all the objects in the hierarchy have been duplicated,
868         // we can update the scenegraph, we need it for the duplication of logic
869         MT_Point3 newpos = ((KX_GameObject*) parentobject)->NodeGetWorldPosition();
870         replica->NodeSetLocalPosition(newpos);
871
872         MT_Matrix3x3 newori = ((KX_GameObject*) parentobject)->NodeGetWorldOrientation();
873         replica->NodeSetLocalOrientation(newori);
874         
875         // get the rootnode's scale
876         MT_Vector3 newscale = parentobj->GetSGNode()->GetRootSGParent()->GetLocalScale();
877
878         // set the replica's relative scale with the rootnode's scale
879         replica->NodeSetRelativeScale(newscale);
880
881         replica->GetSGNode()->UpdateWorldData(0);
882         replica->GetSGNode()->SetBBox(originalobj->GetSGNode()->BBox());
883         replica->GetSGNode()->SetRadius(originalobj->GetSGNode()->Radius());
884         // the size is correct, we can add the graphic controller to the physic engine
885         replica->ActivateGraphicController(true);
886
887         // now replicate logic
888         vector<KX_GameObject*>::iterator git;
889         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
890         {
891                 (*git)->ReParentLogic();
892         }
893         
894         //      relink any pointers as necessary, sort of a temporary solution
895         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
896         {
897                 // this will also relink the actuators in the hierarchy
898                 (*git)->Relink(&m_map_gameobject_to_replica);
899                 // add the object in the layer of the parent
900                 (*git)->SetLayer(parentobj->GetLayer());
901                 // If the object was a light, we need to update it's RAS_LightObject as well
902                 if ((*git)->GetGameObjectType()==SCA_IObject::OBJ_LIGHT)
903                 {
904                         KX_LightObject* lightobj = static_cast<KX_LightObject*>(*git);
905                         lightobj->GetLightData()->m_layer = parentobj->GetLayer();
906                 }
907         }
908
909         // replicate crosslinks etc. between logic bricks
910         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
911         {
912                 ReplicateLogic((*git));
913         }
914         
915         // check if there are objects with dupligroup in the hierarchy
916         vector<KX_GameObject*> duplilist;
917         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
918         {
919                 if ((*git)->IsDupliGroup())
920                 {
921                         // separate list as m_logicHierarchicalGameObjects is also used by DupliGroupRecurse()
922                         duplilist.push_back(*git);
923                 }
924         }
925         for (git = duplilist.begin();!(git==duplilist.end());++git)
926         {
927                 DupliGroupRecurse(*git, 0);
928         }
929         //      don't release replica here because we are returning it, not done with it...
930         return replica;
931 }
932
933
934
935 void KX_Scene::RemoveObject(class CValue* gameobj)
936 {
937         KX_GameObject* newobj = (KX_GameObject*) gameobj;
938
939         // disconnect child from parent
940         SG_Node* node = newobj->GetSGNode();
941
942         if (node)
943         {
944                 node->DisconnectFromParent();
945
946                 // recursively destruct
947                 node->Destruct();
948         }
949         //no need to do that: the object is destroyed and memory released 
950         //newobj->SetSGNode(0);
951 }
952
953 void KX_Scene::DelayedRemoveObject(class CValue* gameobj)
954 {
955         //KX_GameObject* newobj = (KX_GameObject*) gameobj;
956         if (!m_euthanasyobjects->SearchValue(gameobj))
957         {
958                 m_euthanasyobjects->Add(gameobj->AddRef());
959         } 
960 }
961
962
963
964 int KX_Scene::NewRemoveObject(class CValue* gameobj)
965 {
966         int ret;
967         KX_GameObject* newobj = (KX_GameObject*) gameobj;
968
969         /* Invalidate the python reference, since the object may exist in script lists
970          * its possible that it wont be automatically invalidated, so do it manually here,
971          * 
972          * if for some reason the object is added back into the scene python can always get a new Proxy
973          */
974         newobj->InvalidateProxy();
975
976         // keep the blender->game object association up to date
977         // note that all the replicas of an object will have the same
978         // blender object, that's why we need to check the game object
979         // as only the deletion of the original object must be recorded
980         m_logicmgr->UnregisterGameObj(newobj->GetBlenderObject(), gameobj);
981
982         //todo: look at this
983         //GetPhysicsEnvironment()->RemovePhysicsController(gameobj->getPhysicsController());
984
985         // remove all sensors/controllers/actuators from logicsystem...
986         
987         SCA_SensorList& sensors = newobj->GetSensors();
988         for (SCA_SensorList::iterator its = sensors.begin();
989                  !(its==sensors.end());its++)
990         {
991                 m_logicmgr->RemoveSensor(*its);
992         }
993
994         SCA_ControllerList& controllers = newobj->GetControllers();
995         for (SCA_ControllerList::iterator itc = controllers.begin();
996                  !(itc==controllers.end());itc++)
997         {
998                 m_logicmgr->RemoveController(*itc);
999         }
1000
1001         SCA_ActuatorList& actuators = newobj->GetActuators();
1002         for (SCA_ActuatorList::iterator ita = actuators.begin();
1003                  !(ita==actuators.end());ita++)
1004         {
1005                 m_logicmgr->RemoveActuator(*ita);
1006         }
1007         // the sensors/controllers/actuators must also be released, this is done in ~SCA_IObject
1008
1009         // now remove the timer properties from the time manager
1010         int numprops = newobj->GetPropertyCount();
1011
1012         for (int i = 0; i < numprops; i++)
1013         {
1014                 CValue* propval = newobj->GetProperty(i);
1015                 if (propval->GetProperty("timer"))
1016                 {
1017                         m_timemgr->RemoveTimeProperty(propval);
1018                 }
1019         }
1020         
1021         newobj->RemoveMeshes();
1022         ret = 1;
1023         if (newobj->GetGameObjectType()==SCA_IObject::OBJ_LIGHT && m_lightlist->RemoveValue(newobj))
1024                 ret = newobj->Release();
1025         if (m_objectlist->RemoveValue(newobj))
1026                 ret = newobj->Release();
1027         if (m_tempObjectList->RemoveValue(newobj))
1028                 ret = newobj->Release();
1029         if (m_parentlist->RemoveValue(newobj))
1030                 ret = newobj->Release();
1031         if (m_inactivelist->RemoveValue(newobj))
1032                 ret = newobj->Release();
1033         if (m_euthanasyobjects->RemoveValue(newobj))
1034                 ret = newobj->Release();
1035         if (m_animatedlist->RemoveValue(newobj))
1036                 ret = newobj->Release();
1037                 
1038         if (newobj == m_active_camera)
1039         {
1040                 //no AddRef done on m_active_camera so no Release
1041                 //m_active_camera->Release();
1042                 m_active_camera = NULL;
1043         }
1044
1045         // in case this is a camera
1046         m_cameras.remove((KX_Camera*)newobj);
1047
1048         // in case this is a font
1049         m_fonts.remove((KX_FontObject*)newobj);
1050
1051         /* currently does nothing, keep in case we need to Unregister something */
1052 #if 0
1053         if (m_sceneConverter)
1054                 m_sceneConverter->UnregisterGameObject(newobj);
1055 #endif
1056         
1057         // return value will be 0 if the object is actually deleted (all reference gone)
1058         
1059         return ret;
1060 }
1061
1062
1063
1064 void KX_Scene::ReplaceMesh(class CValue* obj,void* meshobj, bool use_gfx, bool use_phys)
1065 {
1066         KX_GameObject* gameobj = static_cast<KX_GameObject*>(obj);
1067         RAS_MeshObject* mesh = static_cast<RAS_MeshObject*>(meshobj);
1068
1069         if(!gameobj) {
1070                 std::cout << "KX_Scene::ReplaceMesh Warning: invalid object, doing nothing" << std::endl;
1071                 return;
1072         }
1073
1074         if(use_gfx && mesh != NULL)
1075         {               
1076         gameobj->RemoveMeshes();
1077         gameobj->AddMesh(mesh);
1078         
1079         if (gameobj->m_isDeformable)
1080         {
1081                 BL_DeformableGameObject* newobj = static_cast<BL_DeformableGameObject*>( gameobj );
1082                 
1083                 if (newobj->GetDeformer())
1084                 {
1085                         delete newobj->GetDeformer();
1086                         newobj->SetDeformer(NULL);
1087                 }
1088
1089                 if (mesh->GetMesh()) 
1090                 {
1091                         // we must create a new deformer but which one?
1092                         KX_GameObject* parentobj = newobj->GetParent();
1093                         // this always return the original game object (also for replicate)
1094                         Object* blendobj = newobj->GetBlenderObject();
1095                         // object that owns the new mesh
1096                         Object* oldblendobj = static_cast<struct Object*>(m_logicmgr->FindBlendObjByGameMeshName(mesh->GetName()));
1097                         Mesh* blendmesh = mesh->GetMesh();
1098
1099                         bool bHasModifier = BL_ModifierDeformer::HasCompatibleDeformer(blendobj);
1100                         bool bHasShapeKey = blendmesh->key != NULL && blendmesh->key->type==KEY_RELATIVE;
1101                         bool bHasDvert = blendmesh->dvert != NULL;
1102                         bool bHasArmature = 
1103                                 BL_ModifierDeformer::HasArmatureDeformer(blendobj) &&
1104                                 parentobj &&                                                            // current parent is armature
1105                                 parentobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE &&
1106                                 oldblendobj &&                                                          // needed for mesh deform
1107                                 blendobj->parent &&                                                     // original object had armature (not sure this test is needed)
1108                                 blendobj->parent->type == OB_ARMATURE &&
1109                                 blendmesh->dvert!=NULL;                                         // mesh has vertex group
1110 #ifdef USE_BULLET
1111                         bool bHasSoftBody = (!parentobj && (blendobj->gameflag & OB_SOFT_BODY));
1112 #endif
1113                         bool releaseParent = true;
1114
1115                         
1116                         if (oldblendobj==NULL) {
1117                                 if (bHasModifier || bHasShapeKey || bHasDvert || bHasArmature) {
1118                                         std::cout << "warning: ReplaceMesh() new mesh is not used in an object from the current scene, you will get incorrect behavior" << std::endl;
1119                                         bHasShapeKey= bHasDvert= bHasArmature=bHasModifier= false;
1120                                 }
1121                         }
1122                         
1123                         if (bHasModifier)
1124                         {
1125                                 BL_ModifierDeformer* modifierDeformer;
1126                                 if (bHasShapeKey || bHasArmature)
1127                                 {
1128                                         modifierDeformer = new BL_ModifierDeformer(
1129                                                 newobj,
1130                                                 m_blenderScene,
1131                                                 oldblendobj, blendobj,
1132                                                 mesh,
1133                                                 true,
1134                                                 static_cast<BL_ArmatureObject*>( parentobj )
1135                                         );
1136                                         releaseParent= false;
1137                                         modifierDeformer->LoadShapeDrivers(blendobj->parent);
1138                                 }
1139                                 else
1140                                 {
1141                                         modifierDeformer = new BL_ModifierDeformer(
1142                                                 newobj,
1143                                                 m_blenderScene,
1144                                                 oldblendobj, blendobj,
1145                                                 mesh,
1146                                                 false,
1147                                                 NULL
1148                                         );
1149                                 }
1150                                 newobj->SetDeformer(modifierDeformer);
1151                         } 
1152                         else    if (bHasShapeKey)
1153                         {
1154                                 BL_ShapeDeformer* shapeDeformer;
1155                                 if (bHasArmature) 
1156                                 {
1157                                         shapeDeformer = new BL_ShapeDeformer(
1158                                                 newobj,
1159                                                 oldblendobj, blendobj,
1160                                                 mesh,
1161                                                 true,
1162                                                 true,
1163                                                 static_cast<BL_ArmatureObject*>( parentobj )
1164                                         );
1165                                         releaseParent= false;
1166                                         shapeDeformer->LoadShapeDrivers(blendobj->parent);
1167                                 }
1168                                 else
1169                                 {
1170                                         shapeDeformer = new BL_ShapeDeformer(
1171                                                 newobj,
1172                                                 oldblendobj, blendobj,
1173                                                 mesh,
1174                                                 false,
1175                                                 true,
1176                                                 NULL
1177                                         );
1178                                 }
1179                                 newobj->SetDeformer( shapeDeformer);
1180                         }
1181                         else if (bHasArmature) 
1182                         {
1183                                 BL_SkinDeformer* skinDeformer = new BL_SkinDeformer(
1184                                         newobj,
1185                                         oldblendobj, blendobj,
1186                                         mesh,
1187                                         true,
1188                                         true,
1189                                         static_cast<BL_ArmatureObject*>( parentobj )
1190                                 );
1191                                 releaseParent= false;
1192                                 newobj->SetDeformer(skinDeformer);
1193                         }
1194                         else if (bHasDvert)
1195                         {
1196                                 BL_MeshDeformer* meshdeformer = new BL_MeshDeformer(
1197                                         newobj, oldblendobj, mesh
1198                                 );
1199                                 newobj->SetDeformer(meshdeformer);
1200                         }
1201 #ifdef USE_BULLET
1202                         else if (bHasSoftBody)
1203                         {
1204                                 KX_SoftBodyDeformer *softdeformer = new KX_SoftBodyDeformer(mesh, newobj);
1205                                 newobj->SetDeformer(softdeformer);
1206                         }
1207 #endif
1208
1209                         // release parent reference if its not being used 
1210                         if( releaseParent && parentobj)
1211                                 parentobj->Release();
1212                 }
1213         }
1214
1215         gameobj->AddMeshUser();
1216         }
1217
1218 #ifdef USE_BULLET
1219         if(use_phys) { /* update the new assigned mesh with the physics mesh */
1220                 KX_ReInstanceBulletShapeFromMesh(gameobj, NULL, use_gfx?NULL:mesh);
1221         }
1222 #endif
1223 }
1224
1225 /* Font Object routines */
1226 void KX_Scene::AddFont(KX_FontObject* font)
1227 {
1228         if (!FindFont(font))
1229                 m_fonts.push_back(font);
1230 }
1231
1232 KX_FontObject* KX_Scene::FindFont(KX_FontObject* font)
1233 {
1234         list<KX_FontObject*>::iterator it = m_fonts.begin();
1235
1236         while ( (it != m_fonts.end()) 
1237                         && ((*it) != font) ) {
1238           ++it;
1239         }
1240
1241         return ((it == m_fonts.end()) ? NULL : (*it));
1242 }
1243
1244
1245 /* Camera Object routines */
1246 KX_Camera* KX_Scene::FindCamera(KX_Camera* cam)
1247 {
1248         list<KX_Camera*>::iterator it = m_cameras.begin();
1249
1250         while ( (it != m_cameras.end())
1251                 && ((*it) != cam) )
1252         {
1253                 it++;
1254         }
1255
1256         return ((it == m_cameras.end()) ? NULL : (*it));
1257 }
1258
1259
1260 KX_Camera* KX_Scene::FindCamera(STR_String& name)
1261 {
1262         list<KX_Camera*>::iterator it = m_cameras.begin();
1263
1264         while ( (it != m_cameras.end())
1265                 && ((*it)->GetName() != name) )
1266         {
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_From_STR_String(self->GetName());
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