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