Revert last merge from trunk
[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 "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 "BKE_anim.h"
72
73 #include "KX_SG_NodeRelationships.h"
74
75 #include "KX_NetworkEventManager.h"
76 #include "NG_NetworkScene.h"
77 #include "PHY_IPhysicsEnvironment.h"
78 #include "KX_IPhysicsController.h"
79 #include "KX_BlenderSceneConverter.h"
80
81 #include "BL_ShapeDeformer.h"
82 #include "BL_DeformableGameObject.h"
83
84 // to get USE_BULLET!
85 #include "KX_ConvertPhysicsObject.h"
86
87 #ifdef USE_BULLET
88 #include "CcdPhysicsEnvironment.h"
89 #include "CcdPhysicsController.h"
90 #endif
91
92 void* KX_SceneReplicationFunc(SG_IObject* node,void* gameobj,void* scene)
93 {
94         KX_GameObject* replica = ((KX_Scene*)scene)->AddNodeReplicaObject(node,(KX_GameObject*)gameobj);
95
96         if(replica)
97                 replica->Release();
98
99         return (void*)replica;
100 }
101
102 void* KX_SceneDestructionFunc(SG_IObject* node,void* gameobj,void* scene)
103 {
104         ((KX_Scene*)scene)->RemoveNodeDestructObject(node,(KX_GameObject*)gameobj);
105
106         return NULL;
107 };
108
109 SG_Callbacks KX_Scene::m_callbacks = SG_Callbacks(KX_SceneReplicationFunc,KX_SceneDestructionFunc,KX_GameObject::UpdateTransformFunc);
110
111 // temporarily var until there is a button in the userinterface
112 // (defined in KX_PythonInit.cpp)
113 extern bool gUseVisibilityTemp;
114
115 KX_Scene::KX_Scene(class SCA_IInputDevice* keyboarddevice,
116                                    class SCA_IInputDevice* mousedevice,
117                                    class NG_NetworkDeviceInterface *ndi,
118                                    class SND_IAudioDevice* adi,
119                                    const STR_String& sceneName): 
120         PyObjectPlus(&KX_Scene::Type),
121         m_keyboardmgr(NULL),
122         m_mousemgr(NULL),
123         m_sceneConverter(NULL),
124         m_physicsEnvironment(0),
125         m_sceneName(sceneName),
126         m_adi(adi),
127         m_networkDeviceInterface(ndi),
128         m_active_camera(NULL),
129         m_ueberExecutionPriority(0)
130 {
131         m_suspendedtime = 0.0;
132         m_suspendeddelta = 0.0;
133
134         m_activity_culling = false;
135         m_suspend = false;
136         m_isclearingZbuffer = true;
137         m_tempObjectList = new CListValue();
138         m_objectlist = new CListValue();
139         m_parentlist = new CListValue();
140         m_lightlist= new CListValue();
141         m_inactivelist = new CListValue();
142         m_euthanasyobjects = new CListValue();
143         m_delayReleaseObjects = new CListValue();
144
145         m_logicmgr = new SCA_LogicManager();
146         
147         m_timemgr = new SCA_TimeEventManager(m_logicmgr);
148         m_keyboardmgr = new SCA_KeyboardManager(m_logicmgr,keyboarddevice);
149         m_mousemgr = new SCA_MouseManager(m_logicmgr,mousedevice);
150         
151         SCA_AlwaysEventManager* alwaysmgr = new SCA_AlwaysEventManager(m_logicmgr);
152         SCA_PropertyEventManager* propmgr = new SCA_PropertyEventManager(m_logicmgr);
153         SCA_ActuatorEventManager* actmgr = new SCA_ActuatorEventManager(m_logicmgr);
154         SCA_RandomEventManager* rndmgr = new SCA_RandomEventManager(m_logicmgr);
155         KX_RayEventManager* raymgr = new KX_RayEventManager(m_logicmgr);
156
157         KX_NetworkEventManager* netmgr = new KX_NetworkEventManager(m_logicmgr, ndi);
158         
159         SCA_JoystickManager *joymgr     = new SCA_JoystickManager(m_logicmgr);
160
161         m_logicmgr->RegisterEventManager(alwaysmgr);
162         m_logicmgr->RegisterEventManager(propmgr);
163         m_logicmgr->RegisterEventManager(actmgr);
164         m_logicmgr->RegisterEventManager(m_keyboardmgr);
165         m_logicmgr->RegisterEventManager(m_mousemgr);
166         m_logicmgr->RegisterEventManager(m_timemgr);
167         m_logicmgr->RegisterEventManager(rndmgr);
168         m_logicmgr->RegisterEventManager(raymgr);
169         m_logicmgr->RegisterEventManager(netmgr);
170         m_logicmgr->RegisterEventManager(joymgr);
171
172         m_soundScene = new SND_Scene(adi);
173         MT_assert (m_networkDeviceInterface != NULL);
174         m_networkScene = new NG_NetworkScene(m_networkDeviceInterface);
175         
176         m_rootnode = NULL;
177
178         m_bucketmanager=new RAS_BucketManager();
179
180         m_canvasDesignWidth = 0;
181         m_canvasDesignHeight = 0;
182         
183         m_attrlist = PyDict_New(); /* new ref */
184 }
185
186
187
188 KX_Scene::~KX_Scene()
189 {
190         // The release of debug properties used to be in SCA_IScene::~SCA_IScene
191         // It's still there but we remove all properties here otherwise some
192         // reference might be hanging and causing late release of objects
193         RemoveAllDebugProperties();
194
195         while (GetRootParentList()->GetCount() > 0) 
196         {
197                 KX_GameObject* parentobj = (KX_GameObject*) GetRootParentList()->GetValue(0);
198                 this->RemoveObject(parentobj);
199         }
200
201         if(m_objectlist)
202                 m_objectlist->Release();
203
204         if (m_parentlist)
205                 m_parentlist->Release();
206         
207         if (m_inactivelist)
208                 m_inactivelist->Release();
209
210         if (m_lightlist)
211                 m_lightlist->Release();
212         
213         if (m_tempObjectList)
214                 m_tempObjectList->Release();
215
216         if (m_euthanasyobjects)
217                 m_euthanasyobjects->Release();
218         if (m_delayReleaseObjects)
219                 m_delayReleaseObjects->Release();
220
221         if (m_logicmgr)
222                 delete m_logicmgr;
223
224         if (m_physicsEnvironment)
225                 delete m_physicsEnvironment;
226
227         if (m_soundScene)
228                 delete m_soundScene;
229
230         if (m_networkScene)
231                 delete m_networkScene;
232         
233         if (m_bucketmanager)
234         {
235                 delete m_bucketmanager;
236         }
237         //Py_DECREF(m_attrlist);
238 }
239
240 void KX_Scene::SetProjectionMatrix(MT_CmMatrix4x4& pmat)
241 {
242         m_projectionmat = pmat;
243 }
244
245
246
247 RAS_BucketManager* KX_Scene::GetBucketManager()
248 {
249         return m_bucketmanager;
250 }
251
252
253
254 CListValue* KX_Scene::GetObjectList()
255 {
256         return m_objectlist;
257 }
258
259
260
261 CListValue* KX_Scene::GetRootParentList()
262 {
263         return m_parentlist;
264 }
265
266 CListValue* KX_Scene::GetInactiveList()
267 {
268         return m_inactivelist;
269 }
270
271
272
273 CListValue* KX_Scene::GetLightList()
274 {
275         return m_lightlist;
276 }
277
278 SCA_LogicManager* KX_Scene::GetLogicManager()
279 {
280         return m_logicmgr;
281 }
282
283 SCA_TimeEventManager* KX_Scene::GetTimeEventManager()
284 {
285         return m_timemgr;
286 }
287
288
289
290  
291 list<class KX_Camera*>* KX_Scene::GetCameras()
292 {
293         return &m_cameras;
294 }
295
296
297
298 void KX_Scene::SetFramingType(RAS_FrameSettings & frame_settings)
299 {
300         m_frame_settings = frame_settings;
301 };
302
303 /**
304  * Return a const reference to the framing 
305  * type set by the above call.
306  * The contents are not guarenteed to be sensible
307  * if you don't call the above function.
308  */
309 const RAS_FrameSettings& KX_Scene::GetFramingType() const 
310 {
311         return m_frame_settings;
312 };      
313
314
315
316 /**
317  * Store the current scene's viewport on the 
318  * game engine canvas.
319  */
320 void KX_Scene::SetSceneViewport(const RAS_Rect &viewport)
321 {
322         m_viewport = viewport;
323 }
324
325
326
327 const RAS_Rect& KX_Scene::GetSceneViewport() const 
328 {
329         return m_viewport;
330 }
331
332
333
334 void KX_Scene::SetWorldInfo(class KX_WorldInfo* worldinfo)
335 {
336         m_worldinfo = worldinfo;
337 }
338
339
340
341 class KX_WorldInfo* KX_Scene::GetWorldInfo()
342 {
343         return m_worldinfo;
344 }
345
346
347
348 SND_Scene* KX_Scene::GetSoundScene()
349 {
350         return m_soundScene;
351 }
352
353 const STR_String& KX_Scene::GetName()
354 {
355         return m_sceneName;
356 }
357
358
359 void KX_Scene::Suspend()
360 {
361         m_suspend = true;
362 }
363
364 void KX_Scene::Resume()
365 {
366         m_suspend = false;
367 }
368
369 void KX_Scene::SetActivityCulling(bool b)
370 {
371         m_activity_culling = b;
372 }
373
374 bool KX_Scene::IsSuspended()
375 {
376         return m_suspend;
377 }
378
379 bool KX_Scene::IsClearingZBuffer()
380 {
381         return m_isclearingZbuffer;
382 }
383
384 void KX_Scene::EnableZBufferClearing(bool isclearingZbuffer)
385 {
386         m_isclearingZbuffer = isclearingZbuffer;
387 }
388
389 void KX_Scene::RemoveNodeDestructObject(class SG_IObject* node,class CValue* gameobj)
390 {
391         KX_GameObject* orgobj = (KX_GameObject*)gameobj;        
392         if (NewRemoveObject(orgobj) != 0)
393         {
394                 // object is not yet deleted (this can happen when it hangs in an add object actuator
395                 // last object created reference. It's a bad situation, don't know how to fix it exactly
396                 // The least I can do, is remove the reference to the node in the object as the node
397                 // will in any case be deleted. This ensures that the object will not try to use the node
398                 // when it is finally deleted (see KX_GameObject destructor)
399                 orgobj->SetSGNode(NULL);
400         }
401         if (node)
402                 delete node;
403 }
404
405 KX_GameObject* KX_Scene::AddNodeReplicaObject(class SG_IObject* node, class CValue* gameobj)
406 {
407         // for group duplication, limit the duplication of the hierarchy to the
408         // objects that are part of the group. 
409         if (!IsObjectInGroup(gameobj))
410                 return NULL;
411         
412         KX_GameObject* orgobj = (KX_GameObject*)gameobj;
413         KX_GameObject* newobj = (KX_GameObject*)orgobj->GetReplica();
414         m_map_gameobject_to_replica.insert(orgobj, newobj);
415
416         // also register 'timers' (time properties) of the replica
417         int numprops = newobj->GetPropertyCount();
418
419         for (int i = 0; i < numprops; i++)
420         {
421                 CValue* prop = newobj->GetProperty(i);
422
423                 if (prop->GetProperty("timer"))
424                         this->m_timemgr->AddTimeProperty(prop);
425         }
426
427         if (node)
428         {
429                 newobj->SetSGNode((SG_Node*)node);
430         }
431         else
432         {
433                 m_rootnode = new SG_Node(newobj,this,KX_Scene::m_callbacks);
434         
435                 // this fixes part of the scaling-added object bug
436                 SG_Node* orgnode = orgobj->GetSGNode();
437                 m_rootnode->SetLocalScale(orgnode->GetLocalScale());
438                 m_rootnode->SetLocalPosition(orgnode->GetLocalPosition());
439                 m_rootnode->SetLocalOrientation(orgnode->GetLocalOrientation());
440
441                 // define the relationship between this node and it's parent.
442                 KX_NormalParentRelation * parent_relation = 
443                         KX_NormalParentRelation::New();
444                 m_rootnode->SetParentRelation(parent_relation);
445
446                 newobj->SetSGNode(m_rootnode);
447         }
448         
449         SG_IObject* replicanode = newobj->GetSGNode();
450 //      SG_Node* rootnode = (replicanode == m_rootnode ? NULL : m_rootnode);
451
452         replicanode->SetSGClientObject(newobj);
453
454         // this is the list of object that are send to the graphics pipeline
455         m_objectlist->Add(newobj->AddRef());
456         newobj->Bucketize();
457
458         // logic cannot be replicated, until the whole hierarchy is replicated.
459         m_logicHierarchicalGameObjects.push_back(newobj);
460         //replicate controllers of this node
461         SGControllerList        scenegraphcontrollers = orgobj->GetSGNode()->GetSGControllerList();
462         replicanode->RemoveAllControllers();
463         SGControllerList::iterator cit;
464         //int numcont = scenegraphcontrollers.size();
465         
466         for (cit = scenegraphcontrollers.begin();!(cit==scenegraphcontrollers.end());++cit)
467         {
468                 // controller replication is quite complicated
469                 // only replicate ipo and physics controller for now
470
471                 SG_Controller* replicacontroller = (*cit)->GetReplica((SG_Node*) replicanode);
472                 if (replicacontroller)
473                 {
474                         replicacontroller->SetObject(replicanode);
475                         replicanode->AddSGController(replicacontroller);
476                 }
477         }
478         
479         return newobj;
480 }
481
482
483
484 // before calling this method KX_Scene::ReplicateLogic(), make sure to
485 // have called 'GameObject::ReParentLogic' for each object this
486 // hierarchy that's because first ALL bricks must exist in the new
487 // replica of the hierarchy in order to make cross-links work properly
488 // !
489 // It is VERY important that the order of sensors and actuators in
490 // the replicated object is preserved: it is is used to reconnect the logic.
491 // This method is more robust then using the bricks name in case of complex 
492 // group replication. The replication of logic bricks is done in 
493 // SCA_IObject::ReParentLogic(), make sure it preserves the order of the bricks.
494 void KX_Scene::ReplicateLogic(KX_GameObject* newobj)
495 {
496         // also relink the controller to sensors/actuators
497         SCA_ControllerList& controllers = newobj->GetControllers();
498         //SCA_SensorList&     sensors     = newobj->GetSensors();
499         //SCA_ActuatorList&   actuators   = newobj->GetActuators();
500
501         for (SCA_ControllerList::iterator itc = controllers.begin(); !(itc==controllers.end());itc++)
502         {
503                 SCA_IController* cont = (*itc);
504                 cont->SetUeberExecutePriority(m_ueberExecutionPriority);
505                 vector<SCA_ISensor*> linkedsensors = cont->GetLinkedSensors();
506                 vector<SCA_IActuator*> linkedactuators = cont->GetLinkedActuators();
507
508                 // disconnect the sensors and actuators
509                 cont->UnlinkAllSensors();
510                 cont->UnlinkAllActuators();
511                 
512                 // now relink each sensor
513                 for (vector<SCA_ISensor*>::iterator its = linkedsensors.begin();!(its==linkedsensors.end());its++)
514                 {
515                         SCA_ISensor* oldsensor = (*its);
516                         SCA_IObject* oldsensorobj = oldsensor->GetParent();
517                         SCA_IObject* newsensorobj = NULL;
518                 
519                         // the original owner of the sensor has been replicated?
520                         void **h_obj = m_map_gameobject_to_replica[oldsensorobj];
521                         if (h_obj)
522                                 newsensorobj = (SCA_IObject*)(*h_obj);
523                         if (!newsensorobj)
524                         {
525                                 // no, then the sensor points outside the hierachy, keep it the same
526                                 if (m_objectlist->SearchValue(oldsensorobj))
527                                         // only replicate links that points to active objects
528                                         m_logicmgr->RegisterToSensor(cont,oldsensor);
529                         }
530                         else
531                         {
532                                 // yes, then the new sensor has the same position
533                                 SCA_SensorList& sensorlist = oldsensorobj->GetSensors();
534                                 SCA_SensorList::iterator sit;
535                                 SCA_ISensor* newsensor = NULL;
536                                 int sensorpos;
537
538                                 for (sensorpos=0, sit=sensorlist.begin(); sit!=sensorlist.end(); sit++, sensorpos++)
539                                 {
540                                         if ((*sit) == oldsensor) 
541                                         {
542                                                 newsensor = newsensorobj->GetSensors().at(sensorpos);
543                                                 break;
544                                         }
545                                 }
546                                 assert(newsensor != NULL);
547                                 m_logicmgr->RegisterToSensor(cont,newsensor);
548                         }
549                 }
550                 
551                 // now relink each actuator
552                 for (vector<SCA_IActuator*>::iterator ita = linkedactuators.begin();!(ita==linkedactuators.end());ita++)
553                 {
554                         SCA_IActuator* oldactuator = (*ita);
555                         SCA_IObject* oldactuatorobj = oldactuator->GetParent();
556                         SCA_IObject* newactuatorobj = NULL;
557
558                         // the original owner of the sensor has been replicated?
559                         void **h_obj = m_map_gameobject_to_replica[oldactuatorobj];
560                         if (h_obj)
561                                 newactuatorobj = (SCA_IObject*)(*h_obj);
562
563                         if (!newactuatorobj)
564                         {
565                                 // no, then the sensor points outside the hierachy, keep it the same
566                                 if (m_objectlist->SearchValue(oldactuatorobj))
567                                         // only replicate links that points to active objects
568                                         m_logicmgr->RegisterToActuator(cont,oldactuator);
569                         }
570                         else
571                         {
572                                 // yes, then the new sensor has the same position
573                                 SCA_ActuatorList& actuatorlist = oldactuatorobj->GetActuators();
574                                 SCA_ActuatorList::iterator ait;
575                                 SCA_IActuator* newactuator = NULL;
576                                 int actuatorpos;
577
578                                 for (actuatorpos=0, ait=actuatorlist.begin(); ait!=actuatorlist.end(); ait++, actuatorpos++)
579                                 {
580                                         if ((*ait) == oldactuator) 
581                                         {
582                                                 newactuator = newactuatorobj->GetActuators().at(actuatorpos);
583                                                 break;
584                                         }
585                                 }
586                                 assert(newactuator != NULL);
587                                 m_logicmgr->RegisterToActuator(cont,newactuator);
588                                 newactuator->SetUeberExecutePriority(m_ueberExecutionPriority);
589                         }
590                 }
591         }
592         // ready to set initial state
593         newobj->ResetState();
594 }
595
596 void KX_Scene::DupliGroupRecurse(CValue* obj, int level)
597 {
598         KX_GameObject* groupobj = (KX_GameObject*) obj;
599         KX_GameObject* replica;
600         KX_GameObject* gameobj;
601         Object* blgroupobj = groupobj->GetBlenderObject();
602         Group* group;
603         GroupObject *go;
604         vector<KX_GameObject*> duplilist;
605
606         if (!groupobj->IsDupliGroup() ||
607                 level>MAX_DUPLI_RECUR)
608                 return;
609
610         // we will add one group at a time
611         m_logicHierarchicalGameObjects.clear();
612         m_map_gameobject_to_replica.clear();
613         m_ueberExecutionPriority++;
614         // for groups will do something special: 
615         // we will force the creation of objects to those in the group only
616         // Again, this is match what Blender is doing (it doesn't care of parent relationship)
617         m_groupGameObjects.clear();
618
619         group = blgroupobj->dup_group;
620         for(go=(GroupObject*)group->gobject.first; go; go=(GroupObject*)go->next) 
621         {
622                 Object* blenderobj = go->ob;
623                 if (blgroupobj == blenderobj)
624                         // this check is also in group_duplilist()
625                         continue;
626                 gameobj = (KX_GameObject*)m_logicmgr->FindGameObjByBlendObj(blenderobj);
627                 if (gameobj == NULL) 
628                 {
629                         // this object has not been converted!!!
630                         // Should not happen as dupli group are created automatically 
631                         continue;
632                 }
633                 if ((blenderobj->lay & group->layer)==0)
634                 {
635                         // object is not visible in the 3D view, will not be instantiated
636                         continue;
637                 }
638                 m_groupGameObjects.insert(gameobj);
639         }
640
641         set<CValue*>::iterator oit;
642         for (oit=m_groupGameObjects.begin(); oit != m_groupGameObjects.end(); oit++)
643         {
644                 gameobj = (KX_GameObject*)(*oit);
645
646                 KX_GameObject *parent = gameobj->GetParent();
647                 if (parent != NULL)
648                 {
649                         parent->Release(); // GetParent() increased the refcount
650
651                         // this object is not a top parent. Either it is the child of another
652                         // object in the group and it will be added automatically when the parent
653                         // is added. Or it is the child of an object outside the group and the group
654                         // is inconsistent, skip it anyway
655                         continue;
656                 }
657                 replica = (KX_GameObject*) AddNodeReplicaObject(NULL,gameobj);
658                 // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame)
659                 m_parentlist->Add(replica->AddRef());
660
661                 // recurse replication into children nodes
662                 NodeList& children = gameobj->GetSGNode()->GetSGChildren();
663
664                 replica->GetSGNode()->ClearSGChildren();
665                 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
666                 {
667                         SG_Node* orgnode = (*childit);
668                         SG_Node* childreplicanode = orgnode->GetSGReplica();
669                         if (childreplicanode)
670                                 replica->GetSGNode()->AddChild(childreplicanode);
671                 }
672                 // don't replicate logic now: we assume that the objects in the group can have
673                 // logic relationship, even outside parent relationship
674                 // In order to match 3D view, the position of groupobj is used as a 
675                 // transformation matrix instead of the new position. This means that 
676                 // the group reference point is 0,0,0
677
678                 // get the rootnode's scale
679                 MT_Vector3 newscale = groupobj->NodeGetWorldScaling();
680                 // set the replica's relative scale with the rootnode's scale
681                 replica->NodeSetRelativeScale(newscale);
682
683                 MT_Matrix3x3 newori = groupobj->NodeGetWorldOrientation() * gameobj->NodeGetWorldOrientation();
684                 replica->NodeSetLocalOrientation(newori);
685
686                 MT_Point3 newpos = groupobj->NodeGetWorldPosition() + 
687                         newscale*(groupobj->NodeGetWorldOrientation() * gameobj->NodeGetWorldPosition());
688                 replica->NodeSetLocalPosition(newpos);
689
690                 if (replica->GetPhysicsController())
691                 {
692                         // not required, already done in NodeSetLocalOrientation..
693                         //replica->GetPhysicsController()->setPosition(newpos);
694                         //replica->GetPhysicsController()->setOrientation(newori.getRotation());
695                         // Scaling has been set relatively hereabove, this does not 
696                         // set the scaling of the controller. I don't know why it's just the
697                         // relative scale and not the full scale that has to be put here...
698                         replica->GetPhysicsController()->setScaling(newscale);
699                 }
700
701                 replica->GetSGNode()->UpdateWorldData(0);
702                 replica->GetSGNode()->SetBBox(gameobj->GetSGNode()->BBox());
703                 replica->GetSGNode()->SetRadius(gameobj->GetSGNode()->Radius());
704                 // done with replica
705                 replica->Release();
706         }
707
708         // the logic must be replicated first because we need
709         // the new logic bricks before relinking
710         vector<KX_GameObject*>::iterator git;
711         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
712         {
713                 (*git)->ReParentLogic();
714         }
715         
716         //      relink any pointers as necessary, sort of a temporary solution
717         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
718         {
719                 // this will also relink the actuator to objects within the hierarchy
720                 (*git)->Relink(&m_map_gameobject_to_replica);
721                 // add the object in the layer of the parent
722                 (*git)->SetLayer(groupobj->GetLayer());
723         }
724
725         // replicate crosslinks etc. between logic bricks
726         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
727         {
728                 ReplicateLogic((*git));
729         }
730         
731         // now look if object in the hierarchy have dupli group and recurse
732         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
733         {
734                 if ((*git) != groupobj && (*git)->IsDupliGroup())
735                         // can't instantiate group immediately as it destroys m_logicHierarchicalGameObjects
736                         duplilist.push_back((*git));
737         }
738
739         for (git = duplilist.begin(); !(git == duplilist.end()); ++git)
740         {
741                 DupliGroupRecurse((*git), level+1);
742         }
743 }
744
745
746 SCA_IObject* KX_Scene::AddReplicaObject(class CValue* originalobject,
747                                                                                 class CValue* parentobject,
748                                                                                 int lifespan)
749 {
750
751         m_logicHierarchicalGameObjects.clear();
752         m_map_gameobject_to_replica.clear();
753         m_groupGameObjects.clear();
754
755         // todo: place a timebomb in the object, for temporarily objects :)
756         // lifespan of zero means 'this object lives forever'
757         KX_GameObject* originalobj = (KX_GameObject*) originalobject;
758         KX_GameObject* parentobj = (KX_GameObject*) parentobject;
759
760         m_ueberExecutionPriority++;
761
762         // lets create a replica
763         KX_GameObject* replica = (KX_GameObject*) AddNodeReplicaObject(NULL,originalobj);
764
765         if (lifespan > 0)
766         {
767                 // add a timebomb to this object
768                 // for now, convert between so called frames and realtime
769                 m_tempObjectList->Add(replica->AddRef());
770                 CValue *fval = new CFloatValue(lifespan*0.02);
771                 replica->SetProperty("::timebomb",fval);
772                 fval->Release();
773         }
774
775         // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame)
776         m_parentlist->Add(replica->AddRef());
777
778         // recurse replication into children nodes
779
780         NodeList& children = originalobj->GetSGNode()->GetSGChildren();
781
782         replica->GetSGNode()->ClearSGChildren();
783         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
784         {
785                 SG_Node* orgnode = (*childit);
786                 SG_Node* childreplicanode = orgnode->GetSGReplica();
787                 if (childreplicanode)
788                         replica->GetSGNode()->AddChild(childreplicanode);
789         }
790
791         // now replicate logic
792         vector<KX_GameObject*>::iterator git;
793         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
794         {
795                 (*git)->ReParentLogic();
796         }
797         
798         //      relink any pointers as necessary, sort of a temporary solution
799         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
800         {
801                 // this will also relink the actuators in the hierarchy
802                 (*git)->Relink(&m_map_gameobject_to_replica);
803                 // add the object in the layer of the parent
804                 (*git)->SetLayer(parentobj->GetLayer());
805         }
806
807         // replicate crosslinks etc. between logic bricks
808         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
809         {
810                 ReplicateLogic((*git));
811         }
812         
813         MT_Point3 newpos = ((KX_GameObject*) parentobject)->NodeGetWorldPosition();
814         replica->NodeSetLocalPosition(newpos);
815
816         MT_Matrix3x3 newori = ((KX_GameObject*) parentobject)->NodeGetWorldOrientation();
817         replica->NodeSetLocalOrientation(newori);
818         
819         // get the rootnode's scale
820         MT_Vector3 newscale = parentobj->GetSGNode()->GetRootSGParent()->GetLocalScale();
821
822         // set the replica's relative scale with the rootnode's scale
823         replica->NodeSetRelativeScale(newscale);
824
825         if (replica->GetPhysicsController())
826         {
827                 // not needed, already done in NodeSetLocalPosition()
828                 //replica->GetPhysicsController()->setPosition(newpos);
829                 //replica->GetPhysicsController()->setOrientation(newori.getRotation());
830                 replica->GetPhysicsController()->setScaling(newscale);
831         }
832
833         // here we want to set the relative scale: the rootnode's scale will override all other
834         // scalings, so lets better prepare for it
835
836
837         replica->GetSGNode()->UpdateWorldData(0);
838         replica->GetSGNode()->SetBBox(originalobj->GetSGNode()->BBox());
839         replica->GetSGNode()->SetRadius(originalobj->GetSGNode()->Radius());
840         // check if there are objects with dupligroup in the hierarchy
841         vector<KX_GameObject*> duplilist;
842         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
843         {
844                 if ((*git)->IsDupliGroup())
845                 {
846                         // separate list as m_logicHierarchicalGameObjects is also used by DupliGroupRecurse()
847                         duplilist.push_back(*git);
848                 }
849         }
850         for (git = duplilist.begin();!(git==duplilist.end());++git)
851         {
852                 DupliGroupRecurse(*git, 0);
853         }
854         //      don't release replica here because we are returning it, not done with it...
855         return replica;
856 }
857
858
859
860 void KX_Scene::RemoveObject(class CValue* gameobj)
861 {
862         KX_GameObject* newobj = (KX_GameObject*) gameobj;
863
864         // first disconnect child from parent
865         SG_Node* node = newobj->GetSGNode();
866
867         if (node)
868         {
869                 node->DisconnectFromParent();
870
871                 // recursively destruct
872                 node->Destruct();
873         }
874         //no need to do that: the object is destroyed and memory released 
875         //newobj->SetSGNode(0);
876 }
877
878 void KX_Scene::DelayedReleaseObject(CValue* gameobj)
879 {
880         m_delayReleaseObjects->Add(gameobj->AddRef());
881 }
882
883
884 void KX_Scene::DelayedRemoveObject(class CValue* gameobj)
885 {
886         //KX_GameObject* newobj = (KX_GameObject*) gameobj;
887         if (!m_euthanasyobjects->SearchValue(gameobj))
888         {
889                 m_euthanasyobjects->Add(gameobj->AddRef());
890         } 
891 }
892
893
894
895 int KX_Scene::NewRemoveObject(class CValue* gameobj)
896 {
897         int ret;
898         KX_GameObject* newobj = (KX_GameObject*) gameobj;
899
900         // keep the blender->game object association up to date
901         // note that all the replicas of an object will have the same
902         // blender object, that's why we need to check the game object
903         // as only the deletion of the original object must be recorded
904         m_logicmgr->UnregisterGameObj(newobj->GetBlenderObject(), gameobj);
905
906         //todo: look at this
907         //GetPhysicsEnvironment()->RemovePhysicsController(gameobj->getPhysicsController());
908
909         // remove all sensors/controllers/actuators from logicsystem...
910         
911         SCA_SensorList& sensors = newobj->GetSensors();
912         for (SCA_SensorList::iterator its = sensors.begin();
913                  !(its==sensors.end());its++)
914         {
915                 m_logicmgr->RemoveSensor(*its);
916         }
917         
918     SCA_ControllerList& controllers = newobj->GetControllers();
919         for (SCA_ControllerList::iterator itc = controllers.begin();
920                  !(itc==controllers.end());itc++)
921         {
922                 m_logicmgr->RemoveController(*itc);
923         }
924
925         SCA_ActuatorList& actuators = newobj->GetActuators();
926         for (SCA_ActuatorList::iterator ita = actuators.begin();
927                  !(ita==actuators.end());ita++)
928         {
929                 m_logicmgr->RemoveDestroyedActuator(*ita);
930         }
931         // the sensors/controllers/actuators must also be released, this is done in ~SCA_IObject
932
933         // now remove the timer properties from the time manager
934         int numprops = newobj->GetPropertyCount();
935
936         for (int i = 0; i < numprops; i++)
937         {
938                 CValue* propval = newobj->GetProperty(i);
939                 if (propval->GetProperty("timer"))
940                 {
941                         m_timemgr->RemoveTimeProperty(propval);
942                 }
943         }
944         
945         newobj->RemoveMeshes();
946         ret = 1;
947         if (m_objectlist->RemoveValue(newobj))
948                 ret = newobj->Release();
949         if (m_tempObjectList->RemoveValue(newobj))
950                 ret = newobj->Release();
951         if (m_parentlist->RemoveValue(newobj))
952                 ret = newobj->Release();
953         if (m_inactivelist->RemoveValue(newobj))
954                 ret = newobj->Release();
955         if (m_euthanasyobjects->RemoveValue(newobj))
956                 ret = newobj->Release();
957                 
958         if (newobj == m_active_camera)
959         {
960                 //no AddRef done on m_active_camera so no Release
961                 //m_active_camera->Release();
962                 m_active_camera = NULL;
963         }
964
965         // in case this is a camera
966         m_cameras.remove((KX_Camera*)newobj);
967
968         if (m_sceneConverter)
969                 m_sceneConverter->UnregisterGameObject(newobj);
970         // return value will be 0 if the object is actually deleted (all reference gone)
971         return ret;
972 }
973
974
975
976 void KX_Scene::ReplaceMesh(class CValue* obj,void* meshobj)
977 {
978         KX_GameObject* gameobj = static_cast<KX_GameObject*>(obj);
979         RAS_MeshObject* mesh = static_cast<RAS_MeshObject*>(meshobj);
980
981         if(!gameobj || !mesh)
982         {
983                 std::cout << "warning: invalid object, mesh will not be replaced" << std::endl;
984                 return;
985         }
986
987         gameobj->RemoveMeshes();
988         gameobj->AddMesh(mesh);
989         
990         if (gameobj->m_isDeformable)
991         {
992                 BL_DeformableGameObject* newobj = static_cast<BL_DeformableGameObject*>( gameobj );
993                 
994                 if (newobj->m_pDeformer)
995                 {
996                         delete newobj->m_pDeformer;
997                         newobj->m_pDeformer = NULL;
998                 }
999
1000                 if (mesh->m_class == 1) 
1001                 {
1002                         // we must create a new deformer but which one?
1003                         KX_GameObject* parentobj = newobj->GetParent();
1004                         // this always return the original game object (also for replicate)
1005                         Object* blendobj = newobj->GetBlenderObject();
1006                         // object that owns the new mesh
1007                         Object* oldblendobj = static_cast<struct Object*>(m_logicmgr->FindBlendObjByGameMeshName(mesh->GetName()));
1008                         Mesh* blendmesh = mesh->GetMesh();
1009
1010                         bool bHasShapeKey = blendmesh->key != NULL && blendmesh->key->type==KEY_RELATIVE;
1011                         bool bHasDvert = blendmesh->dvert != NULL;
1012                         bool bHasArmature = 
1013                                 parentobj &&                                                            // current parent is armature
1014                                 parentobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE &&
1015                                 oldblendobj &&                                                          // needed for mesh deform
1016                                 blendobj->parent &&                                                     // original object had armature (not sure this test is needed)
1017                                 blendobj->parent->type == OB_ARMATURE && 
1018                                 blendobj->partype==PARSKEL && 
1019                                 blendmesh->dvert!=NULL;                                         // mesh has vertex group
1020                         bool releaseParent = true;
1021
1022                         if (bHasShapeKey)
1023                         {
1024                                 BL_ShapeDeformer* shapeDeformer;
1025                                 if (bHasArmature) 
1026                                 {
1027                                         shapeDeformer = new BL_ShapeDeformer(
1028                                                 newobj,
1029                                                 oldblendobj, blendobj,
1030                                                 static_cast<BL_SkinMeshObject*>(mesh),
1031                                                 true,
1032                                                 static_cast<BL_ArmatureObject*>( parentobj )
1033                                         );
1034                                         releaseParent= false;
1035                                         shapeDeformer->LoadShapeDrivers(blendobj->parent);
1036                                 }
1037                                 else
1038                                 {
1039                                         shapeDeformer = new BL_ShapeDeformer(
1040                                                 newobj,
1041                                                 oldblendobj, blendobj,
1042                                                 static_cast<BL_SkinMeshObject*>(mesh),
1043                                                 false,
1044                                                 NULL
1045                                         );
1046                                 }
1047                                 newobj->m_pDeformer = shapeDeformer;
1048                         }
1049                         else if (bHasArmature) 
1050                         {
1051                                 BL_SkinDeformer* skinDeformer = new BL_SkinDeformer(
1052                                         newobj,
1053                                         oldblendobj, blendobj,
1054                                         static_cast<BL_SkinMeshObject*>(mesh),
1055                                         true,
1056                                         static_cast<BL_ArmatureObject*>( parentobj )
1057                                 );
1058                                 releaseParent= false;
1059                                 newobj->m_pDeformer = skinDeformer;
1060                         }
1061                         else if (bHasDvert)
1062                         {
1063                                 BL_MeshDeformer* meshdeformer = new BL_MeshDeformer(
1064                                         newobj, oldblendobj, static_cast<BL_SkinMeshObject*>(mesh)
1065                                 );
1066                                 newobj->m_pDeformer = meshdeformer;
1067                         }
1068
1069                         // release parent reference if its not being used 
1070                         if( releaseParent && parentobj)
1071                                 parentobj->Release();
1072                 }
1073         }
1074         gameobj->Bucketize();
1075 }
1076
1077
1078
1079 MT_CmMatrix4x4& KX_Scene::GetViewMatrix()
1080 {
1081         MT_Scalar cammat[16];
1082         m_active_camera->GetWorldToCamera().getValue(cammat);
1083         m_viewmat = cammat;
1084         return m_viewmat;
1085 }
1086
1087
1088
1089 MT_CmMatrix4x4& KX_Scene::GetProjectionMatrix()
1090 {
1091         return m_projectionmat;
1092 }
1093
1094
1095 KX_Camera* KX_Scene::FindCamera(KX_Camera* cam)
1096 {
1097         list<KX_Camera*>::iterator it = m_cameras.begin();
1098
1099         while ( (it != m_cameras.end()) 
1100                         && ((*it) != cam) ) {
1101           it++;
1102         }
1103
1104         return ((it == m_cameras.end()) ? NULL : (*it));
1105 }
1106
1107
1108 KX_Camera* KX_Scene::FindCamera(STR_String& name)
1109 {
1110         list<KX_Camera*>::iterator it = m_cameras.begin();
1111
1112         while ( (it != m_cameras.end()) 
1113                         && ((*it)->GetName() != name) ) {
1114           it++;
1115         }
1116
1117         return ((it == m_cameras.end()) ? NULL : (*it));
1118 }
1119
1120 void KX_Scene::AddCamera(KX_Camera* cam)
1121 {
1122         if (!FindCamera(cam))
1123                 m_cameras.push_back(cam);
1124 }
1125
1126
1127 KX_Camera* KX_Scene::GetActiveCamera()
1128 {       
1129         // NULL if not defined
1130         return m_active_camera;
1131 }
1132
1133
1134 void KX_Scene::SetActiveCamera(KX_Camera* cam)
1135 {
1136         // only set if the cam is in the active list? Or add it otherwise?
1137         if (!FindCamera(cam)){
1138                 AddCamera(cam);
1139                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
1140         } 
1141
1142         m_active_camera = cam;
1143 }
1144
1145 void KX_Scene::SetCameraOnTop(KX_Camera* cam)
1146 {
1147         if (!FindCamera(cam)){
1148                 // adding is always done at the back, so that's all that needs to be done
1149                 AddCamera(cam);
1150                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
1151         } else {
1152                 m_cameras.remove(cam);
1153                 m_cameras.push_back(cam);
1154         }
1155 }
1156
1157
1158 void KX_Scene::UpdateMeshTransformations()
1159 {
1160         // do this incrementally in the future
1161         for (int i = 0; i < m_objectlist->GetCount(); i++)
1162         {
1163                 KX_GameObject* gameobj = (KX_GameObject*)m_objectlist->GetValue(i);
1164                 gameobj->GetOpenGLMatrix();
1165 //              gameobj->UpdateNonDynas();
1166         }
1167 }
1168
1169 void KX_Scene::MarkVisible(SG_Tree *node, RAS_IRasterizer* rasty, KX_Camera* cam, int layer)
1170 {
1171         int intersect = KX_Camera::INTERSECT;
1172         KX_GameObject *gameobj = node->Client()?(KX_GameObject*) node->Client()->GetSGClientObject():NULL;
1173         bool visible = (gameobj && gameobj->GetVisible() && (!layer || (gameobj->GetLayer() & layer)));
1174         bool dotest = visible || node->Left() || node->Right();
1175
1176         /* If the camera is inside the box, assume intersect. */
1177         if (dotest && !node->inside( cam->NodeGetWorldPosition()))
1178         {
1179                 MT_Scalar radius = node->Radius();
1180                 MT_Point3 center = node->Center();
1181                 
1182                 intersect =  cam->SphereInsideFrustum(center, radius); 
1183                 
1184                 if (intersect == KX_Camera::INTERSECT)
1185                 {
1186                         MT_Point3 box[8];
1187                         node->get(box);
1188                         intersect = cam->BoxInsideFrustum(box);
1189                 }
1190         }
1191
1192         switch (intersect)
1193         {
1194                 case KX_Camera::OUTSIDE:
1195                         MarkSubTreeVisible(node, rasty, false, cam);
1196                         break;
1197                 case KX_Camera::INTERSECT:
1198                         if (gameobj)
1199                                 MarkVisible(rasty, gameobj, cam, layer);
1200                         if (node->Left())
1201                                 MarkVisible(node->Left(), rasty, cam, layer);
1202                         if (node->Right())
1203                                 MarkVisible(node->Right(), rasty, cam, layer);
1204                         break;
1205                 case KX_Camera::INSIDE:
1206                         MarkSubTreeVisible(node, rasty, true, cam, layer);
1207                         break;
1208         }
1209 }
1210
1211 void KX_Scene::MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool visible, KX_Camera* cam, int layer)
1212 {
1213         if (node->Client())
1214         {
1215                 KX_GameObject *gameobj = (KX_GameObject*) node->Client()->GetSGClientObject();
1216                 if (gameobj->GetVisible())
1217                 {
1218                         if (visible)
1219                         {
1220                                 int nummeshes = gameobj->GetMeshCount();
1221                                 
1222                                 // this adds the vertices to the display list
1223                                 for (int m=0;m<nummeshes;m++)
1224                                         (gameobj->GetMesh(m))->SchedulePolygons(rasty->GetDrawingMode());
1225                         }
1226                         gameobj->MarkVisible(visible);
1227                 }
1228         }
1229         if (node->Left())
1230                 MarkSubTreeVisible(node->Left(), rasty, visible, cam, layer);
1231         if (node->Right())
1232                 MarkSubTreeVisible(node->Right(), rasty, visible, cam, layer);
1233 }
1234
1235 void KX_Scene::MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj,KX_Camera*  cam,int layer)
1236 {
1237         // User (Python/Actuator) has forced object invisible...
1238         if (!gameobj->GetVisible())
1239                 return;
1240         
1241         // Shadow lamp layers
1242         if(layer && !(gameobj->GetLayer() & layer)) {
1243                 gameobj->MarkVisible(false);
1244                 return;
1245         }
1246
1247         // If Frustum culling is off, the object is always visible.
1248         bool vis = !cam->GetFrustumCulling();
1249         
1250         // If the camera is inside this node, then the object is visible.
1251         if (!vis)
1252         {
1253                 vis = gameobj->GetSGNode()->inside( GetActiveCamera()->GetCameraLocation() );
1254         }
1255                 
1256         // Test the object's bound sphere against the view frustum.
1257         if (!vis)
1258         {
1259                 MT_Vector3 scale = gameobj->GetSGNode()->GetWorldScaling();
1260                 MT_Scalar radius = fabs(scale[scale.closestAxis()] * gameobj->GetSGNode()->Radius());
1261                 switch (cam->SphereInsideFrustum(gameobj->NodeGetWorldPosition(), radius))
1262                 {
1263                         case KX_Camera::INSIDE:
1264                                 vis = true;
1265                                 break;
1266                         case KX_Camera::OUTSIDE:
1267                                 vis = false;
1268                                 break;
1269                         case KX_Camera::INTERSECT:
1270                                 // Test the object's bound box against the view frustum.
1271                                 MT_Point3 box[8];
1272                                 gameobj->GetSGNode()->getBBox(box); 
1273                                 vis = cam->BoxInsideFrustum(box) != KX_Camera::OUTSIDE;
1274                                 break;
1275                 }
1276         }
1277         
1278         if (vis)
1279         {
1280                 int nummeshes = gameobj->GetMeshCount();
1281                 
1282                 for (int m=0;m<nummeshes;m++)
1283                 {
1284                         // this adds the vertices to the display list
1285                         (gameobj->GetMesh(m))->SchedulePolygons(rasty->GetDrawingMode());
1286                 }
1287                 // Visibility/ non-visibility are marked
1288                 // elsewhere now.
1289                 gameobj->MarkVisible();
1290         } else {
1291                 gameobj->MarkVisible(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 }