svn merge -r 15529:15649 https://svn.blender.org/svnroot/bf-blender/trunk/blender
[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         // for group duplication, limit the duplication of the hierarchy to the
435         // objects that are part of the group. 
436         if (!IsObjectInGroup(gameobj))
437                 return NULL;
438         
439         KX_GameObject* orgobj = (KX_GameObject*)gameobj;
440         KX_GameObject* newobj = (KX_GameObject*)orgobj->GetReplica();
441         m_map_gameobject_to_replica.insert(orgobj, newobj);
442
443         // also register 'timers' (time properties) of the replica
444         int numprops = newobj->GetPropertyCount();
445
446         for (int i = 0; i < numprops; i++)
447         {
448                 CValue* prop = newobj->GetProperty(i);
449
450                 if (prop->GetProperty("timer"))
451                         this->m_timemgr->AddTimeProperty(prop);
452         }
453
454         if (node)
455         {
456                 newobj->SetSGNode((SG_Node*)node);
457         }
458         else
459         {
460                 m_rootnode = new SG_Node(newobj,this,KX_Scene::m_callbacks);
461         
462                 // this fixes part of the scaling-added object bug
463                 SG_Node* orgnode = orgobj->GetSGNode();
464                 m_rootnode->SetLocalScale(orgnode->GetLocalScale());
465                 m_rootnode->SetLocalPosition(orgnode->GetLocalPosition());
466                 m_rootnode->SetLocalOrientation(orgnode->GetLocalOrientation());
467
468                 // define the relationship between this node and it's parent.
469                 KX_NormalParentRelation * parent_relation = 
470                         KX_NormalParentRelation::New();
471                 m_rootnode->SetParentRelation(parent_relation);
472
473                 newobj->SetSGNode(m_rootnode);
474         }
475         
476         SG_IObject* replicanode = newobj->GetSGNode();
477 //      SG_Node* rootnode = (replicanode == m_rootnode ? NULL : m_rootnode);
478
479         replicanode->SetSGClientObject(newobj);
480
481         // this is the list of object that are send to the graphics pipeline
482         m_objectlist->Add(newobj->AddRef());
483         newobj->Bucketize();
484
485         // logic cannot be replicated, until the whole hierarchy is replicated.
486         m_logicHierarchicalGameObjects.push_back(newobj);
487         //replicate controllers of this node
488         SGControllerList        scenegraphcontrollers = orgobj->GetSGNode()->GetSGControllerList();
489         replicanode->RemoveAllControllers();
490         SGControllerList::iterator cit;
491         //int numcont = scenegraphcontrollers.size();
492         
493         for (cit = scenegraphcontrollers.begin();!(cit==scenegraphcontrollers.end());++cit)
494         {
495                 // controller replication is quite complicated
496                 // only replicate ipo and physics controller for now
497
498                 SG_Controller* replicacontroller = (*cit)->GetReplica((SG_Node*) replicanode);
499                 if (replicacontroller)
500                 {
501                         replicacontroller->SetObject(replicanode);
502                         replicanode->AddSGController(replicacontroller);
503                 }
504         }
505         
506         return newobj;
507 }
508
509
510
511 // before calling this method KX_Scene::ReplicateLogic(), make sure to
512 // have called 'GameObject::ReParentLogic' for each object this
513 // hierarchy that's because first ALL bricks must exist in the new
514 // replica of the hierarchy in order to make cross-links work properly
515 // !
516 // It is VERY important that the order of sensors and actuators in
517 // the replicated object is preserved: it is is used to reconnect the logic.
518 // This method is more robust then using the bricks name in case of complex 
519 // group replication. The replication of logic bricks is done in 
520 // SCA_IObject::ReParentLogic(), make sure it preserves the order of the bricks.
521 void KX_Scene::ReplicateLogic(KX_GameObject* newobj)
522 {
523         // also relink the controller to sensors/actuators
524         SCA_ControllerList& controllers = newobj->GetControllers();
525         //SCA_SensorList&     sensors     = newobj->GetSensors();
526         //SCA_ActuatorList&   actuators   = newobj->GetActuators();
527
528         for (SCA_ControllerList::iterator itc = controllers.begin(); !(itc==controllers.end());itc++)
529         {
530                 SCA_IController* cont = (*itc);
531                 cont->SetUeberExecutePriority(m_ueberExecutionPriority);
532                 vector<SCA_ISensor*> linkedsensors = cont->GetLinkedSensors();
533                 vector<SCA_IActuator*> linkedactuators = cont->GetLinkedActuators();
534
535                 // disconnect the sensors and actuators
536                 cont->UnlinkAllSensors();
537                 cont->UnlinkAllActuators();
538                 
539                 // now relink each sensor
540                 for (vector<SCA_ISensor*>::iterator its = linkedsensors.begin();!(its==linkedsensors.end());its++)
541                 {
542                         SCA_ISensor* oldsensor = (*its);
543                         SCA_IObject* oldsensorobj = oldsensor->GetParent();
544                         SCA_IObject* newsensorobj = NULL;
545                 
546                         // the original owner of the sensor has been replicated?
547                         void **h_obj = m_map_gameobject_to_replica[oldsensorobj];
548                         if (h_obj)
549                                 newsensorobj = (SCA_IObject*)(*h_obj);
550                         if (!newsensorobj)
551                         {
552                                 // no, then the sensor points outside the hierachy, keep it the same
553                                 if (m_objectlist->SearchValue(oldsensorobj))
554                                         // only replicate links that points to active objects
555                                         m_logicmgr->RegisterToSensor(cont,oldsensor);
556                         }
557                         else
558                         {
559                                 // yes, then the new sensor has the same position
560                                 SCA_SensorList& sensorlist = oldsensorobj->GetSensors();
561                                 SCA_SensorList::iterator sit;
562                                 SCA_ISensor* newsensor = NULL;
563                                 int sensorpos;
564
565                                 for (sensorpos=0, sit=sensorlist.begin(); sit!=sensorlist.end(); sit++, sensorpos++)
566                                 {
567                                         if ((*sit) == oldsensor) 
568                                         {
569                                                 newsensor = newsensorobj->GetSensors().at(sensorpos);
570                                                 break;
571                                         }
572                                 }
573                                 assert(newsensor != NULL);
574                                 m_logicmgr->RegisterToSensor(cont,newsensor);
575                         }
576                 }
577                 
578                 // now relink each actuator
579                 for (vector<SCA_IActuator*>::iterator ita = linkedactuators.begin();!(ita==linkedactuators.end());ita++)
580                 {
581                         SCA_IActuator* oldactuator = (*ita);
582                         SCA_IObject* oldactuatorobj = oldactuator->GetParent();
583                         SCA_IObject* newactuatorobj = NULL;
584
585                         // the original owner of the sensor has been replicated?
586                         void **h_obj = m_map_gameobject_to_replica[oldactuatorobj];
587                         if (h_obj)
588                                 newactuatorobj = (SCA_IObject*)(*h_obj);
589
590                         if (!newactuatorobj)
591                         {
592                                 // no, then the sensor points outside the hierachy, keep it the same
593                                 if (m_objectlist->SearchValue(oldactuatorobj))
594                                         // only replicate links that points to active objects
595                                         m_logicmgr->RegisterToActuator(cont,oldactuator);
596                         }
597                         else
598                         {
599                                 // yes, then the new sensor has the same position
600                                 SCA_ActuatorList& actuatorlist = oldactuatorobj->GetActuators();
601                                 SCA_ActuatorList::iterator ait;
602                                 SCA_IActuator* newactuator = NULL;
603                                 int actuatorpos;
604
605                                 for (actuatorpos=0, ait=actuatorlist.begin(); ait!=actuatorlist.end(); ait++, actuatorpos++)
606                                 {
607                                         if ((*ait) == oldactuator) 
608                                         {
609                                                 newactuator = newactuatorobj->GetActuators().at(actuatorpos);
610                                                 break;
611                                         }
612                                 }
613                                 assert(newactuator != NULL);
614                                 m_logicmgr->RegisterToActuator(cont,newactuator);
615                                 newactuator->SetUeberExecutePriority(m_ueberExecutionPriority);
616                         }
617                 }
618         }
619         // ready to set initial state
620         newobj->ResetState();
621 }
622
623 void KX_Scene::DupliGroupRecurse(CValue* obj, int level)
624 {
625         KX_GameObject* groupobj = (KX_GameObject*) obj;
626         KX_GameObject* replica;
627         KX_GameObject* gameobj;
628         Object* blgroupobj = groupobj->GetBlenderObject();
629         Group* group;
630         GroupObject *go;
631         vector<KX_GameObject*> duplilist;
632
633         if (!groupobj->IsDupliGroup() ||
634                 level>MAX_DUPLI_RECUR)
635                 return;
636
637         // we will add one group at a time
638         m_logicHierarchicalGameObjects.clear();
639         m_map_gameobject_to_replica.clear();
640         m_ueberExecutionPriority++;
641         // for groups will do something special: 
642         // we will force the creation of objects to those in the group only
643         // Again, this is match what Blender is doing (it doesn't care of parent relationship)
644         m_groupGameObjects.clear();
645
646         group = blgroupobj->dup_group;
647         for(go=(GroupObject*)group->gobject.first; go; go=(GroupObject*)go->next) 
648         {
649                 Object* blenderobj = go->ob;
650                 if (blgroupobj == blenderobj)
651                         // this check is also in group_duplilist()
652                         continue;
653                 gameobj = m_sceneConverter->FindGameObject(blenderobj);
654                 if (gameobj == NULL) 
655                 {
656                         // this object has not been converted!!!
657                         // Should not happen as dupli group are created automatically 
658                         continue;
659                 }
660                 if (blenderobj->lay & group->layer==0)
661                 {
662                         // object is not visible in the 3D view, will not be instantiated
663                         continue;
664                 }
665                 m_groupGameObjects.insert(gameobj);
666         }
667
668         set<CValue*>::iterator oit;
669         for (oit=m_groupGameObjects.begin(); oit != m_groupGameObjects.end(); oit++)
670         {
671                 gameobj = (KX_GameObject*)(*oit);
672                 if (gameobj->GetParent() != NULL)
673                 {
674                         // this object is not a top parent. Either it is the child of another
675                         // object in the group and it will be added automatically when the parent
676                         // is added. Or it is the child of an object outside the group and the group
677                         // is inconsistent, skip it anyway
678                         continue;
679                 }
680                 replica = (KX_GameObject*) AddNodeReplicaObject(NULL,gameobj);
681                 // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame)
682                 m_parentlist->Add(replica->AddRef());
683
684                 // recurse replication into children nodes
685                 NodeList& children = gameobj->GetSGNode()->GetSGChildren();
686
687                 replica->GetSGNode()->ClearSGChildren();
688                 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
689                 {
690                         SG_Node* orgnode = (*childit);
691                         SG_Node* childreplicanode = orgnode->GetSGReplica();
692                         if (childreplicanode)
693                                 replica->GetSGNode()->AddChild(childreplicanode);
694                 }
695                 // don't replicate logic now: we assume that the objects in the group can have
696                 // logic relationship, even outside parent relationship
697                 // In order to match 3D view, the position of groupobj is used as a 
698                 // transformation matrix instead of the new position. This means that 
699                 // the group reference point is 0,0,0
700
701                 // get the rootnode's scale
702                 MT_Vector3 newscale = groupobj->NodeGetWorldScaling();
703                 // set the replica's relative scale with the rootnode's scale
704                 replica->NodeSetRelativeScale(newscale);
705
706                 MT_Matrix3x3 newori = groupobj->NodeGetWorldOrientation() * gameobj->NodeGetWorldOrientation();
707                 replica->NodeSetLocalOrientation(newori);
708
709                 MT_Point3 newpos = groupobj->NodeGetWorldPosition() + 
710                         newscale*(groupobj->NodeGetWorldOrientation() * gameobj->NodeGetWorldPosition());
711                 replica->NodeSetLocalPosition(newpos);
712
713                 if (replica->GetPhysicsController())
714                 {
715                         replica->GetPhysicsController()->setPosition(newpos);
716                         replica->GetPhysicsController()->setOrientation(newori.getRotation());
717                         replica->GetPhysicsController()->setScaling(newscale);
718                 }
719
720                 replica->GetSGNode()->UpdateWorldData(0);
721                 replica->GetSGNode()->SetBBox(gameobj->GetSGNode()->BBox());
722                 replica->GetSGNode()->SetRadius(gameobj->GetSGNode()->Radius());
723                 // done with replica
724                 replica->Release();
725         }
726
727         // the logic must be replicated first because we need
728         // the new logic bricks before relinking
729         vector<KX_GameObject*>::iterator git;
730         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
731         {
732                 (*git)->ReParentLogic();
733         }
734         
735         //      relink any pointers as necessary, sort of a temporary solution
736         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
737         {
738                 // this will also relink the actuator to objects within the hierarchy
739                 (*git)->Relink(&m_map_gameobject_to_replica);
740                 // add the object in the layer of the parent
741                 (*git)->SetLayer(groupobj->GetLayer());
742         }
743
744         // replicate crosslinks etc. between logic bricks
745         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
746         {
747                 ReplicateLogic((*git));
748         }
749         
750         // now look if object in the hierarchy have dupli group and recurse
751         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
752         {
753                 if ((*git) != groupobj && (*git)->IsDupliGroup())
754                         // can't instantiate group immediately as it destroys m_logicHierarchicalGameObjects
755                         duplilist.push_back((*git));
756         }
757
758         for (git = duplilist.begin(); !(git == duplilist.end()); ++git)
759         {
760                 DupliGroupRecurse((*git), level+1);
761         }
762 }
763
764
765 SCA_IObject* KX_Scene::AddReplicaObject(class CValue* originalobject,
766                                                                                 class CValue* parentobject,
767                                                                                 int lifespan)
768 {
769
770         m_logicHierarchicalGameObjects.clear();
771         m_map_gameobject_to_replica.clear();
772         m_groupGameObjects.clear();
773
774         // todo: place a timebomb in the object, for temporarily objects :)
775         // lifespan of zero means 'this object lives forever'
776         KX_GameObject* originalobj = (KX_GameObject*) originalobject;
777         KX_GameObject* parentobj = (KX_GameObject*) parentobject;
778
779         m_ueberExecutionPriority++;
780
781         // lets create a replica
782         KX_GameObject* replica = (KX_GameObject*) AddNodeReplicaObject(NULL,originalobj);
783
784         if (lifespan > 0)
785         {
786                 // add a timebomb to this object
787                 // for now, convert between so called frames and realtime
788                 m_tempObjectList->Add(replica->AddRef());
789                 CValue *fval = new CFloatValue(lifespan*0.02);
790                 replica->SetProperty("::timebomb",fval);
791                 fval->Release();
792         }
793
794         // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame)
795         m_parentlist->Add(replica->AddRef());
796
797         // recurse replication into children nodes
798
799         NodeList& children = originalobj->GetSGNode()->GetSGChildren();
800
801         replica->GetSGNode()->ClearSGChildren();
802         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
803         {
804                 SG_Node* orgnode = (*childit);
805                 SG_Node* childreplicanode = orgnode->GetSGReplica();
806                 if (childreplicanode)
807                         replica->GetSGNode()->AddChild(childreplicanode);
808         }
809
810         // now replicate logic
811         vector<KX_GameObject*>::iterator git;
812         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
813         {
814                 (*git)->ReParentLogic();
815         }
816         
817         //      relink any pointers as necessary, sort of a temporary solution
818         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
819         {
820                 // this will also relink the actuators in the hierarchy
821                 (*git)->Relink(&m_map_gameobject_to_replica);
822                 // add the object in the layer of the parent
823                 (*git)->SetLayer(parentobj->GetLayer());
824         }
825
826         // replicate crosslinks etc. between logic bricks
827         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
828         {
829                 ReplicateLogic((*git));
830         }
831         
832         MT_Point3 newpos = ((KX_GameObject*) parentobject)->NodeGetWorldPosition();
833         replica->NodeSetLocalPosition(newpos);
834
835         MT_Matrix3x3 newori = ((KX_GameObject*) parentobject)->NodeGetWorldOrientation();
836         replica->NodeSetLocalOrientation(newori);
837         
838         // get the rootnode's scale
839         MT_Vector3 newscale = parentobj->GetSGNode()->GetRootSGParent()->GetLocalScale();
840
841         // set the replica's relative scale with the rootnode's scale
842         replica->NodeSetRelativeScale(newscale);
843
844         if (replica->GetPhysicsController())
845         {
846                 replica->GetPhysicsController()->setPosition(newpos);
847                 replica->GetPhysicsController()->setOrientation(newori.getRotation());
848                 replica->GetPhysicsController()->setScaling(newscale);
849         }
850
851         // here we want to set the relative scale: the rootnode's scale will override all other
852         // scalings, so lets better prepare for it
853
854
855         replica->GetSGNode()->UpdateWorldData(0);
856         replica->GetSGNode()->SetBBox(originalobj->GetSGNode()->BBox());
857         replica->GetSGNode()->SetRadius(originalobj->GetSGNode()->Radius());
858         //      don't release replica here because we are returning it, not done with it...
859         return replica;
860 }
861
862
863
864 void KX_Scene::RemoveObject(class CValue* gameobj)
865 {
866         KX_GameObject* newobj = (KX_GameObject*) gameobj;
867
868         // first disconnect child from parent
869         SG_Node* node = newobj->GetSGNode();
870
871         if (node)
872         {
873                 node->DisconnectFromParent();
874
875                 // recursively destruct
876                 node->Destruct();
877         }
878         //no need to do that: the object is destroyed and memory released 
879         //newobj->SetSGNode(0);
880 }
881
882 void KX_Scene::DelayedReleaseObject(CValue* gameobj)
883 {
884         m_delayReleaseObjects->Add(gameobj->AddRef());
885 }
886
887
888 void KX_Scene::DelayedRemoveObject(class CValue* gameobj)
889 {
890         //KX_GameObject* newobj = (KX_GameObject*) gameobj;
891         if (!m_euthanasyobjects->SearchValue(gameobj))
892         {
893                 m_euthanasyobjects->Add(gameobj->AddRef());
894         } 
895 }
896
897
898
899 int KX_Scene::NewRemoveObject(class CValue* gameobj)
900 {
901         int ret;
902         KX_GameObject* newobj = (KX_GameObject*) gameobj;
903
904         //todo: look at this
905         //GetPhysicsEnvironment()->RemovePhysicsController(gameobj->getPhysicsController());
906
907         // remove all sensors/controllers/actuators from logicsystem...
908         
909         SCA_SensorList& sensors = newobj->GetSensors();
910         for (SCA_SensorList::iterator its = sensors.begin();
911                  !(its==sensors.end());its++)
912         {
913                 m_logicmgr->RemoveSensor(*its);
914         }
915         
916     SCA_ControllerList& controllers = newobj->GetControllers();
917         for (SCA_ControllerList::iterator itc = controllers.begin();
918                  !(itc==controllers.end());itc++)
919         {
920                 m_logicmgr->RemoveController(*itc);
921         }
922
923         SCA_ActuatorList& actuators = newobj->GetActuators();
924         for (SCA_ActuatorList::iterator ita = actuators.begin();
925                  !(ita==actuators.end());ita++)
926         {
927                 m_logicmgr->RemoveDestroyedActuator(*ita);
928         }
929         // the sensors/controllers/actuators must also be released, this is done in ~SCA_IObject
930
931         // now remove the timer properties from the time manager
932         int numprops = newobj->GetPropertyCount();
933
934         for (int i = 0; i < numprops; i++)
935         {
936                 CValue* propval = newobj->GetProperty(i);
937                 if (propval->GetProperty("timer"))
938                 {
939                         m_timemgr->RemoveTimeProperty(propval);
940                 }
941         }
942         
943         newobj->RemoveMeshes();
944         ret = 1;
945         if (m_objectlist->RemoveValue(newobj))
946                 ret = newobj->Release();
947         if (m_tempObjectList->RemoveValue(newobj))
948                 ret = newobj->Release();
949         if (m_parentlist->RemoveValue(newobj))
950                 ret = newobj->Release();
951         if (m_inactivelist->RemoveValue(newobj))
952                 ret = newobj->Release();
953         if (m_euthanasyobjects->RemoveValue(newobj))
954                 ret = newobj->Release();
955                 
956         if (newobj == m_active_camera)
957         {
958                 //no AddRef done on m_active_camera so no Release
959                 //m_active_camera->Release();
960                 m_active_camera = NULL;
961         }
962         // in case this is a camera
963         m_cameras.remove((KX_Camera*)newobj);
964
965         if (m_sceneConverter)
966                 m_sceneConverter->UnregisterGameObject(newobj);
967         // return value will be 0 if the object is actually deleted (all reference gone)
968         return ret;
969 }
970
971
972
973 void KX_Scene::ReplaceMesh(class CValue* obj,void* meshobj)
974 {
975         KX_GameObject* gameobj = static_cast<KX_GameObject*>(obj);
976         RAS_MeshObject* mesh = static_cast<RAS_MeshObject*>(meshobj);
977
978         if(!gameobj || !mesh)
979         {
980                 std::cout << "warning: invalid object, mesh will not be replaced" << std::endl;
981                 return;
982         }
983
984         gameobj->RemoveMeshes();
985         gameobj->AddMesh(mesh);
986         
987         if (gameobj->m_isDeformable)
988         {
989                 BL_DeformableGameObject* newobj = static_cast<BL_DeformableGameObject*>( gameobj );
990                 
991                 if (newobj->m_pDeformer)
992                 {
993                         delete newobj->m_pDeformer;
994                         newobj->m_pDeformer = NULL;
995                 }
996
997                 if (mesh->m_class == 1) 
998                 {
999                         // we must create a new deformer but which one?
1000                         KX_GameObject* parentobj = newobj->GetParent();
1001                         // this always return the original game object (also for replicate)
1002                         Object* blendobj = newobj->GetBlenderObject();
1003                         // object that owns the new mesh
1004                         Object* oldblendobj = static_cast<struct Object*>(m_logicmgr->FindBlendObjByGameMeshName(mesh->GetName()));
1005                         Mesh* blendmesh = mesh->GetMesh();
1006
1007                         bool bHasShapeKey = blendmesh->key != NULL && blendmesh->key->type==KEY_RELATIVE;
1008                         bool bHasDvert = blendmesh->dvert != NULL;
1009                         bool bHasArmature = 
1010                                 parentobj &&                                                            // current parent is armature
1011                                 parentobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE &&
1012                                 oldblendobj &&                                                          // needed for mesh deform
1013                                 blendobj->parent &&                                                     // original object had armature (not sure this test is needed)
1014                                 blendobj->parent->type == OB_ARMATURE && 
1015                                 blendobj->partype==PARSKEL && 
1016                                 blendmesh->dvert!=NULL;                                         // mesh has vertex group
1017                         bool releaseParent = true;
1018
1019                         if (bHasShapeKey)
1020                         {
1021                                 BL_ShapeDeformer* shapeDeformer;
1022                                 if (bHasArmature) 
1023                                 {
1024                                         shapeDeformer = new BL_ShapeDeformer(
1025                                                 newobj,
1026                                                 oldblendobj, blendobj,
1027                                                 static_cast<BL_SkinMeshObject*>(mesh),
1028                                                 true,
1029                                                 static_cast<BL_ArmatureObject*>( parentobj )
1030                                         );
1031                                         releaseParent= false;
1032                                         shapeDeformer->LoadShapeDrivers(blendobj->parent);
1033                                 }
1034                                 else
1035                                 {
1036                                         shapeDeformer = new BL_ShapeDeformer(
1037                                                 newobj,
1038                                                 oldblendobj, blendobj,
1039                                                 static_cast<BL_SkinMeshObject*>(mesh),
1040                                                 false,
1041                                                 NULL
1042                                         );
1043                                 }
1044                                 newobj->m_pDeformer = shapeDeformer;
1045                         }
1046                         else if (bHasArmature) 
1047                         {
1048                                 BL_SkinDeformer* skinDeformer = new BL_SkinDeformer(
1049                                         newobj,
1050                                         oldblendobj, blendobj,
1051                                         static_cast<BL_SkinMeshObject*>(mesh),
1052                                         true,
1053                                         static_cast<BL_ArmatureObject*>( parentobj )
1054                                 );
1055                                 releaseParent= false;
1056                                 newobj->m_pDeformer = skinDeformer;
1057                         }
1058                         else if (bHasDvert)
1059                         {
1060                                 BL_MeshDeformer* meshdeformer = new BL_MeshDeformer(
1061                                         newobj, oldblendobj, static_cast<BL_SkinMeshObject*>(mesh)
1062                                 );
1063                                 newobj->m_pDeformer = meshdeformer;
1064                         }
1065
1066                         // release parent reference if its not being used 
1067                         if( releaseParent && parentobj)
1068                                 parentobj->Release();
1069                 }
1070         }
1071         gameobj->Bucketize();
1072 }
1073
1074
1075
1076 MT_CmMatrix4x4& KX_Scene::GetViewMatrix()
1077 {
1078         MT_Scalar cammat[16];
1079         m_active_camera->GetWorldToCamera().getValue(cammat);
1080         m_viewmat = cammat;
1081         return m_viewmat;
1082 }
1083
1084
1085
1086 MT_CmMatrix4x4& KX_Scene::GetProjectionMatrix()
1087 {
1088         return m_projectionmat;
1089 }
1090
1091
1092 KX_Camera* KX_Scene::FindCamera(KX_Camera* cam)
1093 {
1094         list<KX_Camera*>::iterator it = m_cameras.begin();
1095
1096         while ( (it != m_cameras.end()) 
1097                         && ((*it) != cam) ) {
1098           it++;
1099         }
1100
1101         return ((it == m_cameras.end()) ? NULL : (*it));
1102 }
1103
1104
1105 KX_Camera* KX_Scene::FindCamera(STR_String& name)
1106 {
1107         list<KX_Camera*>::iterator it = m_cameras.begin();
1108
1109         while ( (it != m_cameras.end()) 
1110                         && ((*it)->GetName() != name) ) {
1111           it++;
1112         }
1113
1114         return ((it == m_cameras.end()) ? NULL : (*it));
1115 }
1116
1117 void KX_Scene::AddCamera(KX_Camera* cam)
1118 {
1119         if (!FindCamera(cam))
1120                 m_cameras.push_back(cam);
1121 }
1122
1123
1124 KX_Camera* KX_Scene::GetActiveCamera()
1125 {       
1126         // NULL if not defined
1127         return m_active_camera;
1128 }
1129
1130
1131 void KX_Scene::SetActiveCamera(KX_Camera* cam)
1132 {
1133         // only set if the cam is in the active list? Or add it otherwise?
1134         if (!FindCamera(cam)){
1135                 AddCamera(cam);
1136                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
1137         } 
1138
1139         m_active_camera = cam;
1140 }
1141
1142 void KX_Scene::SetCameraOnTop(KX_Camera* cam)
1143 {
1144         if (!FindCamera(cam)){
1145                 // adding is always done at the back, so that's all that needs to be done
1146                 AddCamera(cam);
1147                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
1148         } else {
1149                 m_cameras.remove(cam);
1150                 m_cameras.push_back(cam);
1151         }
1152 }
1153
1154
1155 void KX_Scene::UpdateMeshTransformations()
1156 {
1157         // do this incrementally in the future
1158         for (int i = 0; i < m_objectlist->GetCount(); i++)
1159         {
1160                 KX_GameObject* gameobj = (KX_GameObject*)m_objectlist->GetValue(i);
1161                 gameobj->GetOpenGLMatrix();
1162 //              gameobj->UpdateNonDynas();
1163         }
1164 }
1165
1166 void KX_Scene::MarkVisible(SG_Tree *node, RAS_IRasterizer* rasty, KX_Camera* cam, int layer)
1167 {
1168         int intersect = KX_Camera::INTERSECT;
1169         KX_GameObject *gameobj = node->Client()?(KX_GameObject*) node->Client()->GetSGClientObject():NULL;
1170         bool visible = (gameobj && gameobj->GetVisible() && (!layer || (gameobj->GetLayer() & layer)));
1171         bool dotest = visible || node->Left() || node->Right();
1172
1173         /* If the camera is inside the box, assume intersect. */
1174         if (dotest && !node->inside( cam->NodeGetWorldPosition()))
1175         {
1176                 MT_Scalar radius = node->Radius();
1177                 MT_Point3 center = node->Center();
1178                 
1179                 intersect =  cam->SphereInsideFrustum(center, radius); 
1180                 
1181                 if (intersect == KX_Camera::INTERSECT)
1182                 {
1183                         MT_Point3 box[8];
1184                         node->get(box);
1185                         intersect = cam->BoxInsideFrustum(box);
1186                 }
1187         }
1188
1189         switch (intersect)
1190         {
1191                 case KX_Camera::OUTSIDE:
1192                         MarkSubTreeVisible(node, rasty, false, cam);
1193                         break;
1194                 case KX_Camera::INTERSECT:
1195                         if (gameobj)
1196                                 MarkVisible(rasty, gameobj, cam, layer);
1197                         if (node->Left())
1198                                 MarkVisible(node->Left(), rasty, cam, layer);
1199                         if (node->Right())
1200                                 MarkVisible(node->Right(), rasty, cam, layer);
1201                         break;
1202                 case KX_Camera::INSIDE:
1203                         MarkSubTreeVisible(node, rasty, true, cam, layer);
1204                         break;
1205         }
1206 }
1207
1208 void KX_Scene::MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool visible, KX_Camera* cam, int layer)
1209 {
1210         if (node->Client())
1211         {
1212                 KX_GameObject *gameobj = (KX_GameObject*) node->Client()->GetSGClientObject();
1213                 if (gameobj->GetVisible())
1214                 {
1215                         if (visible)
1216                         {
1217                                 int nummeshes = gameobj->GetMeshCount();
1218                                 MT_Transform t( cam->GetWorldToCamera() * gameobj->GetSGNode()->GetWorldTransform());
1219         
1220                                 
1221                                 for (int m=0;m<nummeshes;m++)
1222                                 {
1223                                         // this adds the vertices to the display list
1224                                         (gameobj->GetMesh(m))->SchedulePolygons(t, rasty->GetDrawingMode());
1225                                 }
1226                         }
1227                         gameobj->MarkVisible(visible);
1228                 }
1229         }
1230         if (node->Left())
1231                 MarkSubTreeVisible(node->Left(), rasty, visible, cam, layer);
1232         if (node->Right())
1233                 MarkSubTreeVisible(node->Right(), rasty, visible, cam, layer);
1234 }
1235
1236 void KX_Scene::MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj,KX_Camera*  cam,int layer)
1237 {
1238         // User (Python/Actuator) has forced object invisible...
1239         if (!gameobj->GetVisible())
1240                 return;
1241         
1242         // Shadow lamp layers
1243         if(layer && !(gameobj->GetLayer() & layer)) {
1244                 gameobj->MarkVisible(false);
1245                 return;
1246         }
1247
1248         // If Frustum culling is off, the object is always visible.
1249         bool vis = !cam->GetFrustumCulling();
1250         
1251         // If the camera is inside this node, then the object is visible.
1252         if (!vis)
1253         {
1254                 vis = gameobj->GetSGNode()->inside( GetActiveCamera()->GetCameraLocation() );
1255         }
1256                 
1257         // Test the object's bound sphere against the view frustum.
1258         if (!vis)
1259         {
1260                 MT_Vector3 scale = gameobj->GetSGNode()->GetWorldScaling();
1261                 MT_Scalar radius = fabs(scale[scale.closestAxis()] * gameobj->GetSGNode()->Radius());
1262                 switch (cam->SphereInsideFrustum(gameobj->NodeGetWorldPosition(), radius))
1263                 {
1264                         case KX_Camera::INSIDE:
1265                                 vis = true;
1266                                 break;
1267                         case KX_Camera::OUTSIDE:
1268                                 vis = false;
1269                                 break;
1270                         case KX_Camera::INTERSECT:
1271                                 // Test the object's bound box against the view frustum.
1272                                 MT_Point3 box[8];
1273                                 gameobj->GetSGNode()->getBBox(box); 
1274                                 vis = cam->BoxInsideFrustum(box) != KX_Camera::OUTSIDE;
1275                                 break;
1276                 }
1277         }
1278         
1279         if (vis)
1280         {
1281                 int nummeshes = gameobj->GetMeshCount();
1282                 MT_Transform t(cam->GetWorldToCamera() * gameobj->GetSGNode()->GetWorldTransform());
1283                 
1284                 for (int m=0;m<nummeshes;m++)
1285                 {
1286                         // this adds the vertices to the display list
1287                         (gameobj->GetMesh(m))->SchedulePolygons(t, rasty->GetDrawingMode());
1288                 }
1289                 // Visibility/ non-visibility are marked
1290                 // elsewhere now.
1291                 gameobj->MarkVisible();
1292         } else {
1293                 gameobj->MarkVisible(false);
1294         }
1295 }
1296
1297 void KX_Scene::CalculateVisibleMeshes(RAS_IRasterizer* rasty,KX_Camera* cam, int layer)
1298 {
1299 // FIXME: When tree is operational
1300 #if 1
1301         // do this incrementally in the future
1302         for (int i = 0; i < m_objectlist->GetCount(); i++)
1303         {
1304                 MarkVisible(rasty, static_cast<KX_GameObject*>(m_objectlist->GetValue(i)), cam, layer);
1305         }
1306 #else
1307         if (cam->GetFrustumCulling())
1308                 MarkVisible(m_objecttree, rasty, cam, layer);
1309         else
1310                 MarkSubTreeVisible(m_objecttree, rasty, true, cam, layer);
1311 #endif
1312 }
1313
1314 // logic stuff
1315 void KX_Scene::LogicBeginFrame(double curtime)
1316 {
1317         // have a look at temp objects ...
1318         int lastobj = m_tempObjectList->GetCount() - 1;
1319         
1320         for (int i = lastobj; i >= 0; i--)
1321         {
1322                 CValue* objval = m_tempObjectList->GetValue(i);
1323                 CFloatValue* propval = (CFloatValue*) objval->GetProperty("::timebomb");
1324                 
1325                 if (propval)
1326                 {
1327                         float timeleft = propval->GetNumber() - 1.0/KX_KetsjiEngine::GetTicRate();
1328                         
1329                         if (timeleft > 0)
1330                         {
1331                                 propval->SetFloat(timeleft);
1332                         }
1333                         else
1334                         {
1335                                 DelayedRemoveObject(objval);
1336                                 // remove obj
1337                         }
1338                 }
1339                 else
1340                 {
1341                         // all object is the tempObjectList should have a clock
1342                 }
1343         }
1344         m_logicmgr->BeginFrame(curtime, 1.0/KX_KetsjiEngine::GetTicRate());
1345 }
1346
1347
1348
1349 void KX_Scene::LogicUpdateFrame(double curtime, bool frame)
1350 {
1351         m_logicmgr->UpdateFrame(curtime, frame);
1352 }
1353
1354
1355
1356 void KX_Scene::LogicEndFrame()
1357 {
1358         m_logicmgr->EndFrame();
1359         int numobj = m_euthanasyobjects->GetCount();
1360         int i;
1361         for (i = numobj - 1; i >= 0; i--)
1362         {
1363                 KX_GameObject* gameobj = (KX_GameObject*)m_euthanasyobjects->GetValue(i);
1364                 // KX_Scene::RemoveObject will also remove the object from this list
1365                 // that's why we start from the end
1366                 this->RemoveObject(gameobj);
1367         }
1368
1369         numobj= m_delayReleaseObjects->GetCount();
1370         for (i = numobj-1;i>=0;i--)
1371         {
1372                 KX_GameObject* gameobj = (KX_GameObject*)m_delayReleaseObjects->GetValue(i);
1373                 // This list is not for object removal, but just object release
1374                 gameobj->Release();
1375         }
1376         // empty the list as we have removed all references
1377         m_delayReleaseObjects->Resize(0);       
1378 }
1379
1380
1381
1382 /**
1383   * UpdateParents: SceneGraph transformation update.
1384   */
1385 void KX_Scene::UpdateParents(double curtime)
1386 {
1387 //      int numrootobjects = GetRootParentList()->GetCount();
1388
1389         for (int i=0; i<GetRootParentList()->GetCount(); i++)
1390         {
1391                 KX_GameObject* parentobj = (KX_GameObject*)GetRootParentList()->GetValue(i);
1392                 parentobj->NodeUpdateGS(curtime,true);
1393         }
1394 }
1395
1396
1397
1398 RAS_MaterialBucket* KX_Scene::FindBucket(class RAS_IPolyMaterial* polymat, bool &bucketCreated)
1399 {
1400         return m_bucketmanager->RAS_BucketManagerFindBucket(polymat, bucketCreated);
1401 }
1402
1403
1404
1405 void KX_Scene::RenderBuckets(const MT_Transform & cameratransform,
1406                                                          class RAS_IRasterizer* rasty,
1407                                                          class RAS_IRenderTools* rendertools)
1408 {
1409         m_bucketmanager->Renderbuckets(cameratransform,rasty,rendertools);
1410 }
1411
1412
1413
1414 void KX_Scene::UpdateObjectActivity(void) 
1415 {
1416         if (m_activity_culling) {
1417                 /* determine the activity criterium and set objects accordingly */
1418                 int i=0;
1419                 
1420                 MT_Point3 camloc = GetActiveCamera()->NodeGetWorldPosition(); //GetCameraLocation();
1421                 
1422                 for (i=0;i<GetObjectList()->GetCount();i++)
1423                 {
1424                         KX_GameObject* ob = (KX_GameObject*) GetObjectList()->GetValue(i);
1425                         
1426                         if (!ob->GetIgnoreActivityCulling()) {
1427                                 /* Simple test: more than 10 away from the camera, count
1428                                  * Manhattan distance. */
1429                                 MT_Point3 obpos = ob->NodeGetWorldPosition();
1430                                 
1431                                 if ( (fabs(camloc[0] - obpos[0]) > m_activity_box_radius)
1432                                          || (fabs(camloc[1] - obpos[1]) > m_activity_box_radius)
1433                                          || (fabs(camloc[2] - obpos[2]) > m_activity_box_radius) )
1434                                 {                       
1435                                         ob->Suspend();
1436                                 } else {
1437                                         ob->Resume();
1438                                 }
1439                         }
1440                 }               
1441         }
1442 }
1443
1444 void KX_Scene::SetActivityCullingRadius(float f)
1445 {
1446         if (f < 0.5)
1447                 f = 0.5;
1448         m_activity_box_radius = f;
1449 }
1450         
1451 NG_NetworkDeviceInterface* KX_Scene::GetNetworkDeviceInterface()
1452 {
1453         return m_networkDeviceInterface;
1454 }
1455
1456 NG_NetworkScene* KX_Scene::GetNetworkScene()
1457 {
1458         return m_networkScene;
1459 }
1460
1461 void KX_Scene::SetNetworkDeviceInterface(NG_NetworkDeviceInterface* newInterface)
1462 {
1463         m_networkDeviceInterface = newInterface;
1464 }
1465
1466 void KX_Scene::SetNetworkScene(NG_NetworkScene *newScene)
1467 {
1468         m_networkScene = newScene;
1469 }
1470
1471
1472 void    KX_Scene::SetGravity(const MT_Vector3& gravity)
1473 {
1474         GetPhysicsEnvironment()->setGravity(gravity[0],gravity[1],gravity[2]);
1475 }
1476
1477 void KX_Scene::SetNodeTree(SG_Tree* root)
1478 {
1479         m_objecttree = root;
1480 }
1481
1482 void KX_Scene::SetSceneConverter(class KX_BlenderSceneConverter* sceneConverter)
1483 {
1484         m_sceneConverter = sceneConverter;
1485 }
1486
1487 void KX_Scene::SetPhysicsEnvironment(class PHY_IPhysicsEnvironment* physEnv)
1488 {
1489         m_physicsEnvironment = physEnv;
1490
1491         KX_TouchEventManager* touchmgr = new KX_TouchEventManager(m_logicmgr, physEnv);
1492         m_logicmgr->RegisterEventManager(touchmgr);
1493         return;
1494 }
1495  
1496 void KX_Scene::setSuspendedTime(double suspendedtime)
1497 {
1498         m_suspendedtime = suspendedtime;
1499 }
1500 double KX_Scene::getSuspendedTime()
1501 {
1502         return m_suspendedtime;
1503 }
1504 void KX_Scene::setSuspendedDelta(double suspendeddelta)
1505 {
1506         m_suspendeddelta = suspendeddelta;
1507 }
1508 double KX_Scene::getSuspendedDelta()
1509 {
1510         return m_suspendeddelta;
1511 }
1512
1513 //----------------------------------------------------------------------------
1514 //Python
1515
1516 PyMethodDef KX_Scene::Methods[] = {
1517         KX_PYMETHODTABLE(KX_Scene, getLightList),
1518         KX_PYMETHODTABLE(KX_Scene, getObjectList),
1519         KX_PYMETHODTABLE(KX_Scene, getName),
1520         
1521         {NULL,NULL} //Sentinel
1522 };
1523
1524 PyTypeObject KX_Scene::Type = {
1525         PyObject_HEAD_INIT(&PyType_Type)
1526                 0,
1527                 "KX_Scene",
1528                 sizeof(KX_Scene),
1529                 0,
1530                 PyDestructor,
1531                 0,
1532                 __getattr,
1533                 __setattr,
1534                 0, //&MyPyCompare,
1535                 __repr,
1536                 0, //&cvalue_as_number,
1537                 0,
1538                 0,
1539                 0,
1540                 0, 0, 0, 0, 0, 0
1541 };
1542
1543 PyParentObject KX_Scene::Parents[] = {
1544         &KX_Scene::Type,
1545                 &CValue::Type,
1546                 NULL
1547 };
1548
1549 PyObject* KX_Scene::_getattr(const STR_String& attr)
1550 {
1551         if (attr == "name")
1552                 return PyString_FromString(GetName());
1553         
1554         if (attr == "active_camera")
1555         {
1556                 KX_Camera *camera = GetActiveCamera();
1557                 camera->AddRef();
1558                 return (PyObject*) camera;
1559         }
1560         
1561         if (attr == "suspended")
1562                 return PyInt_FromLong(m_suspend);
1563         
1564         if (attr == "activity_culling")
1565                 return PyInt_FromLong(m_activity_culling);
1566         
1567         if (attr == "activity_culling_radius")
1568                 return PyFloat_FromDouble(m_activity_box_radius);
1569         
1570         PyObject* value = PyDict_GetItemString(m_attrlist, const_cast<char *>(attr.ReadPtr()));
1571         if (value)
1572         {
1573                 Py_INCREF(value);
1574                 return value;
1575         }
1576         
1577         _getattr_up(PyObjectPlus);
1578 }
1579
1580 int KX_Scene::_delattr(const STR_String &attr)
1581 {
1582         PyDict_DelItemString(m_attrlist, const_cast<char *>(attr.ReadPtr()));
1583         return 0;
1584 }
1585
1586 int KX_Scene::_setattr(const STR_String &attr, PyObject *pyvalue)
1587 {
1588
1589         if (!PyDict_SetItemString(m_attrlist, const_cast<char *>(attr.ReadPtr()), pyvalue))
1590                 return 0;
1591
1592         return PyObjectPlus::_setattr(attr, pyvalue);
1593 }
1594
1595 KX_PYMETHODDEF_DOC(KX_Scene, getLightList,
1596 "getLightList() -> list [KX_Light]\n"
1597 "Returns a list of all lights in the scene.\n"
1598 )
1599 {
1600         m_lightlist->AddRef();
1601         return (PyObject*) m_lightlist;
1602 }
1603
1604 KX_PYMETHODDEF_DOC(KX_Scene, getObjectList,
1605 "getObjectList() -> list [KX_GameObject]\n"
1606 "Returns a list of all game objects in the scene.\n"
1607 )
1608 {
1609         m_objectlist->AddRef();
1610         return (PyObject*) m_objectlist;
1611 }
1612
1613 KX_PYMETHODDEF_DOC(KX_Scene, getName,
1614 "getName() -> string\n"
1615 "Returns the name of the scene.\n"
1616 )
1617 {
1618         return PyString_FromString(GetName());
1619 }