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