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