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