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