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