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