Python BGE 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 "MT_assert.h"
37
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 "KX_Camera.h"
53 #include "SCA_JoystickManager.h"
54
55 #include "RAS_MeshObject.h"
56 #include "BL_SkinMeshObject.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 "KX_BlenderSceneConverter.h"
80
81 #include "BL_ShapeDeformer.h"
82 #include "BL_DeformableGameObject.h"
83
84 // to get USE_BULLET!
85 #include "KX_ConvertPhysicsObject.h"
86
87 #ifdef USE_BULLET
88 #include "CcdPhysicsEnvironment.h"
89 #include "CcdPhysicsController.h"
90 #endif
91
92 void* KX_SceneReplicationFunc(SG_IObject* node,void* gameobj,void* scene)
93 {
94         KX_GameObject* replica = ((KX_Scene*)scene)->AddNodeReplicaObject(node,(KX_GameObject*)gameobj);
95
96         if(replica)
97                 replica->Release();
98
99         return (void*)replica;
100 }
101
102 void* KX_SceneDestructionFunc(SG_IObject* node,void* gameobj,void* scene)
103 {
104         ((KX_Scene*)scene)->RemoveNodeDestructObject(node,(KX_GameObject*)gameobj);
105
106         return NULL;
107 };
108
109 SG_Callbacks KX_Scene::m_callbacks = SG_Callbacks(KX_SceneReplicationFunc,KX_SceneDestructionFunc,KX_GameObject::UpdateTransformFunc);
110
111 // temporarily var until there is a button in the userinterface
112 // (defined in KX_PythonInit.cpp)
113 extern bool gUseVisibilityTemp;
114
115 KX_Scene::KX_Scene(class SCA_IInputDevice* keyboarddevice,
116                                    class SCA_IInputDevice* mousedevice,
117                                    class NG_NetworkDeviceInterface *ndi,
118                                    class SND_IAudioDevice* adi,
119                                    const STR_String& sceneName,
120                                    Scene *scene): 
121         PyObjectPlus(&KX_Scene::Type),
122         m_keyboardmgr(NULL),
123         m_mousemgr(NULL),
124         m_sceneConverter(NULL),
125         m_physicsEnvironment(0),
126         m_sceneName(sceneName),
127         m_adi(adi),
128         m_networkDeviceInterface(ndi),
129         m_active_camera(NULL),
130         m_ueberExecutionPriority(0),
131         m_blenderScene(scene)
132 {
133         m_suspendedtime = 0.0;
134         m_suspendeddelta = 0.0;
135
136         m_activity_culling = false;
137         m_suspend = false;
138         m_isclearingZbuffer = true;
139         m_tempObjectList = new CListValue();
140         m_objectlist = new CListValue();
141         m_parentlist = new CListValue();
142         m_lightlist= new CListValue();
143         m_inactivelist = new CListValue();
144         m_euthanasyobjects = new CListValue();
145         m_delayReleaseObjects = new CListValue();
146
147         m_logicmgr = new SCA_LogicManager();
148         
149         m_timemgr = new SCA_TimeEventManager(m_logicmgr);
150         m_keyboardmgr = new SCA_KeyboardManager(m_logicmgr,keyboarddevice);
151         m_mousemgr = new SCA_MouseManager(m_logicmgr,mousedevice);
152         
153         SCA_AlwaysEventManager* alwaysmgr = new SCA_AlwaysEventManager(m_logicmgr);
154         SCA_PropertyEventManager* propmgr = new SCA_PropertyEventManager(m_logicmgr);
155         SCA_ActuatorEventManager* actmgr = new SCA_ActuatorEventManager(m_logicmgr);
156         SCA_RandomEventManager* rndmgr = new SCA_RandomEventManager(m_logicmgr);
157         KX_RayEventManager* raymgr = new KX_RayEventManager(m_logicmgr);
158
159         KX_NetworkEventManager* netmgr = new KX_NetworkEventManager(m_logicmgr, ndi);
160         
161         
162
163         m_logicmgr->RegisterEventManager(alwaysmgr);
164         m_logicmgr->RegisterEventManager(propmgr);
165         m_logicmgr->RegisterEventManager(actmgr);
166         m_logicmgr->RegisterEventManager(m_keyboardmgr);
167         m_logicmgr->RegisterEventManager(m_mousemgr);
168         m_logicmgr->RegisterEventManager(m_timemgr);
169         m_logicmgr->RegisterEventManager(rndmgr);
170         m_logicmgr->RegisterEventManager(raymgr);
171         m_logicmgr->RegisterEventManager(netmgr);
172
173
174         SYS_SystemHandle hSystem = SYS_GetSystem();
175         bool nojoystick= SYS_GetCommandLineInt(hSystem,"nojoystick",0);
176         if (!nojoystick)
177         {
178                 SCA_JoystickManager *joymgr     = new SCA_JoystickManager(m_logicmgr);
179                 m_logicmgr->RegisterEventManager(joymgr);
180         }
181
182         m_soundScene = new SND_Scene(adi);
183         MT_assert (m_networkDeviceInterface != NULL);
184         m_networkScene = new NG_NetworkScene(m_networkDeviceInterface);
185         
186         m_rootnode = NULL;
187
188         m_bucketmanager=new RAS_BucketManager();
189
190         m_canvasDesignWidth = 0;
191         m_canvasDesignHeight = 0;
192         
193         m_attrlist = PyDict_New(); /* new ref */
194 }
195
196
197
198 KX_Scene::~KX_Scene()
199 {
200         // The release of debug properties used to be in SCA_IScene::~SCA_IScene
201         // It's still there but we remove all properties here otherwise some
202         // reference might be hanging and causing late release of objects
203         RemoveAllDebugProperties();
204
205         while (GetRootParentList()->GetCount() > 0) 
206         {
207                 KX_GameObject* parentobj = (KX_GameObject*) GetRootParentList()->GetValue(0);
208                 this->RemoveObject(parentobj);
209         }
210
211         if(m_objectlist)
212                 m_objectlist->Release();
213
214         if (m_parentlist)
215                 m_parentlist->Release();
216         
217         if (m_inactivelist)
218                 m_inactivelist->Release();
219
220         if (m_lightlist)
221                 m_lightlist->Release();
222         
223         if (m_tempObjectList)
224                 m_tempObjectList->Release();
225
226         if (m_euthanasyobjects)
227                 m_euthanasyobjects->Release();
228         if (m_delayReleaseObjects)
229                 m_delayReleaseObjects->Release();
230
231         if (m_logicmgr)
232                 delete m_logicmgr;
233
234         if (m_physicsEnvironment)
235                 delete m_physicsEnvironment;
236
237         if (m_soundScene)
238                 delete m_soundScene;
239
240         if (m_networkScene)
241                 delete m_networkScene;
242         
243         if (m_bucketmanager)
244         {
245                 delete m_bucketmanager;
246         }
247         //Py_DECREF(m_attrlist);
248 }
249
250 void KX_Scene::SetProjectionMatrix(MT_CmMatrix4x4& pmat)
251 {
252         m_projectionmat = pmat;
253 }
254
255
256
257 RAS_BucketManager* KX_Scene::GetBucketManager()
258 {
259         return m_bucketmanager;
260 }
261
262
263
264 CListValue* KX_Scene::GetObjectList()
265 {
266         return m_objectlist;
267 }
268
269
270
271 CListValue* KX_Scene::GetRootParentList()
272 {
273         return m_parentlist;
274 }
275
276 CListValue* KX_Scene::GetInactiveList()
277 {
278         return m_inactivelist;
279 }
280
281
282
283 CListValue* KX_Scene::GetLightList()
284 {
285         return m_lightlist;
286 }
287
288 SCA_LogicManager* KX_Scene::GetLogicManager()
289 {
290         return m_logicmgr;
291 }
292
293 SCA_TimeEventManager* KX_Scene::GetTimeEventManager()
294 {
295         return m_timemgr;
296 }
297
298
299
300  
301 list<class KX_Camera*>* KX_Scene::GetCameras()
302 {
303         return &m_cameras;
304 }
305
306
307
308 void KX_Scene::SetFramingType(RAS_FrameSettings & frame_settings)
309 {
310         m_frame_settings = frame_settings;
311 };
312
313 /**
314  * Return a const reference to the framing 
315  * type set by the above call.
316  * The contents are not guarenteed to be sensible
317  * if you don't call the above function.
318  */
319 const RAS_FrameSettings& KX_Scene::GetFramingType() const 
320 {
321         return m_frame_settings;
322 };      
323
324
325
326 /**
327  * Store the current scene's viewport on the 
328  * game engine canvas.
329  */
330 void KX_Scene::SetSceneViewport(const RAS_Rect &viewport)
331 {
332         m_viewport = viewport;
333 }
334
335
336
337 const RAS_Rect& KX_Scene::GetSceneViewport() const 
338 {
339         return m_viewport;
340 }
341
342
343
344 void KX_Scene::SetWorldInfo(class KX_WorldInfo* worldinfo)
345 {
346         m_worldinfo = worldinfo;
347 }
348
349
350
351 class KX_WorldInfo* KX_Scene::GetWorldInfo()
352 {
353         return m_worldinfo;
354 }
355
356
357
358 SND_Scene* KX_Scene::GetSoundScene()
359 {
360         return m_soundScene;
361 }
362
363 const STR_String& KX_Scene::GetName()
364 {
365         return m_sceneName;
366 }
367
368
369 void KX_Scene::Suspend()
370 {
371         m_suspend = true;
372 }
373
374 void KX_Scene::Resume()
375 {
376         m_suspend = false;
377 }
378
379 void KX_Scene::SetActivityCulling(bool b)
380 {
381         m_activity_culling = b;
382 }
383
384 bool KX_Scene::IsSuspended()
385 {
386         return m_suspend;
387 }
388
389 bool KX_Scene::IsClearingZBuffer()
390 {
391         return m_isclearingZbuffer;
392 }
393
394 void KX_Scene::EnableZBufferClearing(bool isclearingZbuffer)
395 {
396         m_isclearingZbuffer = isclearingZbuffer;
397 }
398
399 void KX_Scene::RemoveNodeDestructObject(class SG_IObject* node,class CValue* gameobj)
400 {
401         KX_GameObject* orgobj = (KX_GameObject*)gameobj;        
402         if (NewRemoveObject(orgobj) != 0)
403         {
404                 // object is not yet deleted (this can happen when it hangs in an add object actuator
405                 // last object created reference. It's a bad situation, don't know how to fix it exactly
406                 // The least I can do, is remove the reference to the node in the object as the node
407                 // will in any case be deleted. This ensures that the object will not try to use the node
408                 // when it is finally deleted (see KX_GameObject destructor)
409                 orgobj->SetSGNode(NULL);
410         }
411         if (node)
412                 delete node;
413 }
414
415 KX_GameObject* KX_Scene::AddNodeReplicaObject(class SG_IObject* node, class CValue* gameobj)
416 {
417         // for group duplication, limit the duplication of the hierarchy to the
418         // objects that are part of the group. 
419         if (!IsObjectInGroup(gameobj))
420                 return NULL;
421         
422         KX_GameObject* orgobj = (KX_GameObject*)gameobj;
423         KX_GameObject* newobj = (KX_GameObject*)orgobj->GetReplica();
424         m_map_gameobject_to_replica.insert(orgobj, newobj);
425
426         // also register 'timers' (time properties) of the replica
427         int numprops = newobj->GetPropertyCount();
428
429         for (int i = 0; i < numprops; i++)
430         {
431                 CValue* prop = newobj->GetProperty(i);
432
433                 if (prop->GetProperty("timer"))
434                         this->m_timemgr->AddTimeProperty(prop);
435         }
436
437         if (node)
438         {
439                 newobj->SetSGNode((SG_Node*)node);
440         }
441         else
442         {
443                 m_rootnode = new SG_Node(newobj,this,KX_Scene::m_callbacks);
444         
445                 // this fixes part of the scaling-added object bug
446                 SG_Node* orgnode = orgobj->GetSGNode();
447                 m_rootnode->SetLocalScale(orgnode->GetLocalScale());
448                 m_rootnode->SetLocalPosition(orgnode->GetLocalPosition());
449                 m_rootnode->SetLocalOrientation(orgnode->GetLocalOrientation());
450
451                 // define the relationship between this node and it's parent.
452                 KX_NormalParentRelation * parent_relation = 
453                         KX_NormalParentRelation::New();
454                 m_rootnode->SetParentRelation(parent_relation);
455
456                 newobj->SetSGNode(m_rootnode);
457         }
458         
459         SG_IObject* replicanode = newobj->GetSGNode();
460 //      SG_Node* rootnode = (replicanode == m_rootnode ? NULL : m_rootnode);
461
462         replicanode->SetSGClientObject(newobj);
463
464         // this is the list of object that are send to the graphics pipeline
465         m_objectlist->Add(newobj->AddRef());
466         newobj->AddMeshUser();
467
468         // logic cannot be replicated, until the whole hierarchy is replicated.
469         m_logicHierarchicalGameObjects.push_back(newobj);
470         //replicate controllers of this node
471         SGControllerList        scenegraphcontrollers = orgobj->GetSGNode()->GetSGControllerList();
472         replicanode->RemoveAllControllers();
473         SGControllerList::iterator cit;
474         //int numcont = scenegraphcontrollers.size();
475         
476         for (cit = scenegraphcontrollers.begin();!(cit==scenegraphcontrollers.end());++cit)
477         {
478                 // controller replication is quite complicated
479                 // only replicate ipo and physics controller for now
480
481                 SG_Controller* replicacontroller = (*cit)->GetReplica((SG_Node*) replicanode);
482                 if (replicacontroller)
483                 {
484                         replicacontroller->SetObject(replicanode);
485                         replicanode->AddSGController(replicacontroller);
486                 }
487         }
488         
489         return newobj;
490 }
491
492
493
494 // before calling this method KX_Scene::ReplicateLogic(), make sure to
495 // have called 'GameObject::ReParentLogic' for each object this
496 // hierarchy that's because first ALL bricks must exist in the new
497 // replica of the hierarchy in order to make cross-links work properly
498 // !
499 // It is VERY important that the order of sensors and actuators in
500 // the replicated object is preserved: it is is used to reconnect the logic.
501 // This method is more robust then using the bricks name in case of complex 
502 // group replication. The replication of logic bricks is done in 
503 // SCA_IObject::ReParentLogic(), make sure it preserves the order of the bricks.
504 void KX_Scene::ReplicateLogic(KX_GameObject* newobj)
505 {
506         // also relink the controller to sensors/actuators
507         SCA_ControllerList& controllers = newobj->GetControllers();
508         //SCA_SensorList&     sensors     = newobj->GetSensors();
509         //SCA_ActuatorList&   actuators   = newobj->GetActuators();
510
511         for (SCA_ControllerList::iterator itc = controllers.begin(); !(itc==controllers.end());itc++)
512         {
513                 SCA_IController* cont = (*itc);
514                 cont->SetUeberExecutePriority(m_ueberExecutionPriority);
515                 vector<SCA_ISensor*> linkedsensors = cont->GetLinkedSensors();
516                 vector<SCA_IActuator*> linkedactuators = cont->GetLinkedActuators();
517
518                 // disconnect the sensors and actuators
519                 cont->UnlinkAllSensors();
520                 cont->UnlinkAllActuators();
521                 
522                 // now relink each sensor
523                 for (vector<SCA_ISensor*>::iterator its = linkedsensors.begin();!(its==linkedsensors.end());its++)
524                 {
525                         SCA_ISensor* oldsensor = (*its);
526                         SCA_IObject* oldsensorobj = oldsensor->GetParent();
527                         SCA_IObject* newsensorobj = NULL;
528                 
529                         // the original owner of the sensor has been replicated?
530                         void **h_obj = m_map_gameobject_to_replica[oldsensorobj];
531                         if (h_obj)
532                                 newsensorobj = (SCA_IObject*)(*h_obj);
533                         if (!newsensorobj)
534                         {
535                                 // no, then the sensor points outside the hierachy, keep it the same
536                                 if (m_objectlist->SearchValue(oldsensorobj))
537                                         // only replicate links that points to active objects
538                                         m_logicmgr->RegisterToSensor(cont,oldsensor);
539                         }
540                         else
541                         {
542                                 // yes, then the new sensor has the same position
543                                 SCA_SensorList& sensorlist = oldsensorobj->GetSensors();
544                                 SCA_SensorList::iterator sit;
545                                 SCA_ISensor* newsensor = NULL;
546                                 int sensorpos;
547
548                                 for (sensorpos=0, sit=sensorlist.begin(); sit!=sensorlist.end(); sit++, sensorpos++)
549                                 {
550                                         if ((*sit) == oldsensor) 
551                                         {
552                                                 newsensor = newsensorobj->GetSensors().at(sensorpos);
553                                                 break;
554                                         }
555                                 }
556                                 assert(newsensor != NULL);
557                                 m_logicmgr->RegisterToSensor(cont,newsensor);
558                         }
559                 }
560                 
561                 // now relink each actuator
562                 for (vector<SCA_IActuator*>::iterator ita = linkedactuators.begin();!(ita==linkedactuators.end());ita++)
563                 {
564                         SCA_IActuator* oldactuator = (*ita);
565                         SCA_IObject* oldactuatorobj = oldactuator->GetParent();
566                         SCA_IObject* newactuatorobj = NULL;
567
568                         // the original owner of the sensor has been replicated?
569                         void **h_obj = m_map_gameobject_to_replica[oldactuatorobj];
570                         if (h_obj)
571                                 newactuatorobj = (SCA_IObject*)(*h_obj);
572
573                         if (!newactuatorobj)
574                         {
575                                 // no, then the sensor points outside the hierachy, keep it the same
576                                 if (m_objectlist->SearchValue(oldactuatorobj))
577                                         // only replicate links that points to active objects
578                                         m_logicmgr->RegisterToActuator(cont,oldactuator);
579                         }
580                         else
581                         {
582                                 // yes, then the new sensor has the same position
583                                 SCA_ActuatorList& actuatorlist = oldactuatorobj->GetActuators();
584                                 SCA_ActuatorList::iterator ait;
585                                 SCA_IActuator* newactuator = NULL;
586                                 int actuatorpos;
587
588                                 for (actuatorpos=0, ait=actuatorlist.begin(); ait!=actuatorlist.end(); ait++, actuatorpos++)
589                                 {
590                                         if ((*ait) == oldactuator) 
591                                         {
592                                                 newactuator = newactuatorobj->GetActuators().at(actuatorpos);
593                                                 break;
594                                         }
595                                 }
596                                 assert(newactuator != NULL);
597                                 m_logicmgr->RegisterToActuator(cont,newactuator);
598                                 newactuator->SetUeberExecutePriority(m_ueberExecutionPriority);
599                         }
600                 }
601         }
602         // ready to set initial state
603         newobj->ResetState();
604 }
605
606 void KX_Scene::DupliGroupRecurse(CValue* obj, int level)
607 {
608         KX_GameObject* groupobj = (KX_GameObject*) obj;
609         KX_GameObject* replica;
610         KX_GameObject* gameobj;
611         Object* blgroupobj = groupobj->GetBlenderObject();
612         Group* group;
613         GroupObject *go;
614         vector<KX_GameObject*> duplilist;
615
616         if (!groupobj->GetSGNode() ||
617                 !groupobj->IsDupliGroup() ||
618                 level>MAX_DUPLI_RECUR)
619                 return;
620
621         // we will add one group at a time
622         m_logicHierarchicalGameObjects.clear();
623         m_map_gameobject_to_replica.clear();
624         m_ueberExecutionPriority++;
625         // for groups will do something special: 
626         // we will force the creation of objects to those in the group only
627         // Again, this is match what Blender is doing (it doesn't care of parent relationship)
628         m_groupGameObjects.clear();
629
630         group = blgroupobj->dup_group;
631         for(go=(GroupObject*)group->gobject.first; go; go=(GroupObject*)go->next) 
632         {
633                 Object* blenderobj = go->ob;
634                 if (blgroupobj == blenderobj)
635                         // this check is also in group_duplilist()
636                         continue;
637
638                 gameobj = (KX_GameObject*)m_logicmgr->FindGameObjByBlendObj(blenderobj);
639                 if (gameobj == NULL) 
640                 {
641                         // this object has not been converted!!!
642                         // Should not happen as dupli group are created automatically 
643                         continue;
644                 }
645
646                 gameobj->SetBlenderGroupObject(blgroupobj);
647
648                 if ((blenderobj->lay & group->layer)==0)
649                 {
650                         // object is not visible in the 3D view, will not be instantiated
651                         continue;
652                 }
653                 m_groupGameObjects.insert(gameobj);
654         }
655
656         set<CValue*>::iterator oit;
657         for (oit=m_groupGameObjects.begin(); oit != m_groupGameObjects.end(); oit++)
658         {
659                 gameobj = (KX_GameObject*)(*oit);
660
661                 KX_GameObject *parent = gameobj->GetParent();
662                 if (parent != NULL)
663                 {
664                         parent->Release(); // GetParent() increased the refcount
665
666                         // this object is not a top parent. Either it is the child of another
667                         // object in the group and it will be added automatically when the parent
668                         // is added. Or it is the child of an object outside the group and the group
669                         // is inconsistent, skip it anyway
670                         continue;
671                 }
672                 replica = (KX_GameObject*) AddNodeReplicaObject(NULL,gameobj);
673                 // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame)
674                 m_parentlist->Add(replica->AddRef());
675
676                 // recurse replication into children nodes
677                 NodeList& children = gameobj->GetSGNode()->GetSGChildren();
678
679                 replica->GetSGNode()->ClearSGChildren();
680                 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
681                 {
682                         SG_Node* orgnode = (*childit);
683                         SG_Node* childreplicanode = orgnode->GetSGReplica();
684                         if (childreplicanode)
685                                 replica->GetSGNode()->AddChild(childreplicanode);
686                 }
687                 // don't replicate logic now: we assume that the objects in the group can have
688                 // logic relationship, even outside parent relationship
689                 // In order to match 3D view, the position of groupobj is used as a 
690                 // transformation matrix instead of the new position. This means that 
691                 // the group reference point is 0,0,0
692
693                 // get the rootnode's scale
694                 MT_Vector3 newscale = groupobj->NodeGetWorldScaling();
695                 // set the replica's relative scale with the rootnode's scale
696                 replica->NodeSetRelativeScale(newscale);
697
698                 MT_Matrix3x3 newori = groupobj->NodeGetWorldOrientation() * gameobj->NodeGetWorldOrientation();
699                 replica->NodeSetLocalOrientation(newori);
700
701                 MT_Point3 newpos = groupobj->NodeGetWorldPosition() + 
702                         newscale*(groupobj->NodeGetWorldOrientation() * gameobj->NodeGetWorldPosition());
703                 replica->NodeSetLocalPosition(newpos);
704
705                 replica->GetSGNode()->UpdateWorldData(0);
706                 replica->GetSGNode()->SetBBox(gameobj->GetSGNode()->BBox());
707                 replica->GetSGNode()->SetRadius(gameobj->GetSGNode()->Radius());
708                 // done with replica
709                 replica->Release();
710         }
711
712         // the logic must be replicated first because we need
713         // the new logic bricks before relinking
714         vector<KX_GameObject*>::iterator git;
715         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
716         {
717                 (*git)->ReParentLogic();
718         }
719         
720         //      relink any pointers as necessary, sort of a temporary solution
721         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
722         {
723                 // this will also relink the actuator to objects within the hierarchy
724                 (*git)->Relink(&m_map_gameobject_to_replica);
725                 // add the object in the layer of the parent
726                 (*git)->SetLayer(groupobj->GetLayer());
727         }
728
729         // replicate crosslinks etc. between logic bricks
730         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
731         {
732                 ReplicateLogic((*git));
733         }
734         
735         // now look if object in the hierarchy have dupli group and recurse
736         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
737         {
738                 if ((*git) != groupobj && (*git)->IsDupliGroup())
739                         // can't instantiate group immediately as it destroys m_logicHierarchicalGameObjects
740                         duplilist.push_back((*git));
741         }
742
743         for (git = duplilist.begin(); !(git == duplilist.end()); ++git)
744         {
745                 DupliGroupRecurse((*git), level+1);
746         }
747 }
748
749
750 SCA_IObject* KX_Scene::AddReplicaObject(class CValue* originalobject,
751                                                                                 class CValue* parentobject,
752                                                                                 int lifespan)
753 {
754
755         m_logicHierarchicalGameObjects.clear();
756         m_map_gameobject_to_replica.clear();
757         m_groupGameObjects.clear();
758
759         // todo: place a timebomb in the object, for temporarily objects :)
760         // lifespan of zero means 'this object lives forever'
761         KX_GameObject* originalobj = (KX_GameObject*) originalobject;
762         KX_GameObject* parentobj = (KX_GameObject*) parentobject;
763
764         m_ueberExecutionPriority++;
765
766         // lets create a replica
767         KX_GameObject* replica = (KX_GameObject*) AddNodeReplicaObject(NULL,originalobj);
768
769         if (lifespan > 0)
770         {
771                 // add a timebomb to this object
772                 // for now, convert between so called frames and realtime
773                 m_tempObjectList->Add(replica->AddRef());
774                 CValue *fval = new CFloatValue(lifespan*0.02);
775                 replica->SetProperty("::timebomb",fval);
776                 fval->Release();
777         }
778
779         // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame)
780         m_parentlist->Add(replica->AddRef());
781
782         // recurse replication into children nodes
783
784         NodeList& children = originalobj->GetSGNode()->GetSGChildren();
785
786         replica->GetSGNode()->ClearSGChildren();
787         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
788         {
789                 SG_Node* orgnode = (*childit);
790                 SG_Node* childreplicanode = orgnode->GetSGReplica();
791                 if (childreplicanode)
792                         replica->GetSGNode()->AddChild(childreplicanode);
793         }
794
795         // now replicate logic
796         vector<KX_GameObject*>::iterator git;
797         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
798         {
799                 (*git)->ReParentLogic();
800         }
801         
802         //      relink any pointers as necessary, sort of a temporary solution
803         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
804         {
805                 // this will also relink the actuators in the hierarchy
806                 (*git)->Relink(&m_map_gameobject_to_replica);
807                 // add the object in the layer of the parent
808                 (*git)->SetLayer(parentobj->GetLayer());
809         }
810
811         // replicate crosslinks etc. between logic bricks
812         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
813         {
814                 ReplicateLogic((*git));
815         }
816         
817         MT_Point3 newpos = ((KX_GameObject*) parentobject)->NodeGetWorldPosition();
818         replica->NodeSetLocalPosition(newpos);
819
820         MT_Matrix3x3 newori = ((KX_GameObject*) parentobject)->NodeGetWorldOrientation();
821         replica->NodeSetLocalOrientation(newori);
822         
823         // get the rootnode's scale
824         MT_Vector3 newscale = parentobj->GetSGNode()->GetRootSGParent()->GetLocalScale();
825
826         // set the replica's relative scale with the rootnode's scale
827         replica->NodeSetRelativeScale(newscale);
828
829         replica->GetSGNode()->UpdateWorldData(0);
830         replica->GetSGNode()->SetBBox(originalobj->GetSGNode()->BBox());
831         replica->GetSGNode()->SetRadius(originalobj->GetSGNode()->Radius());
832         // check if there are objects with dupligroup in the hierarchy
833         vector<KX_GameObject*> duplilist;
834         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
835         {
836                 if ((*git)->IsDupliGroup())
837                 {
838                         // separate list as m_logicHierarchicalGameObjects is also used by DupliGroupRecurse()
839                         duplilist.push_back(*git);
840                 }
841         }
842         for (git = duplilist.begin();!(git==duplilist.end());++git)
843         {
844                 DupliGroupRecurse(*git, 0);
845         }
846         //      don't release replica here because we are returning it, not done with it...
847         return replica;
848 }
849
850
851
852 void KX_Scene::RemoveObject(class CValue* gameobj)
853 {
854         KX_GameObject* newobj = (KX_GameObject*) gameobj;
855
856         // first disconnect child from parent
857         SG_Node* node = newobj->GetSGNode();
858
859         if (node)
860         {
861                 node->DisconnectFromParent();
862
863                 // recursively destruct
864                 node->Destruct();
865         }
866         //no need to do that: the object is destroyed and memory released 
867         //newobj->SetSGNode(0);
868 }
869
870 void KX_Scene::DelayedReleaseObject(CValue* gameobj)
871 {
872         m_delayReleaseObjects->Add(gameobj->AddRef());
873 }
874
875
876 void KX_Scene::DelayedRemoveObject(class CValue* gameobj)
877 {
878         //KX_GameObject* newobj = (KX_GameObject*) gameobj;
879         if (!m_euthanasyobjects->SearchValue(gameobj))
880         {
881                 m_euthanasyobjects->Add(gameobj->AddRef());
882         } 
883 }
884
885
886
887 int KX_Scene::NewRemoveObject(class CValue* gameobj)
888 {
889         int ret;
890         KX_GameObject* newobj = (KX_GameObject*) gameobj;
891
892         // keep the blender->game object association up to date
893         // note that all the replicas of an object will have the same
894         // blender object, that's why we need to check the game object
895         // as only the deletion of the original object must be recorded
896         m_logicmgr->UnregisterGameObj(newobj->GetBlenderObject(), gameobj);
897
898         //todo: look at this
899         //GetPhysicsEnvironment()->RemovePhysicsController(gameobj->getPhysicsController());
900
901         // remove all sensors/controllers/actuators from logicsystem...
902         
903         SCA_SensorList& sensors = newobj->GetSensors();
904         for (SCA_SensorList::iterator its = sensors.begin();
905                  !(its==sensors.end());its++)
906         {
907                 m_logicmgr->RemoveSensor(*its);
908         }
909         
910     SCA_ControllerList& controllers = newobj->GetControllers();
911         for (SCA_ControllerList::iterator itc = controllers.begin();
912                  !(itc==controllers.end());itc++)
913         {
914                 m_logicmgr->RemoveController(*itc);
915         }
916
917         SCA_ActuatorList& actuators = newobj->GetActuators();
918         for (SCA_ActuatorList::iterator ita = actuators.begin();
919                  !(ita==actuators.end());ita++)
920         {
921                 m_logicmgr->RemoveDestroyedActuator(*ita);
922         }
923         // the sensors/controllers/actuators must also be released, this is done in ~SCA_IObject
924
925         // now remove the timer properties from the time manager
926         int numprops = newobj->GetPropertyCount();
927
928         for (int i = 0; i < numprops; i++)
929         {
930                 CValue* propval = newobj->GetProperty(i);
931                 if (propval->GetProperty("timer"))
932                 {
933                         m_timemgr->RemoveTimeProperty(propval);
934                 }
935         }
936         
937         newobj->RemoveMeshes();
938         ret = 1;
939         if (m_lightlist->RemoveValue(newobj)) // TODO - use newobj->IsLight() test when its merged in from apricot. - Campbell
940                 ret = newobj->Release();
941         if (m_objectlist->RemoveValue(newobj))
942                 ret = newobj->Release();
943         if (m_tempObjectList->RemoveValue(newobj))
944                 ret = newobj->Release();
945         if (m_parentlist->RemoveValue(newobj))
946                 ret = newobj->Release();
947         if (m_inactivelist->RemoveValue(newobj))
948                 ret = newobj->Release();
949         if (m_euthanasyobjects->RemoveValue(newobj))
950                 ret = newobj->Release();
951                 
952         if (newobj == m_active_camera)
953         {
954                 //no AddRef done on m_active_camera so no Release
955                 //m_active_camera->Release();
956                 m_active_camera = NULL;
957         }
958
959         // in case this is a camera
960         m_cameras.remove((KX_Camera*)newobj);
961
962         if (m_sceneConverter)
963                 m_sceneConverter->UnregisterGameObject(newobj);
964         // return value will be 0 if the object is actually deleted (all reference gone)
965         return ret;
966 }
967
968
969
970 void KX_Scene::ReplaceMesh(class CValue* obj,void* meshobj)
971 {
972         KX_GameObject* gameobj = static_cast<KX_GameObject*>(obj);
973         RAS_MeshObject* mesh = static_cast<RAS_MeshObject*>(meshobj);
974
975         if(!gameobj || !mesh)
976         {
977                 std::cout << "warning: invalid object, mesh will not be replaced" << std::endl;
978                 return;
979         }
980
981         gameobj->RemoveMeshes();
982         gameobj->AddMesh(mesh);
983         
984         if (gameobj->m_isDeformable)
985         {
986                 BL_DeformableGameObject* newobj = static_cast<BL_DeformableGameObject*>( gameobj );
987                 
988                 if (newobj->GetDeformer())
989                 {
990                         delete newobj->GetDeformer();
991                         newobj->SetDeformer(NULL);
992                 }
993
994                 if (mesh->IsDeformed())
995                 {
996                         // we must create a new deformer but which one?
997                         KX_GameObject* parentobj = newobj->GetParent();
998                         // this always return the original game object (also for replicate)
999                         Object* blendobj = newobj->GetBlenderObject();
1000                         // object that owns the new mesh
1001                         Object* oldblendobj = static_cast<struct Object*>(m_logicmgr->FindBlendObjByGameMeshName(mesh->GetName()));
1002                         Mesh* blendmesh = mesh->GetMesh();
1003
1004                         bool bHasShapeKey = blendmesh->key != NULL && blendmesh->key->type==KEY_RELATIVE;
1005                         bool bHasDvert = blendmesh->dvert != NULL;
1006                         bool bHasArmature = 
1007                                 parentobj &&                                                            // current parent is armature
1008                                 parentobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE &&
1009                                 oldblendobj &&                                                          // needed for mesh deform
1010                                 blendobj->parent &&                                                     // original object had armature (not sure this test is needed)
1011                                 blendobj->parent->type == OB_ARMATURE && 
1012                                 blendobj->partype==PARSKEL && 
1013                                 blendmesh->dvert!=NULL;                                         // mesh has vertex group
1014                         bool releaseParent = true;
1015
1016                         
1017                         if (oldblendobj==NULL) {
1018                                 std::cout << "warning: ReplaceMesh() new mesh is not used in an object from the current scene, you will get incorrect behavior" << std::endl;
1019                                 bHasShapeKey= bHasDvert= bHasArmature= false;
1020                         }
1021                         
1022                         if (bHasShapeKey)
1023                         {
1024                                 BL_ShapeDeformer* shapeDeformer;
1025                                 if (bHasArmature) 
1026                                 {
1027                                         shapeDeformer = new BL_ShapeDeformer(
1028                                                 newobj,
1029                                                 oldblendobj, blendobj,
1030                                                 static_cast<BL_SkinMeshObject*>(mesh),
1031                                                 true,
1032                                                 static_cast<BL_ArmatureObject*>( parentobj )
1033                                         );
1034                                         releaseParent= false;
1035                                         shapeDeformer->LoadShapeDrivers(blendobj->parent);
1036                                 }
1037                                 else
1038                                 {
1039                                         shapeDeformer = new BL_ShapeDeformer(
1040                                                 newobj,
1041                                                 oldblendobj, blendobj,
1042                                                 static_cast<BL_SkinMeshObject*>(mesh),
1043                                                 false,
1044                                                 NULL
1045                                         );
1046                                 }
1047                                 newobj->SetDeformer( shapeDeformer);
1048                         }
1049                         else if (bHasArmature) 
1050                         {
1051                                 BL_SkinDeformer* skinDeformer = new BL_SkinDeformer(
1052                                         newobj,
1053                                         oldblendobj, blendobj,
1054                                         static_cast<BL_SkinMeshObject*>(mesh),
1055                                         true,
1056                                         static_cast<BL_ArmatureObject*>( parentobj )
1057                                 );
1058                                 releaseParent= false;
1059                                 newobj->SetDeformer(skinDeformer);
1060                         }
1061                         else if (bHasDvert)
1062                         {
1063                                 BL_MeshDeformer* meshdeformer = new BL_MeshDeformer(
1064                                         newobj, oldblendobj, static_cast<BL_SkinMeshObject*>(mesh)
1065                                 );
1066                                 newobj->SetDeformer(meshdeformer);
1067                         }
1068
1069                         // release parent reference if its not being used 
1070                         if( releaseParent && parentobj)
1071                                 parentobj->Release();
1072                 }
1073         }
1074
1075         gameobj->AddMeshUser();
1076 }
1077
1078
1079
1080 MT_CmMatrix4x4& KX_Scene::GetViewMatrix()
1081 {
1082         MT_Scalar cammat[16];
1083         m_active_camera->GetWorldToCamera().getValue(cammat);
1084         m_viewmat = cammat;
1085         return m_viewmat;
1086 }
1087
1088
1089
1090 MT_CmMatrix4x4& KX_Scene::GetProjectionMatrix()
1091 {
1092         return m_projectionmat;
1093 }
1094
1095
1096 KX_Camera* KX_Scene::FindCamera(KX_Camera* cam)
1097 {
1098         list<KX_Camera*>::iterator it = m_cameras.begin();
1099
1100         while ( (it != m_cameras.end()) 
1101                         && ((*it) != cam) ) {
1102           it++;
1103         }
1104
1105         return ((it == m_cameras.end()) ? NULL : (*it));
1106 }
1107
1108
1109 KX_Camera* KX_Scene::FindCamera(STR_String& name)
1110 {
1111         list<KX_Camera*>::iterator it = m_cameras.begin();
1112
1113         while ( (it != m_cameras.end()) 
1114                         && ((*it)->GetName() != name) ) {
1115           it++;
1116         }
1117
1118         return ((it == m_cameras.end()) ? NULL : (*it));
1119 }
1120
1121 void KX_Scene::AddCamera(KX_Camera* cam)
1122 {
1123         if (!FindCamera(cam))
1124                 m_cameras.push_back(cam);
1125 }
1126
1127
1128 KX_Camera* KX_Scene::GetActiveCamera()
1129 {       
1130         // NULL if not defined
1131         return m_active_camera;
1132 }
1133
1134
1135 void KX_Scene::SetActiveCamera(KX_Camera* cam)
1136 {
1137         // only set if the cam is in the active list? Or add it otherwise?
1138         if (!FindCamera(cam)){
1139                 AddCamera(cam);
1140                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
1141         } 
1142
1143         m_active_camera = cam;
1144 }
1145
1146 void KX_Scene::SetCameraOnTop(KX_Camera* cam)
1147 {
1148         if (!FindCamera(cam)){
1149                 // adding is always done at the back, so that's all that needs to be done
1150                 AddCamera(cam);
1151                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
1152         } else {
1153                 m_cameras.remove(cam);
1154                 m_cameras.push_back(cam);
1155         }
1156 }
1157
1158
1159 void KX_Scene::UpdateMeshTransformations()
1160 {
1161         // do this incrementally in the future
1162         for (int i = 0; i < m_objectlist->GetCount(); i++)
1163         {
1164                 KX_GameObject* gameobj = (KX_GameObject*)m_objectlist->GetValue(i);
1165                 gameobj->GetOpenGLMatrix();
1166 //              gameobj->UpdateNonDynas();
1167         }
1168 }
1169
1170 void KX_Scene::MarkVisible(SG_Tree *node, RAS_IRasterizer* rasty, KX_Camera* cam, int layer)
1171 {
1172         int intersect = KX_Camera::INTERSECT;
1173         KX_GameObject *gameobj = node->Client()?(KX_GameObject*) node->Client()->GetSGClientObject():NULL;
1174         bool visible = (gameobj && gameobj->GetVisible() && (!layer || (gameobj->GetLayer() & layer)));
1175         bool dotest = visible || node->Left() || node->Right();
1176
1177         /* If the camera is inside the box, assume intersect. */
1178         if (dotest && !node->inside( cam->NodeGetWorldPosition()))
1179         {
1180                 MT_Scalar radius = node->Radius();
1181                 MT_Point3 center = node->Center();
1182                 
1183                 intersect =  cam->SphereInsideFrustum(center, radius); 
1184                 
1185                 if (intersect == KX_Camera::INTERSECT)
1186                 {
1187                         MT_Point3 box[8];
1188                         node->get(box);
1189                         intersect = cam->BoxInsideFrustum(box);
1190                 }
1191         }
1192
1193         switch (intersect)
1194         {
1195                 case KX_Camera::OUTSIDE:
1196                         MarkSubTreeVisible(node, rasty, false, cam);
1197                         break;
1198                 case KX_Camera::INTERSECT:
1199                         if (gameobj)
1200                                 MarkVisible(rasty, gameobj, cam, layer);
1201                         if (node->Left())
1202                                 MarkVisible(node->Left(), rasty, cam, layer);
1203                         if (node->Right())
1204                                 MarkVisible(node->Right(), rasty, cam, layer);
1205                         break;
1206                 case KX_Camera::INSIDE:
1207                         MarkSubTreeVisible(node, rasty, true, cam, layer);
1208                         break;
1209         }
1210 }
1211
1212 void KX_Scene::MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool visible, KX_Camera* cam, int layer)
1213 {
1214         if (node->Client())
1215         {
1216                 KX_GameObject *gameobj = (KX_GameObject*) node->Client()->GetSGClientObject();
1217                 if (gameobj->GetVisible())
1218                 {
1219                         if (visible)
1220                         {
1221                                 int nummeshes = gameobj->GetMeshCount();
1222                                 
1223                                 // this adds the vertices to the display list
1224                                 for (int m=0;m<nummeshes;m++)
1225                                         (gameobj->GetMesh(m))->SchedulePolygons(rasty->GetDrawingMode());
1226                         }
1227
1228                         gameobj->SetCulled(!visible);
1229                         gameobj->UpdateBuckets(false);
1230                 }
1231         }
1232         if (node->Left())
1233                 MarkSubTreeVisible(node->Left(), rasty, visible, cam, layer);
1234         if (node->Right())
1235                 MarkSubTreeVisible(node->Right(), rasty, visible, cam, layer);
1236 }
1237
1238 void KX_Scene::MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj,KX_Camera*  cam,int layer)
1239 {
1240         // User (Python/Actuator) has forced object invisible...
1241         if (!gameobj->GetSGNode() || !gameobj->GetVisible())
1242                 return;
1243         
1244         // Shadow lamp layers
1245         if(layer && !(gameobj->GetLayer() & layer)) {
1246                 gameobj->SetCulled(true);
1247                 gameobj->UpdateBuckets(false);
1248                 return;
1249         }
1250
1251         // If Frustum culling is off, the object is always visible.
1252         bool vis = !cam->GetFrustumCulling();
1253         
1254         // If the camera is inside this node, then the object is visible.
1255         if (!vis)
1256         {
1257                 vis = gameobj->GetSGNode()->inside( cam->GetCameraLocation() );
1258         }
1259                 
1260         // Test the object's bound sphere against the view frustum.
1261         if (!vis)
1262         {
1263                 MT_Vector3 scale = gameobj->GetSGNode()->GetWorldScaling();
1264                 MT_Scalar radius = fabs(scale[scale.closestAxis()] * gameobj->GetSGNode()->Radius());
1265                 switch (cam->SphereInsideFrustum(gameobj->NodeGetWorldPosition(), radius))
1266                 {
1267                         case KX_Camera::INSIDE:
1268                                 vis = true;
1269                                 break;
1270                         case KX_Camera::OUTSIDE:
1271                                 vis = false;
1272                                 break;
1273                         case KX_Camera::INTERSECT:
1274                                 // Test the object's bound box against the view frustum.
1275                                 MT_Point3 box[8];
1276                                 gameobj->GetSGNode()->getBBox(box); 
1277                                 vis = cam->BoxInsideFrustum(box) != KX_Camera::OUTSIDE;
1278                                 break;
1279                 }
1280         }
1281         
1282         if (vis)
1283         {
1284                 int nummeshes = gameobj->GetMeshCount();
1285                 
1286                 for (int m=0;m<nummeshes;m++)
1287                 {
1288                         // this adds the vertices to the display list
1289                         (gameobj->GetMesh(m))->SchedulePolygons(rasty->GetDrawingMode());
1290                 }
1291                 // Visibility/ non-visibility are marked
1292                 // elsewhere now.
1293                 gameobj->SetCulled(false);
1294                 gameobj->UpdateBuckets(false);
1295         } else {
1296                 gameobj->SetCulled(true);
1297                 gameobj->UpdateBuckets(false);
1298         }
1299 }
1300
1301 void KX_Scene::CalculateVisibleMeshes(RAS_IRasterizer* rasty,KX_Camera* cam, int layer)
1302 {
1303 // FIXME: When tree is operational
1304 #if 1
1305         // do this incrementally in the future
1306         for (int i = 0; i < m_objectlist->GetCount(); i++)
1307         {
1308                 MarkVisible(rasty, static_cast<KX_GameObject*>(m_objectlist->GetValue(i)), cam, layer);
1309         }
1310 #else
1311         if (cam->GetFrustumCulling())
1312                 MarkVisible(m_objecttree, rasty, cam, layer);
1313         else
1314                 MarkSubTreeVisible(m_objecttree, rasty, true, cam, layer);
1315 #endif
1316 }
1317
1318 // logic stuff
1319 void KX_Scene::LogicBeginFrame(double curtime)
1320 {
1321         // have a look at temp objects ...
1322         int lastobj = m_tempObjectList->GetCount() - 1;
1323         
1324         for (int i = lastobj; i >= 0; i--)
1325         {
1326                 CValue* objval = m_tempObjectList->GetValue(i);
1327                 CFloatValue* propval = (CFloatValue*) objval->GetProperty("::timebomb");
1328                 
1329                 if (propval)
1330                 {
1331                         float timeleft = propval->GetNumber() - 1.0/KX_KetsjiEngine::GetTicRate();
1332                         
1333                         if (timeleft > 0)
1334                         {
1335                                 propval->SetFloat(timeleft);
1336                         }
1337                         else
1338                         {
1339                                 DelayedRemoveObject(objval);
1340                                 // remove obj
1341                         }
1342                 }
1343                 else
1344                 {
1345                         // all object is the tempObjectList should have a clock
1346                 }
1347         }
1348         m_logicmgr->BeginFrame(curtime, 1.0/KX_KetsjiEngine::GetTicRate());
1349 }
1350
1351
1352
1353 void KX_Scene::LogicUpdateFrame(double curtime, bool frame)
1354 {
1355         m_logicmgr->UpdateFrame(curtime, frame);
1356 }
1357
1358
1359
1360 void KX_Scene::LogicEndFrame()
1361 {
1362         m_logicmgr->EndFrame();
1363         int numobj = m_euthanasyobjects->GetCount();
1364         int i;
1365         for (i = numobj - 1; i >= 0; i--)
1366         {
1367                 KX_GameObject* gameobj = (KX_GameObject*)m_euthanasyobjects->GetValue(i);
1368                 // KX_Scene::RemoveObject will also remove the object from this list
1369                 // that's why we start from the end
1370                 this->RemoveObject(gameobj);
1371         }
1372
1373         numobj= m_delayReleaseObjects->GetCount();
1374         for (i = numobj-1;i>=0;i--)
1375         {
1376                 KX_GameObject* gameobj = (KX_GameObject*)m_delayReleaseObjects->GetValue(i);
1377                 // This list is not for object removal, but just object release
1378                 gameobj->Release();
1379         }
1380         // empty the list as we have removed all references
1381         m_delayReleaseObjects->Resize(0);       
1382 }
1383
1384
1385
1386 /**
1387   * UpdateParents: SceneGraph transformation update.
1388   */
1389 void KX_Scene::UpdateParents(double curtime)
1390 {
1391 //      int numrootobjects = GetRootParentList()->GetCount();
1392
1393         for (int i=0; i<GetRootParentList()->GetCount(); i++)
1394         {
1395                 KX_GameObject* parentobj = (KX_GameObject*)GetRootParentList()->GetValue(i);
1396                 parentobj->NodeUpdateGS(curtime,true);
1397         }
1398 }
1399
1400
1401
1402 RAS_MaterialBucket* KX_Scene::FindBucket(class RAS_IPolyMaterial* polymat, bool &bucketCreated)
1403 {
1404         return m_bucketmanager->FindBucket(polymat, bucketCreated);
1405 }
1406
1407
1408
1409 void KX_Scene::RenderBuckets(const MT_Transform & cameratransform,
1410                                                          class RAS_IRasterizer* rasty,
1411                                                          class RAS_IRenderTools* rendertools)
1412 {
1413         m_bucketmanager->Renderbuckets(cameratransform,rasty,rendertools);
1414         KX_BlenderMaterial::EndFrame();
1415 }
1416
1417 void KX_Scene::UpdateObjectActivity(void) 
1418 {
1419         if (m_activity_culling) {
1420                 /* determine the activity criterium and set objects accordingly */
1421                 int i=0;
1422                 
1423                 MT_Point3 camloc = GetActiveCamera()->NodeGetWorldPosition(); //GetCameraLocation();
1424                 
1425                 for (i=0;i<GetObjectList()->GetCount();i++)
1426                 {
1427                         KX_GameObject* ob = (KX_GameObject*) GetObjectList()->GetValue(i);
1428                         
1429                         if (!ob->GetIgnoreActivityCulling()) {
1430                                 /* Simple test: more than 10 away from the camera, count
1431                                  * Manhattan distance. */
1432                                 MT_Point3 obpos = ob->NodeGetWorldPosition();
1433                                 
1434                                 if ( (fabs(camloc[0] - obpos[0]) > m_activity_box_radius)
1435                                          || (fabs(camloc[1] - obpos[1]) > m_activity_box_radius)
1436                                          || (fabs(camloc[2] - obpos[2]) > m_activity_box_radius) )
1437                                 {                       
1438                                         ob->Suspend();
1439                                 } else {
1440                                         ob->Resume();
1441                                 }
1442                         }
1443                 }               
1444         }
1445 }
1446
1447 void KX_Scene::SetActivityCullingRadius(float f)
1448 {
1449         if (f < 0.5)
1450                 f = 0.5;
1451         m_activity_box_radius = f;
1452 }
1453         
1454 NG_NetworkDeviceInterface* KX_Scene::GetNetworkDeviceInterface()
1455 {
1456         return m_networkDeviceInterface;
1457 }
1458
1459 NG_NetworkScene* KX_Scene::GetNetworkScene()
1460 {
1461         return m_networkScene;
1462 }
1463
1464 void KX_Scene::SetNetworkDeviceInterface(NG_NetworkDeviceInterface* newInterface)
1465 {
1466         m_networkDeviceInterface = newInterface;
1467 }
1468
1469 void KX_Scene::SetNetworkScene(NG_NetworkScene *newScene)
1470 {
1471         m_networkScene = newScene;
1472 }
1473
1474
1475 void    KX_Scene::SetGravity(const MT_Vector3& gravity)
1476 {
1477         GetPhysicsEnvironment()->setGravity(gravity[0],gravity[1],gravity[2]);
1478 }
1479
1480 void KX_Scene::SetNodeTree(SG_Tree* root)
1481 {
1482         m_objecttree = root;
1483 }
1484
1485 void KX_Scene::SetSceneConverter(class KX_BlenderSceneConverter* sceneConverter)
1486 {
1487         m_sceneConverter = sceneConverter;
1488 }
1489
1490 void KX_Scene::SetPhysicsEnvironment(class PHY_IPhysicsEnvironment* physEnv)
1491 {
1492         m_physicsEnvironment = physEnv;
1493
1494         KX_TouchEventManager* touchmgr = new KX_TouchEventManager(m_logicmgr, physEnv);
1495         m_logicmgr->RegisterEventManager(touchmgr);
1496         return;
1497 }
1498  
1499 void KX_Scene::setSuspendedTime(double suspendedtime)
1500 {
1501         m_suspendedtime = suspendedtime;
1502 }
1503 double KX_Scene::getSuspendedTime()
1504 {
1505         return m_suspendedtime;
1506 }
1507 void KX_Scene::setSuspendedDelta(double suspendeddelta)
1508 {
1509         m_suspendeddelta = suspendeddelta;
1510 }
1511 double KX_Scene::getSuspendedDelta()
1512 {
1513         return m_suspendeddelta;
1514 }
1515
1516 //----------------------------------------------------------------------------
1517 //Python
1518
1519 PyTypeObject KX_Scene::Type = {
1520         PyObject_HEAD_INIT(NULL)
1521                 0,
1522                 "KX_Scene",
1523                 sizeof(KX_Scene),
1524                 0,
1525                 PyDestructor,
1526                 0,
1527                 0,
1528                 0,
1529                 0,
1530                 py_base_repr,
1531                 0,0,0,0,0,0,
1532                 py_base_getattro,
1533                 py_base_setattro,
1534                 0,0,0,0,0,0,0,0,0,
1535                 Methods
1536 };
1537
1538 PyParentObject KX_Scene::Parents[] = {
1539         &KX_Scene::Type,
1540                 &CValue::Type,
1541                 NULL
1542 };
1543
1544 PyMethodDef KX_Scene::Methods[] = {
1545         KX_PYMETHODTABLE(KX_Scene, getLightList),
1546         KX_PYMETHODTABLE(KX_Scene, getObjectList),
1547         KX_PYMETHODTABLE(KX_Scene, getName),
1548         KX_PYMETHODTABLE(KX_Scene, addObject),
1549         
1550         {NULL,NULL} //Sentinel
1551 };
1552
1553 PyObject* KX_Scene::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1554 {
1555         KX_Scene* self= static_cast<KX_Scene*>(self_v);
1556         return PyString_FromString(self->GetName().ReadPtr());
1557 }
1558
1559 PyObject* KX_Scene::pyattr_get_objects(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1560 {
1561         KX_Scene* self= static_cast<KX_Scene*>(self_v);
1562         return self->GetObjectList()->AddRef();
1563 }
1564
1565 PyObject* KX_Scene::pyattr_get_active_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1566 {
1567         KX_Scene* self= static_cast<KX_Scene*>(self_v);
1568         return self->GetActiveCamera()->AddRef();
1569 }
1570
1571 /* __dict__ only for the purpose of giving useful dir() results */
1572 PyObject* KX_Scene::pyattr_get_dir_dict(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1573 {
1574         KX_Scene* self= static_cast<KX_Scene*>(self_v);
1575         /* Useually done by py_getattro_up but in this case we want to include m_attrlist dict */
1576         PyObject *dict_str= PyString_FromString("__dict__");
1577         PyObject *dict= _getattr_dict(self->PyObjectPlus::py_getattro(dict_str), KX_Scene::Methods, KX_Scene::Attributes);
1578         Py_DECREF(dict_str);
1579         
1580         PyDict_Update(dict, self->m_attrlist);
1581         return dict;
1582 }
1583
1584 PyAttributeDef KX_Scene::Attributes[] = {
1585         KX_PYATTRIBUTE_RO_FUNCTION("name",                      KX_Scene, pyattr_get_name),
1586         KX_PYATTRIBUTE_RO_FUNCTION("objects",           KX_Scene, pyattr_get_objects),
1587         KX_PYATTRIBUTE_RO_FUNCTION("active_camera",     KX_Scene, pyattr_get_active_camera),
1588         KX_PYATTRIBUTE_BOOL_RO("suspended",                     KX_Scene, m_suspend),
1589         KX_PYATTRIBUTE_BOOL_RO("activity_culling",      KX_Scene, m_activity_culling),
1590         KX_PYATTRIBUTE_FLOAT_RW("activity_culling_radius", 0.5f, FLT_MAX, KX_Scene, m_activity_box_radius),
1591         KX_PYATTRIBUTE_RO_FUNCTION("__dict__",          KX_Scene, pyattr_get_dir_dict),
1592         { NULL }        //Sentinel
1593 };
1594
1595 PyObject* KX_Scene::py_getattro(PyObject *attr)
1596 {
1597         PyObject* object = py_getattro_self(Attributes, this, attr);
1598         if (object != NULL)
1599                 return object;
1600         
1601         object = PyDict_GetItem(m_attrlist, attr);
1602         if (object)
1603         {
1604                 Py_INCREF(object);
1605                 return object;
1606         }
1607         
1608         py_getattro_up(PyObjectPlus);
1609 }
1610
1611 int KX_Scene::py_delattro(PyObject *attr)
1612 {
1613         PyDict_DelItem(m_attrlist, attr);
1614         return 0;
1615 }
1616
1617 int KX_Scene::py_setattro(PyObject *attr, PyObject *pyvalue)
1618 {
1619         if (!PyDict_SetItem(m_attrlist, attr, pyvalue))
1620                 return 0;
1621
1622         return PyObjectPlus::py_setattro(attr, pyvalue);
1623 }
1624
1625 KX_PYMETHODDEF_DOC_NOARGS(KX_Scene, getLightList,
1626 "getLightList() -> list [KX_Light]\n"
1627 "Returns a list of all lights in the scene.\n"
1628 )
1629 {
1630         return (PyObject*) m_lightlist->AddRef();
1631 }
1632
1633 KX_PYMETHODDEF_DOC_NOARGS(KX_Scene, getObjectList,
1634 "getObjectList() -> list [KX_GameObject]\n"
1635 "Returns a list of all game objects in the scene.\n"
1636 )
1637 {
1638         // ShowDeprecationWarning("getObjectList()", "the objects property"); // XXX Grr, why doesnt this work?
1639         return (PyObject*) m_objectlist->AddRef();
1640 }
1641
1642 KX_PYMETHODDEF_DOC_NOARGS(KX_Scene, getName,
1643 "getName() -> string\n"
1644 "Returns the name of the scene.\n"
1645 )
1646 {
1647         return PyString_FromString(GetName());
1648 }
1649
1650 KX_PYMETHODDEF_DOC(KX_Scene, addObject,
1651 "addObject(object, other, time=0)\n"
1652 "Returns the added object.\n")
1653 {
1654         PyObject *pyob, *pyother;
1655         KX_GameObject *ob, *other;
1656
1657         int time = 0;
1658
1659         if (!PyArg_ParseTuple(args, "OO|i", &pyob, &pyother, &time))
1660                 return NULL;
1661
1662         if (!ConvertPythonToGameObject(pyob, &ob, false)
1663                 || !ConvertPythonToGameObject(pyother, &other, false))
1664                 return NULL;
1665
1666
1667         SCA_IObject* replica = AddReplicaObject((SCA_IObject*)ob, other, time);
1668         replica->AddRef();
1669         return replica;
1670 }