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