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