synched with trunk at revision 36569
[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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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 /** \file gameengine/Ketsji/KX_Scene.cpp
32  *  \ingroup ketsji
33  */
34
35
36 #if defined(WIN32) && !defined(FREE_WINDOWS)
37 #pragma warning (disable : 4786)
38 #endif //WIN32
39
40 #include "KX_Scene.h"
41 #include "KX_PythonInit.h"
42 #include "MT_assert.h"
43 #include "KX_KetsjiEngine.h"
44 #include "KX_BlenderMaterial.h"
45 #include "RAS_IPolygonMaterial.h"
46 #include "ListValue.h"
47 #include "SCA_LogicManager.h"
48 #include "SCA_TimeEventManager.h"
49 //#include "SCA_AlwaysEventManager.h"
50 //#include "SCA_RandomEventManager.h"
51 //#include "KX_RayEventManager.h"
52 #include "KX_TouchEventManager.h"
53 #include "SCA_KeyboardManager.h"
54 #include "SCA_MouseManager.h"
55 //#include "SCA_PropertyEventManager.h"
56 #include "SCA_ActuatorEventManager.h"
57 #include "SCA_BasicEventManager.h"
58 #include "KX_Camera.h"
59 #include "SCA_JoystickManager.h"
60
61 #include "RAS_MeshObject.h"
62
63 #include "RAS_IRasterizer.h"
64 #include "RAS_BucketManager.h"
65
66 #include "FloatValue.h"
67 #include "SCA_IController.h"
68 #include "SCA_IActuator.h"
69 #include "SG_Node.h"
70 #include "BL_System.h"
71 #include "SG_Controller.h"
72 #include "SG_IObject.h"
73 #include "SG_Tree.h"
74 #include "DNA_group_types.h"
75 #include "DNA_scene_types.h"
76
77 #include "KX_SG_NodeRelationships.h"
78
79 #include "KX_NetworkEventManager.h"
80 #include "NG_NetworkScene.h"
81 #include "PHY_IPhysicsEnvironment.h"
82 #include "KX_IPhysicsController.h"
83 #include "PHY_IGraphicController.h"
84 #include "KX_BlenderSceneConverter.h"
85 #include "KX_MotionState.h"
86
87 #include "BL_ModifierDeformer.h"
88 #include "BL_ShapeDeformer.h"
89 #include "BL_DeformableGameObject.h"
90 #include "KX_ObstacleSimulation.h"
91
92 #ifdef USE_BULLET
93 #include "KX_SoftBodyDeformer.h"
94 #include "KX_ConvertPhysicsObject.h"
95 #include "CcdPhysicsEnvironment.h"
96 #include "CcdPhysicsController.h"
97 #endif
98
99 #include "KX_Light.h"
100
101 #include <stdio.h>
102
103 void* KX_SceneReplicationFunc(SG_IObject* node,void* gameobj,void* scene)
104 {
105         KX_GameObject* replica = ((KX_Scene*)scene)->AddNodeReplicaObject(node,(KX_GameObject*)gameobj);
106
107         if(replica)
108                 replica->Release();
109
110         return (void*)replica;
111 }
112
113 void* KX_SceneDestructionFunc(SG_IObject* node,void* gameobj,void* scene)
114 {
115         ((KX_Scene*)scene)->RemoveNodeDestructObject(node,(KX_GameObject*)gameobj);
116
117         return NULL;
118 };
119
120 bool KX_Scene::KX_ScenegraphUpdateFunc(SG_IObject* node,void* gameobj,void* scene)
121 {
122         return ((SG_Node*)node)->Schedule(((KX_Scene*)scene)->m_sghead);
123 }
124
125 bool KX_Scene::KX_ScenegraphRescheduleFunc(SG_IObject* node,void* gameobj,void* scene)
126 {
127         return ((SG_Node*)node)->Reschedule(((KX_Scene*)scene)->m_sghead);
128 }
129
130 SG_Callbacks KX_Scene::m_callbacks = SG_Callbacks(
131         KX_SceneReplicationFunc,
132         KX_SceneDestructionFunc,
133         KX_GameObject::UpdateTransformFunc,
134         KX_Scene::KX_ScenegraphUpdateFunc,
135         KX_Scene::KX_ScenegraphRescheduleFunc);
136
137 // temporarily var until there is a button in the userinterface
138 // (defined in KX_PythonInit.cpp)
139 extern bool gUseVisibilityTemp;
140
141 KX_Scene::KX_Scene(class SCA_IInputDevice* keyboarddevice,
142                                    class SCA_IInputDevice* mousedevice,
143                                    class NG_NetworkDeviceInterface *ndi,
144                                    const STR_String& sceneName,
145                                    Scene *scene,
146                                    class RAS_ICanvas* canvas): 
147         PyObjectPlus(),
148         m_keyboardmgr(NULL),
149         m_mousemgr(NULL),
150         m_sceneConverter(NULL),
151         m_physicsEnvironment(0),
152         m_sceneName(sceneName),
153         m_networkDeviceInterface(ndi),
154         m_active_camera(NULL),
155         m_ueberExecutionPriority(0),
156         m_blenderScene(scene)
157 {
158         m_suspendedtime = 0.0;
159         m_suspendeddelta = 0.0;
160
161         m_dbvt_culling = false;
162         m_dbvt_occlusion_res = 0;
163         m_activity_culling = false;
164         m_suspend = false;
165         m_isclearingZbuffer = true;
166         m_tempObjectList = new CListValue();
167         m_objectlist = new CListValue();
168         m_parentlist = new CListValue();
169         m_lightlist= new CListValue();
170         m_inactivelist = new CListValue();
171         m_euthanasyobjects = new CListValue();
172
173         m_logicmgr = new SCA_LogicManager();
174         
175         m_timemgr = new SCA_TimeEventManager(m_logicmgr);
176         m_keyboardmgr = new SCA_KeyboardManager(m_logicmgr,keyboarddevice);
177         m_mousemgr = new SCA_MouseManager(m_logicmgr,mousedevice, canvas);
178         
179         //SCA_AlwaysEventManager* alwaysmgr = new SCA_AlwaysEventManager(m_logicmgr);
180         //SCA_PropertyEventManager* propmgr = new SCA_PropertyEventManager(m_logicmgr);
181         SCA_ActuatorEventManager* actmgr = new SCA_ActuatorEventManager(m_logicmgr);
182         //SCA_RandomEventManager* rndmgr = new SCA_RandomEventManager(m_logicmgr);
183         SCA_BasicEventManager* basicmgr = new SCA_BasicEventManager(m_logicmgr);
184         //KX_RayEventManager* raymgr = new KX_RayEventManager(m_logicmgr);
185
186         KX_NetworkEventManager* netmgr = new KX_NetworkEventManager(m_logicmgr, ndi);
187         
188         
189
190         //m_logicmgr->RegisterEventManager(alwaysmgr);
191         //m_logicmgr->RegisterEventManager(propmgr);
192         m_logicmgr->RegisterEventManager(actmgr);
193         m_logicmgr->RegisterEventManager(m_keyboardmgr);
194         m_logicmgr->RegisterEventManager(m_mousemgr);
195         m_logicmgr->RegisterEventManager(m_timemgr);
196         //m_logicmgr->RegisterEventManager(rndmgr);
197         //m_logicmgr->RegisterEventManager(raymgr);
198         m_logicmgr->RegisterEventManager(netmgr);
199         m_logicmgr->RegisterEventManager(basicmgr);
200
201
202         SYS_SystemHandle hSystem = SYS_GetSystem();
203         bool nojoystick= SYS_GetCommandLineInt(hSystem,"nojoystick",0);
204         if (!nojoystick)
205         {
206                 SCA_JoystickManager *joymgr     = new SCA_JoystickManager(m_logicmgr);
207                 m_logicmgr->RegisterEventManager(joymgr);
208         }
209
210         MT_assert (m_networkDeviceInterface != NULL);
211         m_networkScene = new NG_NetworkScene(m_networkDeviceInterface);
212         
213         m_rootnode = NULL;
214
215         m_bucketmanager=new RAS_BucketManager();
216         
217         bool showObstacleSimulation = scene->gm.flag & GAME_SHOW_OBSTACLE_SIMULATION;
218         switch (scene->gm.obstacleSimulation)
219         {
220         case OBSTSIMULATION_TOI_rays:
221                 m_obstacleSimulation = new KX_ObstacleSimulationTOI_rays((MT_Scalar)scene->gm.levelHeight, showObstacleSimulation);
222                 break;
223         case OBSTSIMULATION_TOI_cells:
224                 m_obstacleSimulation = new KX_ObstacleSimulationTOI_cells((MT_Scalar)scene->gm.levelHeight, showObstacleSimulation);
225                 break;
226         default:
227                 m_obstacleSimulation = NULL;
228         }
229         
230 #ifdef WITH_PYTHON
231         m_attr_dict = PyDict_New(); /* new ref */
232         m_draw_call_pre = NULL;
233         m_draw_call_post = NULL;
234 #endif
235 }
236
237
238
239 KX_Scene::~KX_Scene()
240 {
241         // The release of debug properties used to be in SCA_IScene::~SCA_IScene
242         // It's still there but we remove all properties here otherwise some
243         // reference might be hanging and causing late release of objects
244         RemoveAllDebugProperties();
245
246         while (GetRootParentList()->GetCount() > 0) 
247         {
248                 KX_GameObject* parentobj = (KX_GameObject*) GetRootParentList()->GetValue(0);
249                 this->RemoveObject(parentobj);
250         }
251
252         if (m_obstacleSimulation)
253                 delete m_obstacleSimulation;
254
255         if(m_objectlist)
256                 m_objectlist->Release();
257
258         if (m_parentlist)
259                 m_parentlist->Release();
260         
261         if (m_inactivelist)
262                 m_inactivelist->Release();
263
264         if (m_lightlist)
265                 m_lightlist->Release();
266         
267         if (m_tempObjectList)
268                 m_tempObjectList->Release();
269
270         if (m_euthanasyobjects)
271                 m_euthanasyobjects->Release();
272
273         if (m_logicmgr)
274                 delete m_logicmgr;
275
276         if (m_physicsEnvironment)
277                 delete m_physicsEnvironment;
278
279         if (m_networkScene)
280                 delete m_networkScene;
281         
282         if (m_bucketmanager)
283         {
284                 delete m_bucketmanager;
285         }
286
287 #ifdef WITH_PYTHON
288         PyDict_Clear(m_attr_dict);
289         /* Py_CLEAR: Py_DECREF's and NULL's */
290         Py_CLEAR(m_attr_dict);
291
292         /* these may be NULL but the macro checks */
293         Py_CLEAR(m_draw_call_pre);
294         Py_CLEAR(m_draw_call_post);
295 #endif
296 }
297
298 RAS_BucketManager* KX_Scene::GetBucketManager()
299 {
300         return m_bucketmanager;
301 }
302
303
304 CListValue* KX_Scene::GetTempObjectList()
305 {
306         return m_tempObjectList;
307 }
308
309 CListValue* KX_Scene::GetObjectList()
310 {
311         return m_objectlist;
312 }
313
314
315 CListValue* KX_Scene::GetRootParentList()
316 {
317         return m_parentlist;
318 }
319
320 CListValue* KX_Scene::GetInactiveList()
321 {
322         return m_inactivelist;
323 }
324
325
326
327 CListValue* KX_Scene::GetLightList()
328 {
329         return m_lightlist;
330 }
331
332 SCA_LogicManager* KX_Scene::GetLogicManager()
333 {
334         return m_logicmgr;
335 }
336
337 SCA_TimeEventManager* KX_Scene::GetTimeEventManager()
338 {
339         return m_timemgr;
340 }
341
342
343
344  
345 list<class KX_Camera*>* KX_Scene::GetCameras()
346 {
347         return &m_cameras;
348 }
349
350 list<class KX_FontObject*>* KX_Scene::GetFonts()
351 {
352         return &m_fonts;
353 }
354
355 void KX_Scene::SetFramingType(RAS_FrameSettings & frame_settings)
356 {
357         m_frame_settings = frame_settings;
358 };
359
360 /**
361  * Return a const reference to the framing 
362  * type set by the above call.
363  * The contents are not guarenteed to be sensible
364  * if you don't call the above function.
365  */
366 const RAS_FrameSettings& KX_Scene::GetFramingType() const 
367 {
368         return m_frame_settings;
369 };      
370
371
372
373 /**
374  * Store the current scene's viewport on the 
375  * game engine canvas.
376  */
377 void KX_Scene::SetSceneViewport(const RAS_Rect &viewport)
378 {
379         m_viewport = viewport;
380 }
381
382
383
384 const RAS_Rect& KX_Scene::GetSceneViewport() const 
385 {
386         return m_viewport;
387 }
388
389
390
391 void KX_Scene::SetWorldInfo(class KX_WorldInfo* worldinfo)
392 {
393         m_worldinfo = worldinfo;
394 }
395
396
397
398 class KX_WorldInfo* KX_Scene::GetWorldInfo()
399 {
400         return m_worldinfo;
401 }
402
403
404 const STR_String& KX_Scene::GetName()
405 {
406         return m_sceneName;
407 }
408
409
410 void KX_Scene::Suspend()
411 {
412         m_suspend = true;
413 }
414
415 void KX_Scene::Resume()
416 {
417         m_suspend = false;
418 }
419
420 void KX_Scene::SetActivityCulling(bool b)
421 {
422         m_activity_culling = b;
423 }
424
425 bool KX_Scene::IsSuspended()
426 {
427         return m_suspend;
428 }
429
430 bool KX_Scene::IsClearingZBuffer()
431 {
432         return m_isclearingZbuffer;
433 }
434
435 void KX_Scene::EnableZBufferClearing(bool isclearingZbuffer)
436 {
437         m_isclearingZbuffer = isclearingZbuffer;
438 }
439
440 void KX_Scene::RemoveNodeDestructObject(class SG_IObject* node,class CValue* gameobj)
441 {
442         KX_GameObject* orgobj = (KX_GameObject*)gameobj;        
443         if (NewRemoveObject(orgobj) != 0)
444         {
445                 // object is not yet deleted because a reference is hanging somewhere.
446                 // This should not happen anymore since we use proxy object for Python
447                 // confident enough to put an assert?
448                 //assert(false);
449                 printf("Zombie object! name=%s\n", orgobj->GetName().ReadPtr());
450                 orgobj->SetSGNode(NULL);
451                 PHY_IGraphicController* ctrl = orgobj->GetGraphicController();
452                 if (ctrl)
453                 {
454                         // a graphic controller is set, we must delete it as the node will be deleted
455                         delete ctrl;
456                         orgobj->SetGraphicController(NULL);
457                 }
458         }
459         if (node)
460                 delete node;
461 }
462
463 KX_GameObject* KX_Scene::AddNodeReplicaObject(class SG_IObject* node, class CValue* gameobj)
464 {
465         // for group duplication, limit the duplication of the hierarchy to the
466         // objects that are part of the group. 
467         if (!IsObjectInGroup(gameobj))
468                 return NULL;
469         
470         KX_GameObject* orgobj = (KX_GameObject*)gameobj;
471         KX_GameObject* newobj = (KX_GameObject*)orgobj->GetReplica();
472         m_map_gameobject_to_replica.insert(orgobj, newobj);
473
474         // also register 'timers' (time properties) of the replica
475         int numprops = newobj->GetPropertyCount();
476
477         for (int i = 0; i < numprops; i++)
478         {
479                 CValue* prop = newobj->GetProperty(i);
480
481                 if (prop->GetProperty("timer"))
482                         this->m_timemgr->AddTimeProperty(prop);
483         }
484
485         if (node)
486         {
487                 newobj->SetSGNode((SG_Node*)node);
488         }
489         else
490         {
491                 m_rootnode = new SG_Node(newobj,this,KX_Scene::m_callbacks);
492         
493                 // this fixes part of the scaling-added object bug
494                 SG_Node* orgnode = orgobj->GetSGNode();
495                 m_rootnode->SetLocalScale(orgnode->GetLocalScale());
496                 m_rootnode->SetLocalPosition(orgnode->GetLocalPosition());
497                 m_rootnode->SetLocalOrientation(orgnode->GetLocalOrientation());
498
499                 // define the relationship between this node and it's parent.
500                 KX_NormalParentRelation * parent_relation = 
501                         KX_NormalParentRelation::New();
502                 m_rootnode->SetParentRelation(parent_relation);
503
504                 newobj->SetSGNode(m_rootnode);
505         }
506         
507         SG_IObject* replicanode = newobj->GetSGNode();
508 //      SG_Node* rootnode = (replicanode == m_rootnode ? NULL : m_rootnode);
509
510         replicanode->SetSGClientObject(newobj);
511
512         // this is the list of object that are send to the graphics pipeline
513         m_objectlist->Add(newobj->AddRef());
514         if (newobj->GetGameObjectType()==SCA_IObject::OBJ_LIGHT)
515                 m_lightlist->Add(newobj->AddRef());
516         newobj->AddMeshUser();
517
518         // logic cannot be replicated, until the whole hierarchy is replicated.
519         m_logicHierarchicalGameObjects.push_back(newobj);
520         //replicate controllers of this node
521         SGControllerList        scenegraphcontrollers = orgobj->GetSGNode()->GetSGControllerList();
522         replicanode->RemoveAllControllers();
523         SGControllerList::iterator cit;
524         //int numcont = scenegraphcontrollers.size();
525         
526         for (cit = scenegraphcontrollers.begin();!(cit==scenegraphcontrollers.end());++cit)
527         {
528                 // controller replication is quite complicated
529                 // only replicate ipo and physics controller for now
530
531                 SG_Controller* replicacontroller = (*cit)->GetReplica((SG_Node*) replicanode);
532                 if (replicacontroller)
533                 {
534                         replicacontroller->SetObject(replicanode);
535                         replicanode->AddSGController(replicacontroller);
536                 }
537         }
538         // replicate graphic controller
539         if (orgobj->GetGraphicController())
540         {
541                 PHY_IMotionState* motionstate = new KX_MotionState(newobj->GetSGNode());
542                 PHY_IGraphicController* newctrl = orgobj->GetGraphicController()->GetReplica(motionstate);
543                 newctrl->setNewClientInfo(newobj->getClientInfo());
544                 newobj->SetGraphicController(newctrl);
545         }
546         return newobj;
547 }
548
549
550
551 // before calling this method KX_Scene::ReplicateLogic(), make sure to
552 // have called 'GameObject::ReParentLogic' for each object this
553 // hierarchy that's because first ALL bricks must exist in the new
554 // replica of the hierarchy in order to make cross-links work properly
555 // !
556 // It is VERY important that the order of sensors and actuators in
557 // the replicated object is preserved: it is used to reconnect the logic.
558 // This method is more robust then using the bricks name in case of complex 
559 // group replication. The replication of logic bricks is done in 
560 // SCA_IObject::ReParentLogic(), make sure it preserves the order of the bricks.
561 void KX_Scene::ReplicateLogic(KX_GameObject* newobj)
562 {
563         // also relink the controller to sensors/actuators
564         SCA_ControllerList& controllers = newobj->GetControllers();
565         //SCA_SensorList&     sensors     = newobj->GetSensors();
566         //SCA_ActuatorList&   actuators   = newobj->GetActuators();
567
568         for (SCA_ControllerList::iterator itc = controllers.begin(); !(itc==controllers.end());itc++)
569         {
570                 SCA_IController* cont = (*itc);
571                 cont->SetUeberExecutePriority(m_ueberExecutionPriority);
572                 vector<SCA_ISensor*> linkedsensors = cont->GetLinkedSensors();
573                 vector<SCA_IActuator*> linkedactuators = cont->GetLinkedActuators();
574
575                 // disconnect the sensors and actuators
576                 // do it directly on the list at this controller is not connected to anything at this stage
577                 cont->GetLinkedSensors().clear();
578                 cont->GetLinkedActuators().clear();
579                 
580                 // now relink each sensor
581                 for (vector<SCA_ISensor*>::iterator its = linkedsensors.begin();!(its==linkedsensors.end());its++)
582                 {
583                         SCA_ISensor* oldsensor = (*its);
584                         SCA_IObject* oldsensorobj = oldsensor->GetParent();
585                         SCA_IObject* newsensorobj = NULL;
586                 
587                         // the original owner of the sensor has been replicated?
588                         void **h_obj = m_map_gameobject_to_replica[oldsensorobj];
589                         if (h_obj)
590                                 newsensorobj = (SCA_IObject*)(*h_obj);
591                         if (!newsensorobj)
592                         {
593                                 // no, then the sensor points outside the hierachy, keep it the same
594                                 if (m_objectlist->SearchValue(oldsensorobj))
595                                         // only replicate links that points to active objects
596                                         m_logicmgr->RegisterToSensor(cont,oldsensor);
597                         }
598                         else
599                         {
600                                 // yes, then the new sensor has the same position
601                                 SCA_SensorList& sensorlist = oldsensorobj->GetSensors();
602                                 SCA_SensorList::iterator sit;
603                                 SCA_ISensor* newsensor = NULL;
604                                 int sensorpos;
605
606                                 for (sensorpos=0, sit=sensorlist.begin(); sit!=sensorlist.end(); sit++, sensorpos++)
607                                 {
608                                         if ((*sit) == oldsensor) 
609                                         {
610                                                 newsensor = newsensorobj->GetSensors().at(sensorpos);
611                                                 break;
612                                         }
613                                 }
614                                 assert(newsensor != NULL);
615                                 m_logicmgr->RegisterToSensor(cont,newsensor);
616                         }
617                 }
618                 
619                 // now relink each actuator
620                 for (vector<SCA_IActuator*>::iterator ita = linkedactuators.begin();!(ita==linkedactuators.end());ita++)
621                 {
622                         SCA_IActuator* oldactuator = (*ita);
623                         SCA_IObject* oldactuatorobj = oldactuator->GetParent();
624                         SCA_IObject* newactuatorobj = NULL;
625
626                         // the original owner of the sensor has been replicated?
627                         void **h_obj = m_map_gameobject_to_replica[oldactuatorobj];
628                         if (h_obj)
629                                 newactuatorobj = (SCA_IObject*)(*h_obj);
630
631                         if (!newactuatorobj)
632                         {
633                                 // no, then the sensor points outside the hierachy, keep it the same
634                                 if (m_objectlist->SearchValue(oldactuatorobj))
635                                         // only replicate links that points to active objects
636                                         m_logicmgr->RegisterToActuator(cont,oldactuator);
637                         }
638                         else
639                         {
640                                 // yes, then the new sensor has the same position
641                                 SCA_ActuatorList& actuatorlist = oldactuatorobj->GetActuators();
642                                 SCA_ActuatorList::iterator ait;
643                                 SCA_IActuator* newactuator = NULL;
644                                 int actuatorpos;
645
646                                 for (actuatorpos=0, ait=actuatorlist.begin(); ait!=actuatorlist.end(); ait++, actuatorpos++)
647                                 {
648                                         if ((*ait) == oldactuator) 
649                                         {
650                                                 newactuator = newactuatorobj->GetActuators().at(actuatorpos);
651                                                 break;
652                                         }
653                                 }
654                                 assert(newactuator != NULL);
655                                 m_logicmgr->RegisterToActuator(cont,newactuator);
656                                 newactuator->SetUeberExecutePriority(m_ueberExecutionPriority);
657                         }
658                 }
659         }
660         // ready to set initial state
661         newobj->ResetState();
662 }
663
664 void KX_Scene::DupliGroupRecurse(CValue* obj, int level)
665 {
666         KX_GameObject* groupobj = (KX_GameObject*) obj;
667         KX_GameObject* replica;
668         KX_GameObject* gameobj;
669         Object* blgroupobj = groupobj->GetBlenderObject();
670         Group* group;
671         GroupObject *go;
672         vector<KX_GameObject*> duplilist;
673
674         if (!groupobj->GetSGNode() ||
675                 !groupobj->IsDupliGroup() ||
676                 level>MAX_DUPLI_RECUR)
677                 return;
678
679         // we will add one group at a time
680         m_logicHierarchicalGameObjects.clear();
681         m_map_gameobject_to_replica.clear();
682         m_ueberExecutionPriority++;
683         // for groups will do something special: 
684         // we will force the creation of objects to those in the group only
685         // Again, this is match what Blender is doing (it doesn't care of parent relationship)
686         m_groupGameObjects.clear();
687
688         group = blgroupobj->dup_group;
689         for(go=(GroupObject*)group->gobject.first; go; go=(GroupObject*)go->next) 
690         {
691                 Object* blenderobj = go->ob;
692                 if (blgroupobj == blenderobj)
693                         // this check is also in group_duplilist()
694                         continue;
695
696                 gameobj = (KX_GameObject*)m_logicmgr->FindGameObjByBlendObj(blenderobj);
697                 if (gameobj == NULL) 
698                 {
699                         // this object has not been converted!!!
700                         // Should not happen as dupli group are created automatically 
701                         continue;
702                 }
703
704                 gameobj->SetBlenderGroupObject(blgroupobj);
705
706                 if ((blenderobj->lay & group->layer)==0)
707                 {
708                         // object is not visible in the 3D view, will not be instantiated
709                         continue;
710                 }
711                 m_groupGameObjects.insert(gameobj);
712         }
713
714         set<CValue*>::iterator oit;
715         for (oit=m_groupGameObjects.begin(); oit != m_groupGameObjects.end(); oit++)
716         {
717                 gameobj = (KX_GameObject*)(*oit);
718
719                 KX_GameObject *parent = gameobj->GetParent();
720                 if (parent != NULL)
721                 {
722                         parent->Release(); // GetParent() increased the refcount
723
724                         // this object is not a top parent. Either it is the child of another
725                         // object in the group and it will be added automatically when the parent
726                         // is added. Or it is the child of an object outside the group and the group
727                         // is inconsistent, skip it anyway
728                         continue;
729                 }
730                 replica = (KX_GameObject*) AddNodeReplicaObject(NULL,gameobj);
731                 // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame)
732                 m_parentlist->Add(replica->AddRef());
733
734                 // recurse replication into children nodes
735                 NodeList& children = gameobj->GetSGNode()->GetSGChildren();
736
737                 replica->GetSGNode()->ClearSGChildren();
738                 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
739                 {
740                         SG_Node* orgnode = (*childit);
741                         SG_Node* childreplicanode = orgnode->GetSGReplica();
742                         if (childreplicanode)
743                                 replica->GetSGNode()->AddChild(childreplicanode);
744                 }
745                 // don't replicate logic now: we assume that the objects in the group can have
746                 // logic relationship, even outside parent relationship
747                 // In order to match 3D view, the position of groupobj is used as a 
748                 // transformation matrix instead of the new position. This means that 
749                 // the group reference point is 0,0,0
750
751                 // get the rootnode's scale
752                 MT_Vector3 newscale = groupobj->NodeGetWorldScaling();
753                 // set the replica's relative scale with the rootnode's scale
754                 replica->NodeSetRelativeScale(newscale);
755
756                 MT_Point3 offset(group->dupli_ofs);
757                 MT_Point3 newpos = groupobj->NodeGetWorldPosition() + 
758                         newscale*(groupobj->NodeGetWorldOrientation() * (gameobj->NodeGetWorldPosition()-offset));
759                 replica->NodeSetLocalPosition(newpos);
760                 // set the orientation after position for softbody!
761                 MT_Matrix3x3 newori = groupobj->NodeGetWorldOrientation() * gameobj->NodeGetWorldOrientation();
762                 replica->NodeSetLocalOrientation(newori);
763                 // update scenegraph for entire tree of children
764                 replica->GetSGNode()->UpdateWorldData(0);
765                 replica->GetSGNode()->SetBBox(gameobj->GetSGNode()->BBox());
766                 replica->GetSGNode()->SetRadius(gameobj->GetSGNode()->Radius());
767                 // we can now add the graphic controller to the physic engine
768                 replica->ActivateGraphicController(true);
769
770                 // done with replica
771                 replica->Release();
772         }
773
774         // the logic must be replicated first because we need
775         // the new logic bricks before relinking
776         vector<KX_GameObject*>::iterator git;
777         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
778         {
779                 (*git)->ReParentLogic();
780         }
781         
782         //      relink any pointers as necessary, sort of a temporary solution
783         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
784         {
785                 // this will also relink the actuator to objects within the hierarchy
786                 (*git)->Relink(&m_map_gameobject_to_replica);
787                 // add the object in the layer of the parent
788                 (*git)->SetLayer(groupobj->GetLayer());
789                 // If the object was a light, we need to update it's RAS_LightObject as well
790                 if ((*git)->GetGameObjectType()==SCA_IObject::OBJ_LIGHT)
791                 {
792                         KX_LightObject* lightobj = static_cast<KX_LightObject*>(*git);
793                         lightobj->GetLightData()->m_layer = groupobj->GetLayer();
794                 }
795         }
796
797         // replicate crosslinks etc. between logic bricks
798         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
799         {
800                 ReplicateLogic((*git));
801         }
802         
803         // now look if object in the hierarchy have dupli group and recurse
804         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
805         {
806                 if ((*git) != groupobj && (*git)->IsDupliGroup())
807                         // can't instantiate group immediately as it destroys m_logicHierarchicalGameObjects
808                         duplilist.push_back((*git));
809         }
810
811         for (git = duplilist.begin(); !(git == duplilist.end()); ++git)
812         {
813                 DupliGroupRecurse((*git), level+1);
814         }
815 }
816
817
818 SCA_IObject* KX_Scene::AddReplicaObject(class CValue* originalobject,
819                                                                                 class CValue* parentobject,
820                                                                                 int lifespan)
821 {
822
823         m_logicHierarchicalGameObjects.clear();
824         m_map_gameobject_to_replica.clear();
825         m_groupGameObjects.clear();
826
827         // todo: place a timebomb in the object, for temporarily objects :)
828         // lifespan of zero means 'this object lives forever'
829         KX_GameObject* originalobj = (KX_GameObject*) originalobject;
830         KX_GameObject* parentobj = (KX_GameObject*) parentobject;
831
832         m_ueberExecutionPriority++;
833
834         // lets create a replica
835         KX_GameObject* replica = (KX_GameObject*) AddNodeReplicaObject(NULL,originalobj);
836
837         if (lifespan > 0)
838         {
839                 // add a timebomb to this object
840                 // for now, convert between so called frames and realtime
841                 m_tempObjectList->Add(replica->AddRef());
842                 // this convert the life from frames to sort-of seconds, hard coded 0.02 that assumes we have 50 frames per second
843                 // if you change this value, make sure you change it in KX_GameObject::pyattr_get_life property too
844                 CValue *fval = new CFloatValue(lifespan*0.02);
845                 replica->SetProperty("::timebomb",fval);
846                 fval->Release();
847         }
848
849         // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame)
850         m_parentlist->Add(replica->AddRef());
851
852         // recurse replication into children nodes
853
854         NodeList& children = originalobj->GetSGNode()->GetSGChildren();
855
856         replica->GetSGNode()->ClearSGChildren();
857         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
858         {
859                 SG_Node* orgnode = (*childit);
860                 SG_Node* childreplicanode = orgnode->GetSGReplica();
861                 if (childreplicanode)
862                         replica->GetSGNode()->AddChild(childreplicanode);
863         }
864
865         // At this stage all the objects in the hierarchy have been duplicated,
866         // we can update the scenegraph, we need it for the duplication of logic
867         MT_Point3 newpos = ((KX_GameObject*) parentobject)->NodeGetWorldPosition();
868         replica->NodeSetLocalPosition(newpos);
869
870         MT_Matrix3x3 newori = ((KX_GameObject*) parentobject)->NodeGetWorldOrientation();
871         replica->NodeSetLocalOrientation(newori);
872         
873         // get the rootnode's scale
874         MT_Vector3 newscale = parentobj->GetSGNode()->GetRootSGParent()->GetLocalScale();
875
876         // set the replica's relative scale with the rootnode's scale
877         replica->NodeSetRelativeScale(newscale);
878
879         replica->GetSGNode()->UpdateWorldData(0);
880         replica->GetSGNode()->SetBBox(originalobj->GetSGNode()->BBox());
881         replica->GetSGNode()->SetRadius(originalobj->GetSGNode()->Radius());
882         // the size is correct, we can add the graphic controller to the physic engine
883         replica->ActivateGraphicController(true);
884
885         // now replicate logic
886         vector<KX_GameObject*>::iterator git;
887         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
888         {
889                 (*git)->ReParentLogic();
890         }
891         
892         //      relink any pointers as necessary, sort of a temporary solution
893         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
894         {
895                 // this will also relink the actuators in the hierarchy
896                 (*git)->Relink(&m_map_gameobject_to_replica);
897                 // add the object in the layer of the parent
898                 (*git)->SetLayer(parentobj->GetLayer());
899                 // If the object was a light, we need to update it's RAS_LightObject as well
900                 if ((*git)->GetGameObjectType()==SCA_IObject::OBJ_LIGHT)
901                 {
902                         KX_LightObject* lightobj = static_cast<KX_LightObject*>(*git);
903                         lightobj->GetLightData()->m_layer = parentobj->GetLayer();
904                 }
905         }
906
907         // replicate crosslinks etc. between logic bricks
908         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
909         {
910                 ReplicateLogic((*git));
911         }
912         
913         // check if there are objects with dupligroup in the hierarchy
914         vector<KX_GameObject*> duplilist;
915         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
916         {
917                 if ((*git)->IsDupliGroup())
918                 {
919                         // separate list as m_logicHierarchicalGameObjects is also used by DupliGroupRecurse()
920                         duplilist.push_back(*git);
921                 }
922         }
923         for (git = duplilist.begin();!(git==duplilist.end());++git)
924         {
925                 DupliGroupRecurse(*git, 0);
926         }
927         //      don't release replica here because we are returning it, not done with it...
928         return replica;
929 }
930
931
932
933 void KX_Scene::RemoveObject(class CValue* gameobj)
934 {
935         KX_GameObject* newobj = (KX_GameObject*) gameobj;
936
937         // disconnect child from parent
938         SG_Node* node = newobj->GetSGNode();
939
940         if (node)
941         {
942                 node->DisconnectFromParent();
943
944                 // recursively destruct
945                 node->Destruct();
946         }
947         //no need to do that: the object is destroyed and memory released 
948         //newobj->SetSGNode(0);
949 }
950
951 void KX_Scene::DelayedRemoveObject(class CValue* gameobj)
952 {
953         //KX_GameObject* newobj = (KX_GameObject*) gameobj;
954         if (!m_euthanasyobjects->SearchValue(gameobj))
955         {
956                 m_euthanasyobjects->Add(gameobj->AddRef());
957         } 
958 }
959
960
961
962 int KX_Scene::NewRemoveObject(class CValue* gameobj)
963 {
964         int ret;
965         KX_GameObject* newobj = (KX_GameObject*) gameobj;
966
967         /* Invalidate the python reference, since the object may exist in script lists
968          * its possible that it wont be automatically invalidated, so do it manually here,
969          * 
970          * if for some reason the object is added back into the scene python can always get a new Proxy
971          */
972         newobj->InvalidateProxy();
973
974         // keep the blender->game object association up to date
975         // note that all the replicas of an object will have the same
976         // blender object, that's why we need to check the game object
977         // as only the deletion of the original object must be recorded
978         m_logicmgr->UnregisterGameObj(newobj->GetBlenderObject(), gameobj);
979
980         //todo: look at this
981         //GetPhysicsEnvironment()->RemovePhysicsController(gameobj->getPhysicsController());
982
983         // remove all sensors/controllers/actuators from logicsystem...
984         
985         SCA_SensorList& sensors = newobj->GetSensors();
986         for (SCA_SensorList::iterator its = sensors.begin();
987                  !(its==sensors.end());its++)
988         {
989                 m_logicmgr->RemoveSensor(*its);
990         }
991
992         SCA_ControllerList& controllers = newobj->GetControllers();
993         for (SCA_ControllerList::iterator itc = controllers.begin();
994                  !(itc==controllers.end());itc++)
995         {
996                 m_logicmgr->RemoveController(*itc);
997         }
998
999         SCA_ActuatorList& actuators = newobj->GetActuators();
1000         for (SCA_ActuatorList::iterator ita = actuators.begin();
1001                  !(ita==actuators.end());ita++)
1002         {
1003                 m_logicmgr->RemoveActuator(*ita);
1004         }
1005         // the sensors/controllers/actuators must also be released, this is done in ~SCA_IObject
1006
1007         // now remove the timer properties from the time manager
1008         int numprops = newobj->GetPropertyCount();
1009
1010         for (int i = 0; i < numprops; i++)
1011         {
1012                 CValue* propval = newobj->GetProperty(i);
1013                 if (propval->GetProperty("timer"))
1014                 {
1015                         m_timemgr->RemoveTimeProperty(propval);
1016                 }
1017         }
1018         
1019         newobj->RemoveMeshes();
1020         ret = 1;
1021         if (newobj->GetGameObjectType()==SCA_IObject::OBJ_LIGHT && m_lightlist->RemoveValue(newobj))
1022                 ret = newobj->Release();
1023         if (m_objectlist->RemoveValue(newobj))
1024                 ret = newobj->Release();
1025         if (m_tempObjectList->RemoveValue(newobj))
1026                 ret = newobj->Release();
1027         if (m_parentlist->RemoveValue(newobj))
1028                 ret = newobj->Release();
1029         if (m_inactivelist->RemoveValue(newobj))
1030                 ret = newobj->Release();
1031         if (m_euthanasyobjects->RemoveValue(newobj))
1032                 ret = newobj->Release();
1033                 
1034         if (newobj == m_active_camera)
1035         {
1036                 //no AddRef done on m_active_camera so no Release
1037                 //m_active_camera->Release();
1038                 m_active_camera = NULL;
1039         }
1040
1041         // in case this is a camera
1042         m_cameras.remove((KX_Camera*)newobj);
1043
1044         // in case this is a font
1045         m_fonts.remove((KX_FontObject*)newobj);
1046
1047         /* currently does nothing, keep incase we need to Unregister something */
1048 #if 0
1049         if (m_sceneConverter)
1050                 m_sceneConverter->UnregisterGameObject(newobj);
1051 #endif
1052         
1053         // return value will be 0 if the object is actually deleted (all reference gone)
1054         
1055         return ret;
1056 }
1057
1058
1059
1060 void KX_Scene::ReplaceMesh(class CValue* obj,void* meshobj, bool use_gfx, bool use_phys)
1061 {
1062         KX_GameObject* gameobj = static_cast<KX_GameObject*>(obj);
1063         RAS_MeshObject* mesh = static_cast<RAS_MeshObject*>(meshobj);
1064
1065         if(!gameobj) {
1066                 std::cout << "KX_Scene::ReplaceMesh Warning: invalid object, doing nothing" << std::endl;
1067                 return;
1068         }
1069
1070         if(use_gfx && mesh != NULL)
1071         {               
1072         gameobj->RemoveMeshes();
1073         gameobj->AddMesh(mesh);
1074         
1075         if (gameobj->m_isDeformable)
1076         {
1077                 BL_DeformableGameObject* newobj = static_cast<BL_DeformableGameObject*>( gameobj );
1078                 
1079                 if (newobj->GetDeformer())
1080                 {
1081                         delete newobj->GetDeformer();
1082                         newobj->SetDeformer(NULL);
1083                 }
1084
1085                 if (mesh->GetMesh()) 
1086                 {
1087                         // we must create a new deformer but which one?
1088                         KX_GameObject* parentobj = newobj->GetParent();
1089                         // this always return the original game object (also for replicate)
1090                         Object* blendobj = newobj->GetBlenderObject();
1091                         // object that owns the new mesh
1092                         Object* oldblendobj = static_cast<struct Object*>(m_logicmgr->FindBlendObjByGameMeshName(mesh->GetName()));
1093                         Mesh* blendmesh = mesh->GetMesh();
1094
1095                         bool bHasModifier = BL_ModifierDeformer::HasCompatibleDeformer(blendobj);
1096                         bool bHasShapeKey = blendmesh->key != NULL && blendmesh->key->type==KEY_RELATIVE;
1097                         bool bHasDvert = blendmesh->dvert != NULL;
1098                         bool bHasArmature = 
1099                                 BL_ModifierDeformer::HasArmatureDeformer(blendobj) &&
1100                                 parentobj &&                                                            // current parent is armature
1101                                 parentobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE &&
1102                                 oldblendobj &&                                                          // needed for mesh deform
1103                                 blendobj->parent &&                                                     // original object had armature (not sure this test is needed)
1104                                 blendobj->parent->type == OB_ARMATURE &&
1105                                 blendmesh->dvert!=NULL;                                         // mesh has vertex group
1106 #ifdef USE_BULLET
1107                         bool bHasSoftBody = (!parentobj && (blendobj->gameflag & OB_SOFT_BODY));
1108 #endif
1109                         bool releaseParent = true;
1110
1111                         
1112                         if (oldblendobj==NULL) {
1113                                 if (bHasModifier || bHasShapeKey || bHasDvert || bHasArmature) {
1114                                         std::cout << "warning: ReplaceMesh() new mesh is not used in an object from the current scene, you will get incorrect behavior" << std::endl;
1115                                         bHasShapeKey= bHasDvert= bHasArmature=bHasModifier= false;
1116                                 }
1117                         }
1118                         
1119                         if (bHasModifier)
1120                         {
1121                                 BL_ModifierDeformer* modifierDeformer;
1122                                 if (bHasShapeKey || bHasArmature)
1123                                 {
1124                                         modifierDeformer = new BL_ModifierDeformer(
1125                                                 newobj,
1126                                                 m_blenderScene,
1127                                                 oldblendobj, blendobj,
1128                                                 mesh,
1129                                                 true,
1130                                                 static_cast<BL_ArmatureObject*>( parentobj )
1131                                         );
1132                                         releaseParent= false;
1133                                         modifierDeformer->LoadShapeDrivers(blendobj->parent);
1134                                 }
1135                                 else
1136                                 {
1137                                         modifierDeformer = new BL_ModifierDeformer(
1138                                                 newobj,
1139                                                 m_blenderScene,
1140                                                 oldblendobj, blendobj,
1141                                                 mesh,
1142                                                 false,
1143                                                 NULL
1144                                         );
1145                                 }
1146                                 newobj->SetDeformer(modifierDeformer);
1147                         } 
1148                         else    if (bHasShapeKey)
1149                         {
1150                                 BL_ShapeDeformer* shapeDeformer;
1151                                 if (bHasArmature) 
1152                                 {
1153                                         shapeDeformer = new BL_ShapeDeformer(
1154                                                 newobj,
1155                                                 oldblendobj, blendobj,
1156                                                 mesh,
1157                                                 true,
1158                                                 true,
1159                                                 static_cast<BL_ArmatureObject*>( parentobj )
1160                                         );
1161                                         releaseParent= false;
1162                                         shapeDeformer->LoadShapeDrivers(blendobj->parent);
1163                                 }
1164                                 else
1165                                 {
1166                                         shapeDeformer = new BL_ShapeDeformer(
1167                                                 newobj,
1168                                                 oldblendobj, blendobj,
1169                                                 mesh,
1170                                                 false,
1171                                                 true,
1172                                                 NULL
1173                                         );
1174                                 }
1175                                 newobj->SetDeformer( shapeDeformer);
1176                         }
1177                         else if (bHasArmature) 
1178                         {
1179                                 BL_SkinDeformer* skinDeformer = new BL_SkinDeformer(
1180                                         newobj,
1181                                         oldblendobj, blendobj,
1182                                         mesh,
1183                                         true,
1184                                         true,
1185                                         static_cast<BL_ArmatureObject*>( parentobj )
1186                                 );
1187                                 releaseParent= false;
1188                                 newobj->SetDeformer(skinDeformer);
1189                         }
1190                         else if (bHasDvert)
1191                         {
1192                                 BL_MeshDeformer* meshdeformer = new BL_MeshDeformer(
1193                                         newobj, oldblendobj, mesh
1194                                 );
1195                                 newobj->SetDeformer(meshdeformer);
1196                         }
1197 #ifdef USE_BULLET
1198                         else if (bHasSoftBody)
1199                         {
1200                                 KX_SoftBodyDeformer *softdeformer = new KX_SoftBodyDeformer(mesh, newobj);
1201                                 newobj->SetDeformer(softdeformer);
1202                         }
1203 #endif
1204
1205                         // release parent reference if its not being used 
1206                         if( releaseParent && parentobj)
1207                                 parentobj->Release();
1208                 }
1209         }
1210
1211         gameobj->AddMeshUser();
1212         }
1213
1214 #ifdef USE_BULLET
1215         if(use_phys) { /* update the new assigned mesh with the physics mesh */
1216                 KX_ReInstanceBulletShapeFromMesh(gameobj, NULL, use_gfx?NULL:mesh);
1217         }
1218 #endif
1219 }
1220
1221 /* Font Object routines */
1222 void KX_Scene::AddFont(KX_FontObject* font)
1223 {
1224         if (!FindFont(font))
1225                 m_fonts.push_back(font);
1226 }
1227
1228 KX_FontObject* KX_Scene::FindFont(KX_FontObject* font)
1229 {
1230         list<KX_FontObject*>::iterator it = m_fonts.begin();
1231
1232         while ( (it != m_fonts.end()) 
1233                         && ((*it) != font) ) {
1234           ++it;
1235         }
1236
1237         return ((it == m_fonts.end()) ? NULL : (*it));
1238 }
1239
1240
1241 /* Camera Object routines */
1242 KX_Camera* KX_Scene::FindCamera(KX_Camera* cam)
1243 {
1244         list<KX_Camera*>::iterator it = m_cameras.begin();
1245
1246         while ( (it != m_cameras.end()) 
1247                         && ((*it) != cam) ) {
1248           it++;
1249         }
1250
1251         return ((it == m_cameras.end()) ? NULL : (*it));
1252 }
1253
1254
1255 KX_Camera* KX_Scene::FindCamera(STR_String& name)
1256 {
1257         list<KX_Camera*>::iterator it = m_cameras.begin();
1258
1259         while ( (it != m_cameras.end()) 
1260                         && ((*it)->GetName() != name) ) {
1261           it++;
1262         }
1263
1264         return ((it == m_cameras.end()) ? NULL : (*it));
1265 }
1266
1267 void KX_Scene::AddCamera(KX_Camera* cam)
1268 {
1269         if (!FindCamera(cam))
1270                 m_cameras.push_back(cam);
1271 }
1272
1273
1274 KX_Camera* KX_Scene::GetActiveCamera()
1275 {       
1276         // NULL if not defined
1277         return m_active_camera;
1278 }
1279
1280
1281 void KX_Scene::SetActiveCamera(KX_Camera* cam)
1282 {
1283         // only set if the cam is in the active list? Or add it otherwise?
1284         if (!FindCamera(cam)){
1285                 AddCamera(cam);
1286                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
1287         } 
1288
1289         m_active_camera = cam;
1290 }
1291
1292 void KX_Scene::SetCameraOnTop(KX_Camera* cam)
1293 {
1294         if (!FindCamera(cam)){
1295                 // adding is always done at the back, so that's all that needs to be done
1296                 AddCamera(cam);
1297                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
1298         } else {
1299                 m_cameras.remove(cam);
1300                 m_cameras.push_back(cam);
1301         }
1302 }
1303
1304
1305 void KX_Scene::UpdateMeshTransformations()
1306 {
1307         // do this incrementally in the future
1308         for (int i = 0; i < m_objectlist->GetCount(); i++)
1309         {
1310                 KX_GameObject* gameobj = (KX_GameObject*)m_objectlist->GetValue(i);
1311                 gameobj->GetOpenGLMatrix();
1312         }
1313 }
1314
1315 void KX_Scene::MarkVisible(SG_Tree *node, RAS_IRasterizer* rasty, KX_Camera* cam, int layer)
1316 {
1317         int intersect = KX_Camera::INTERSECT;
1318         KX_GameObject *gameobj = node->Client()?(KX_GameObject*) node->Client()->GetSGClientObject():NULL;
1319         bool visible = (gameobj && gameobj->GetVisible() && (!layer || (gameobj->GetLayer() & layer)));
1320         bool dotest = visible || node->Left() || node->Right();
1321
1322         /* If the camera is inside the box, assume intersect. */
1323         if (dotest && !node->inside( cam->NodeGetWorldPosition()))
1324         {
1325                 MT_Scalar radius = node->Radius();
1326                 MT_Point3 center = node->Center();
1327                 
1328                 intersect =  cam->SphereInsideFrustum(center, radius); 
1329                 
1330                 if (intersect == KX_Camera::INTERSECT)
1331                 {
1332                         MT_Point3 box[8];
1333                         node->get(box);
1334                         intersect = cam->BoxInsideFrustum(box);
1335                 }
1336         }
1337
1338         switch (intersect)
1339         {
1340                 case KX_Camera::OUTSIDE:
1341                         MarkSubTreeVisible(node, rasty, false, cam);
1342                         break;
1343                 case KX_Camera::INTERSECT:
1344                         if (gameobj)
1345                                 MarkVisible(rasty, gameobj, cam, layer);
1346                         if (node->Left())
1347                                 MarkVisible(node->Left(), rasty, cam, layer);
1348                         if (node->Right())
1349                                 MarkVisible(node->Right(), rasty, cam, layer);
1350                         break;
1351                 case KX_Camera::INSIDE:
1352                         MarkSubTreeVisible(node, rasty, true, cam, layer);
1353                         break;
1354         }
1355 }
1356
1357 void KX_Scene::MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool visible, KX_Camera* cam, int layer)
1358 {
1359         if (node->Client())
1360         {
1361                 KX_GameObject *gameobj = (KX_GameObject*) node->Client()->GetSGClientObject();
1362                 if (gameobj->GetVisible())
1363                 {
1364                         if (visible)
1365                         {
1366                                 int nummeshes = gameobj->GetMeshCount();
1367                                 
1368                                 // this adds the vertices to the display list
1369                                 for (int m=0;m<nummeshes;m++)
1370                                         (gameobj->GetMesh(m))->SchedulePolygons(rasty->GetDrawingMode());
1371                         }
1372
1373                         gameobj->SetCulled(!visible);
1374                         gameobj->UpdateBuckets(false);
1375                 }
1376         }
1377         if (node->Left())
1378                 MarkSubTreeVisible(node->Left(), rasty, visible, cam, layer);
1379         if (node->Right())
1380                 MarkSubTreeVisible(node->Right(), rasty, visible, cam, layer);
1381 }
1382
1383 void KX_Scene::MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj,KX_Camera*  cam,int layer)
1384 {
1385         // User (Python/Actuator) has forced object invisible...
1386         if (!gameobj->GetSGNode() || !gameobj->GetVisible())
1387                 return;
1388         
1389         // Shadow lamp layers
1390         if(layer && !(gameobj->GetLayer() & layer)) {
1391                 gameobj->SetCulled(true);
1392                 gameobj->UpdateBuckets(false);
1393                 return;
1394         }
1395
1396         // If Frustum culling is off, the object is always visible.
1397         bool vis = !cam->GetFrustumCulling();
1398         
1399         // If the camera is inside this node, then the object is visible.
1400         if (!vis)
1401         {
1402                 vis = gameobj->GetSGNode()->inside( cam->GetCameraLocation() );
1403         }
1404                 
1405         // Test the object's bound sphere against the view frustum.
1406         if (!vis)
1407         {
1408                 MT_Vector3 scale = gameobj->GetSGNode()->GetWorldScaling();
1409                 MT_Scalar radius = fabs(scale[scale.closestAxis()] * gameobj->GetSGNode()->Radius());
1410                 switch (cam->SphereInsideFrustum(gameobj->NodeGetWorldPosition(), radius))
1411                 {
1412                         case KX_Camera::INSIDE:
1413                                 vis = true;
1414                                 break;
1415                         case KX_Camera::OUTSIDE:
1416                                 vis = false;
1417                                 break;
1418                         case KX_Camera::INTERSECT:
1419                                 // Test the object's bound box against the view frustum.
1420                                 MT_Point3 box[8];
1421                                 gameobj->GetSGNode()->getBBox(box); 
1422                                 vis = cam->BoxInsideFrustum(box) != KX_Camera::OUTSIDE;
1423                                 break;
1424                 }
1425         }
1426         
1427         if (vis)
1428         {
1429                 int nummeshes = gameobj->GetMeshCount();
1430                 
1431                 for (int m=0;m<nummeshes;m++)
1432                 {
1433                         // this adds the vertices to the display list
1434                         (gameobj->GetMesh(m))->SchedulePolygons(rasty->GetDrawingMode());
1435                 }
1436                 // Visibility/ non-visibility are marked
1437                 // elsewhere now.
1438                 gameobj->SetCulled(false);
1439                 gameobj->UpdateBuckets(false);
1440         } else {
1441                 gameobj->SetCulled(true);
1442                 gameobj->UpdateBuckets(false);
1443         }
1444 }
1445
1446 void KX_Scene::PhysicsCullingCallback(KX_ClientObjectInfo* objectInfo, void* cullingInfo)
1447 {
1448         KX_GameObject* gameobj = objectInfo->m_gameobject;
1449         if (!gameobj->GetVisible())
1450                 // ideally, invisible objects should be removed from the culling tree temporarily
1451                 return;
1452         if(((CullingInfo*)cullingInfo)->m_layer && !(gameobj->GetLayer() & ((CullingInfo*)cullingInfo)->m_layer))
1453                 // used for shadow: object is not in shadow layer
1454                 return;
1455
1456         // make object visible
1457         gameobj->SetCulled(false);
1458         gameobj->UpdateBuckets(false);
1459 }
1460
1461 void KX_Scene::CalculateVisibleMeshes(RAS_IRasterizer* rasty,KX_Camera* cam, int layer)
1462 {
1463         bool dbvt_culling = false;
1464         if (m_dbvt_culling) 
1465         {
1466                 // test culling through Bullet
1467                 PHY__Vector4 planes[6];
1468                 // get the clip planes
1469                 MT_Vector4* cplanes = cam->GetNormalizedClipPlanes();
1470                 // and convert
1471                 planes[0].setValue(cplanes[4].getValue());      // near
1472                 planes[1].setValue(cplanes[5].getValue());      // far
1473                 planes[2].setValue(cplanes[0].getValue());      // left
1474                 planes[3].setValue(cplanes[1].getValue());      // right
1475                 planes[4].setValue(cplanes[2].getValue());      // top
1476                 planes[5].setValue(cplanes[3].getValue());      // bottom
1477                 CullingInfo info(layer);
1478                 dbvt_culling = m_physicsEnvironment->cullingTest(PhysicsCullingCallback,&info,planes,5,m_dbvt_occlusion_res);
1479         }
1480         if (!dbvt_culling) {
1481                 // the physics engine couldn't help us, do it the hard way
1482                 for (int i = 0; i < m_objectlist->GetCount(); i++)
1483                 {
1484                         MarkVisible(rasty, static_cast<KX_GameObject*>(m_objectlist->GetValue(i)), cam, layer);
1485                 }
1486         }
1487 }
1488
1489 // logic stuff
1490 void KX_Scene::LogicBeginFrame(double curtime)
1491 {
1492         // have a look at temp objects ...
1493         int lastobj = m_tempObjectList->GetCount() - 1;
1494         
1495         for (int i = lastobj; i >= 0; i--)
1496         {
1497                 CValue* objval = m_tempObjectList->GetValue(i);
1498                 CFloatValue* propval = (CFloatValue*) objval->GetProperty("::timebomb");
1499                 
1500                 if (propval)
1501                 {
1502                         float timeleft = propval->GetNumber() - 1.0/KX_KetsjiEngine::GetTicRate();
1503                         
1504                         if (timeleft > 0)
1505                         {
1506                                 propval->SetFloat(timeleft);
1507                         }
1508                         else
1509                         {
1510                                 DelayedRemoveObject(objval);
1511                                 // remove obj
1512                         }
1513                 }
1514                 else
1515                 {
1516                         // all object is the tempObjectList should have a clock
1517                 }
1518         }
1519         m_logicmgr->BeginFrame(curtime, 1.0/KX_KetsjiEngine::GetTicRate());
1520 }
1521
1522
1523
1524 void KX_Scene::LogicUpdateFrame(double curtime, bool frame)
1525 {
1526         m_logicmgr->UpdateFrame(curtime, frame);
1527 }
1528
1529
1530
1531 void KX_Scene::LogicEndFrame()
1532 {
1533         m_logicmgr->EndFrame();
1534         int numobj;
1535
1536         KX_GameObject* obj;
1537
1538         while ((numobj = m_euthanasyobjects->GetCount()) > 0)
1539         {
1540                 // remove the object from this list to make sure we will not hit it again
1541                 obj = (KX_GameObject*)m_euthanasyobjects->GetValue(numobj-1);
1542                 m_euthanasyobjects->Remove(numobj-1);
1543                 obj->Release();
1544                 RemoveObject(obj);
1545         }
1546
1547         //prepare obstacle simulation for new frame
1548         if (m_obstacleSimulation)
1549                 m_obstacleSimulation->UpdateObstacles();
1550 }
1551
1552
1553
1554 /**
1555   * UpdateParents: SceneGraph transformation update.
1556   */
1557 void KX_Scene::UpdateParents(double curtime)
1558 {
1559         // we use the SG dynamic list
1560         SG_Node* node;
1561
1562         while ((node = SG_Node::GetNextScheduled(m_sghead)) != NULL)
1563         {
1564                 node->UpdateWorldData(curtime);
1565         }
1566
1567         //for (int i=0; i<GetRootParentList()->GetCount(); i++)
1568         //{
1569         //      KX_GameObject* parentobj = (KX_GameObject*)GetRootParentList()->GetValue(i);
1570         //      parentobj->NodeUpdateGS(curtime);
1571         //}
1572
1573         // the list must be empty here
1574         assert(m_sghead.Empty());
1575         // some nodes may be ready for reschedule, move them to schedule list for next time
1576         while ((node = SG_Node::GetNextRescheduled(m_sghead)) != NULL)
1577         {
1578                 node->Schedule(m_sghead);
1579         }
1580 }
1581
1582
1583 RAS_MaterialBucket* KX_Scene::FindBucket(class RAS_IPolyMaterial* polymat, bool &bucketCreated)
1584 {
1585         return m_bucketmanager->FindBucket(polymat, bucketCreated);
1586 }
1587
1588
1589
1590 void KX_Scene::RenderBuckets(const MT_Transform & cameratransform,
1591                                                          class RAS_IRasterizer* rasty,
1592                                                          class RAS_IRenderTools* rendertools)
1593 {
1594         m_bucketmanager->Renderbuckets(cameratransform,rasty,rendertools);
1595         KX_BlenderMaterial::EndFrame();
1596 }
1597
1598 void KX_Scene::UpdateObjectActivity(void) 
1599 {
1600         if (m_activity_culling) {
1601                 /* determine the activity criterium and set objects accordingly */
1602                 int i=0;
1603                 
1604                 MT_Point3 camloc = GetActiveCamera()->NodeGetWorldPosition(); //GetCameraLocation();
1605                 
1606                 for (i=0;i<GetObjectList()->GetCount();i++)
1607                 {
1608                         KX_GameObject* ob = (KX_GameObject*) GetObjectList()->GetValue(i);
1609                         
1610                         if (!ob->GetIgnoreActivityCulling()) {
1611                                 /* Simple test: more than 10 away from the camera, count
1612                                  * Manhattan distance. */
1613                                 MT_Point3 obpos = ob->NodeGetWorldPosition();
1614                                 
1615                                 if ( (fabs(camloc[0] - obpos[0]) > m_activity_box_radius)
1616                                          || (fabs(camloc[1] - obpos[1]) > m_activity_box_radius)
1617                                          || (fabs(camloc[2] - obpos[2]) > m_activity_box_radius) )
1618                                 {                       
1619                                         ob->Suspend();
1620                                 } else {
1621                                         ob->Resume();
1622                                 }
1623                         }
1624                 }               
1625         }
1626 }
1627
1628 void KX_Scene::SetActivityCullingRadius(float f)
1629 {
1630         if (f < 0.5)
1631                 f = 0.5;
1632         m_activity_box_radius = f;
1633 }
1634         
1635 NG_NetworkDeviceInterface* KX_Scene::GetNetworkDeviceInterface()
1636 {
1637         return m_networkDeviceInterface;
1638 }
1639
1640 NG_NetworkScene* KX_Scene::GetNetworkScene()
1641 {
1642         return m_networkScene;
1643 }
1644
1645 void KX_Scene::SetNetworkDeviceInterface(NG_NetworkDeviceInterface* newInterface)
1646 {
1647         m_networkDeviceInterface = newInterface;
1648 }
1649
1650 void KX_Scene::SetNetworkScene(NG_NetworkScene *newScene)
1651 {
1652         m_networkScene = newScene;
1653 }
1654
1655
1656 void    KX_Scene::SetGravity(const MT_Vector3& gravity)
1657 {
1658         GetPhysicsEnvironment()->setGravity(gravity[0],gravity[1],gravity[2]);
1659 }
1660
1661 void KX_Scene::SetSceneConverter(class KX_BlenderSceneConverter* sceneConverter)
1662 {
1663         m_sceneConverter = sceneConverter;
1664 }
1665
1666 void KX_Scene::SetPhysicsEnvironment(class PHY_IPhysicsEnvironment* physEnv)
1667 {
1668         m_physicsEnvironment = physEnv;
1669         if(m_physicsEnvironment) {
1670                 KX_TouchEventManager* touchmgr = new KX_TouchEventManager(m_logicmgr, physEnv);
1671                 m_logicmgr->RegisterEventManager(touchmgr);
1672         }
1673 }
1674  
1675 void KX_Scene::setSuspendedTime(double suspendedtime)
1676 {
1677         m_suspendedtime = suspendedtime;
1678 }
1679 double KX_Scene::getSuspendedTime()
1680 {
1681         return m_suspendedtime;
1682 }
1683 void KX_Scene::setSuspendedDelta(double suspendeddelta)
1684 {
1685         m_suspendeddelta = suspendeddelta;
1686 }
1687 double KX_Scene::getSuspendedDelta()
1688 {
1689         return m_suspendeddelta;
1690 }
1691
1692 #ifdef USE_BULLET
1693 #include "KX_BulletPhysicsController.h"
1694 #endif
1695
1696 static void MergeScene_LogicBrick(SCA_ILogicBrick* brick, KX_Scene *to)
1697 {
1698         SCA_LogicManager *logicmgr= to->GetLogicManager();
1699
1700         brick->Replace_IScene(to);
1701         brick->Replace_NetworkScene(to->GetNetworkScene());
1702
1703         SCA_ISensor *sensor=  dynamic_cast<class SCA_ISensor *>(brick);
1704         if(sensor) {
1705                 sensor->Replace_EventManager(logicmgr);
1706         }
1707
1708         /* near sensors have physics controllers */
1709 #ifdef USE_BULLET
1710         KX_TouchSensor *touch_sensor = dynamic_cast<class KX_TouchSensor *>(brick);
1711         if(touch_sensor) {
1712                 touch_sensor->GetPhysicsController()->SetPhysicsEnvironment(to->GetPhysicsEnvironment());
1713         }
1714 #endif
1715 }
1716
1717 #ifdef USE_BULLET
1718 #include "CcdGraphicController.h" // XXX  ctrl->SetPhysicsEnvironment(to->GetPhysicsEnvironment());
1719 #include "CcdPhysicsEnvironment.h" // XXX  ctrl->SetPhysicsEnvironment(to->GetPhysicsEnvironment());
1720 #include "KX_BulletPhysicsController.h"
1721 #endif
1722
1723 static void MergeScene_GameObject(KX_GameObject* gameobj, KX_Scene *to, KX_Scene *from)
1724 {
1725         {
1726                 SCA_ActuatorList& actuators= gameobj->GetActuators();
1727                 SCA_ActuatorList::iterator ita;
1728
1729                 for (ita = actuators.begin(); !(ita==actuators.end()); ++ita)
1730                 {
1731                         MergeScene_LogicBrick(*ita, to);
1732                 }
1733         }
1734
1735
1736         {
1737                 SCA_SensorList& sensors= gameobj->GetSensors();
1738                 SCA_SensorList::iterator its;
1739
1740                 for (its = sensors.begin(); !(its==sensors.end()); ++its)
1741                 {
1742                         MergeScene_LogicBrick(*its, to);
1743                 }
1744         }
1745
1746         {
1747                 SCA_ControllerList& controllers= gameobj->GetControllers();
1748                 SCA_ControllerList::iterator itc;
1749
1750                 for (itc = controllers.begin(); !(itc==controllers.end()); ++itc)
1751                 {
1752                         SCA_IController *cont= *itc;
1753                         MergeScene_LogicBrick(cont, to);
1754
1755                         vector<SCA_ISensor*> linkedsensors = cont->GetLinkedSensors();
1756                         vector<SCA_IActuator*> linkedactuators = cont->GetLinkedActuators();
1757
1758                         for (vector<SCA_IActuator*>::iterator ita = linkedactuators.begin();!(ita==linkedactuators.end());++ita) {
1759                                 MergeScene_LogicBrick(*ita, to);
1760                         }
1761
1762                         for (vector<SCA_ISensor*>::iterator its = linkedsensors.begin();!(its==linkedsensors.end());++its) {
1763                                 MergeScene_LogicBrick(*its, to);
1764                         }
1765                 }
1766         }
1767
1768         /* graphics controller */
1769         PHY_IGraphicController *ctrl = gameobj->GetGraphicController();
1770         if(ctrl) {
1771                 /* SHOULD update the m_cullingTree */
1772                 ctrl->SetPhysicsEnvironment(to->GetPhysicsEnvironment());
1773         }
1774
1775         /* SG_Node can hold a scene reference */
1776         SG_Node *sg= gameobj->GetSGNode();
1777         if(sg) {
1778                 if(sg->GetSGClientInfo() == from) {
1779                         sg->SetSGClientInfo(to);
1780
1781                         /* Make sure to grab the children too since they might not be tied to a game object */
1782                         NodeList children = sg->GetSGChildren();
1783                         for (int i=0; i<children.size(); i++)
1784                                         children[i]->SetSGClientInfo(to);
1785                 }
1786 #ifdef USE_BULLET
1787                 SGControllerList::iterator contit;
1788                 SGControllerList& controllers = sg->GetSGControllerList();
1789                 for (contit = controllers.begin();contit!=controllers.end();++contit)
1790                 {
1791                         KX_BulletPhysicsController *phys_ctrl= dynamic_cast<KX_BulletPhysicsController *>(*contit);
1792                         if (phys_ctrl)
1793                                 phys_ctrl->SetPhysicsEnvironment(to->GetPhysicsEnvironment());
1794                 }
1795 #endif // USE_BULLET
1796         }
1797         /* If the object is a light, update it's scene */
1798         if (gameobj->GetGameObjectType() == SCA_IObject::OBJ_LIGHT)
1799                 ((KX_LightObject*)gameobj)->UpdateScene(to);
1800
1801         /* Add the object to the scene's logic manager */
1802         to->GetLogicManager()->RegisterGameObjectName(gameobj->GetName(), gameobj);
1803         to->GetLogicManager()->RegisterGameObj(gameobj->GetBlenderObject(), gameobj);
1804
1805         for (int i=0; i<gameobj->GetMeshCount(); ++i)
1806                 to->GetLogicManager()->RegisterGameMeshName(gameobj->GetMesh(i)->GetName(), gameobj->GetBlenderObject());
1807 }
1808
1809 bool KX_Scene::MergeScene(KX_Scene *other)
1810 {
1811 #ifdef USE_BULLET
1812         CcdPhysicsEnvironment *env=                     dynamic_cast<CcdPhysicsEnvironment *>(this->GetPhysicsEnvironment());
1813         CcdPhysicsEnvironment *env_other=       dynamic_cast<CcdPhysicsEnvironment *>(other->GetPhysicsEnvironment());
1814
1815         if((env==NULL) != (env_other==NULL)) /* TODO - even when both scenes have NONE physics, the other is loaded with bullet enabled, ??? */
1816         {
1817                 printf("KX_Scene::MergeScene: physics scenes type differ, aborting\n");
1818                 printf("\tsource %d, terget %d\n", (int)(env!=NULL), (int)(env_other!=NULL));
1819                 return false;
1820         }
1821 #endif // USE_BULLET
1822
1823         if(GetSceneConverter() != other->GetSceneConverter()) {
1824                 printf("KX_Scene::MergeScene: converters differ, aborting\n");
1825                 return false;
1826         }
1827
1828
1829         GetBucketManager()->MergeBucketManager(other->GetBucketManager(), this);
1830
1831         /* move materials across, assume they both use the same scene-converters */
1832         GetSceneConverter()->MergeScene(this, other);
1833
1834         /* active + inactive == all ??? - lets hope so */
1835         for (int i = 0; i < other->GetObjectList()->GetCount(); i++)
1836         {
1837                 KX_GameObject* gameobj = (KX_GameObject*)other->GetObjectList()->GetValue(i);
1838                 MergeScene_GameObject(gameobj, this, other);
1839
1840                 gameobj->UpdateBuckets(false); /* only for active objects */
1841         }
1842
1843         for (int i = 0; i < other->GetInactiveList()->GetCount(); i++)
1844         {
1845                 KX_GameObject* gameobj = (KX_GameObject*)other->GetInactiveList()->GetValue(i);
1846                 MergeScene_GameObject(gameobj, this, other);
1847         }
1848
1849         GetTempObjectList()->MergeList(other->GetTempObjectList());
1850         other->GetTempObjectList()->ReleaseAndRemoveAll();
1851
1852         GetObjectList()->MergeList(other->GetObjectList());
1853         other->GetObjectList()->ReleaseAndRemoveAll();
1854
1855         GetInactiveList()->MergeList(other->GetInactiveList());
1856         other->GetInactiveList()->ReleaseAndRemoveAll();
1857
1858         GetRootParentList()->MergeList(other->GetRootParentList());
1859         other->GetRootParentList()->ReleaseAndRemoveAll();
1860
1861         GetLightList()->MergeList(other->GetLightList());
1862         other->GetLightList()->ReleaseAndRemoveAll();
1863
1864 #ifdef USE_BULLET
1865         if(env) /* bullet scene? - dummy scenes dont need touching */
1866                 env->MergeEnvironment(env_other);
1867 #endif
1868         
1869         /* merge logic */
1870         {
1871                 SCA_LogicManager *logicmgr=                     GetLogicManager();
1872                 SCA_LogicManager *logicmgr_other=       other->GetLogicManager();
1873
1874                 vector<class SCA_EventManager*>evtmgrs= logicmgr->GetEventManagers();
1875                 //vector<class SCA_EventManager*>evtmgrs_others= logicmgr_other->GetEventManagers();
1876
1877                 //SCA_EventManager *evtmgr;
1878                 SCA_EventManager *evtmgr_other;
1879
1880                 for(unsigned int i= 0; i < evtmgrs.size(); i++) {
1881                         evtmgr_other= logicmgr_other->FindEventManager(evtmgrs[i]->GetType());
1882
1883                         if(evtmgr_other) /* unlikely but possible one scene has a joystick and not the other */
1884                                 evtmgr_other->Replace_LogicManager(logicmgr);
1885
1886                         /* when merging objects sensors are moved across into the new manager, dont need to do this here */
1887                 }
1888
1889                 /* grab any timer properties from the other scene */
1890                 SCA_TimeEventManager *timemgr=          GetTimeEventManager();
1891                 SCA_TimeEventManager *timemgr_other=    other->GetTimeEventManager();
1892                 vector<CValue*> times = timemgr_other->GetTimeValues();
1893
1894                 for(unsigned int i= 0; i < times.size(); i++) {
1895                         timemgr->AddTimeProperty(times[i]);
1896                 }
1897                 
1898         }
1899         return true;
1900 }
1901
1902 void KX_Scene::Update2DFilter(vector<STR_String>& propNames, void* gameObj, RAS_2DFilterManager::RAS_2DFILTER_MODE filtermode, int pass, STR_String& text)
1903 {
1904         m_filtermanager.EnableFilter(propNames, gameObj, filtermode, pass, text);
1905 }
1906
1907 void KX_Scene::Render2DFilters(RAS_ICanvas* canvas)
1908 {
1909         m_filtermanager.RenderFilters(canvas);
1910 }
1911
1912 #ifdef WITH_PYTHON
1913
1914 void KX_Scene::RunDrawingCallbacks(PyObject* cb_list)
1915 {
1916         int len;
1917
1918         if (cb_list && (len=PyList_GET_SIZE(cb_list)))
1919         {
1920                 PyObject* args= PyTuple_New(0); // save python creating each call
1921                 PyObject* func;
1922                 PyObject* ret;
1923
1924                 // Iterate the list and run the callbacks
1925                 for (int pos=0; pos < len; pos++)
1926                 {
1927                         func= PyList_GET_ITEM(cb_list, pos);
1928                         ret= PyObject_Call(func, args, NULL);
1929                         if (ret==NULL) {
1930                                 PyErr_Print();
1931                                 PyErr_Clear();
1932                         }
1933                         else {
1934                                 Py_DECREF(ret);
1935                         }
1936                 }
1937
1938                 Py_DECREF(args);
1939         }
1940 }
1941
1942 //----------------------------------------------------------------------------
1943 //Python
1944
1945 PyTypeObject KX_Scene::Type = {
1946         PyVarObject_HEAD_INIT(NULL, 0)
1947         "KX_Scene",
1948         sizeof(PyObjectPlus_Proxy),
1949         0,
1950         py_base_dealloc,
1951         0,
1952         0,
1953         0,
1954         0,
1955         py_base_repr,
1956         0,
1957         &Sequence,
1958         &Mapping,
1959         0,0,0,0,0,0,
1960         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
1961         0,0,0,0,0,0,0,
1962         Methods,
1963         0,
1964         0,
1965         &CValue::Type,
1966         0,0,0,0,0,0,
1967         py_base_new
1968 };
1969
1970 PyMethodDef KX_Scene::Methods[] = {
1971         KX_PYMETHODTABLE(KX_Scene, addObject),
1972         KX_PYMETHODTABLE(KX_Scene, end),
1973         KX_PYMETHODTABLE(KX_Scene, restart),
1974         KX_PYMETHODTABLE(KX_Scene, replace),
1975         KX_PYMETHODTABLE(KX_Scene, suspend),
1976         KX_PYMETHODTABLE(KX_Scene, resume),
1977         KX_PYMETHODTABLE(KX_Scene, drawObstacleSimulation),
1978
1979         
1980         /* dict style access */
1981         KX_PYMETHODTABLE(KX_Scene, get),
1982         
1983         {NULL,NULL} //Sentinel
1984 };
1985 static PyObject *Map_GetItem(PyObject *self_v, PyObject *item)
1986 {
1987         KX_Scene* self= static_cast<KX_Scene*>BGE_PROXY_REF(self_v);
1988         const char *attr_str= _PyUnicode_AsString(item);
1989         PyObject* pyconvert;
1990         
1991         if (self==NULL) {
1992                 PyErr_SetString(PyExc_SystemError, "val = scene[key]: KX_Scene, "BGE_PROXY_ERROR_MSG);
1993                 return NULL;
1994         }
1995         
1996         if (self->m_attr_dict && (pyconvert=PyDict_GetItem(self->m_attr_dict, item))) {
1997                 
1998                 if (attr_str)
1999                         PyErr_Clear();
2000                 Py_INCREF(pyconvert);
2001                 return pyconvert;
2002         }
2003         else {
2004                 if(attr_str)    PyErr_Format(PyExc_KeyError, "value = scene[key]: KX_Scene, key \"%s\" does not exist", attr_str);
2005                 else                    PyErr_SetString(PyExc_KeyError, "value = scene[key]: KX_Scene, key does not exist");
2006                 return NULL;
2007         }
2008                 
2009 }
2010
2011 static int Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val)
2012 {
2013         KX_Scene* self= static_cast<KX_Scene*>BGE_PROXY_REF(self_v);
2014         const char *attr_str= _PyUnicode_AsString(key);
2015         if(attr_str==NULL)
2016                 PyErr_Clear();
2017         
2018         if (self==NULL) {
2019                 PyErr_SetString(PyExc_SystemError, "scene[key] = value: KX_Scene, "BGE_PROXY_ERROR_MSG);
2020                 return -1;
2021         }
2022         
2023         if (val==NULL) { /* del ob["key"] */
2024                 int del= 0;
2025                 
2026                 if(self->m_attr_dict)
2027                         del |= (PyDict_DelItem(self->m_attr_dict, key)==0) ? 1:0;
2028                 
2029                 if (del==0) {
2030                         if(attr_str)    PyErr_Format(PyExc_KeyError, "scene[key] = value: KX_Scene, key \"%s\" could not be set", attr_str);
2031                         else                    PyErr_SetString(PyExc_KeyError, "del scene[key]: KX_Scene, key could not be deleted");
2032                         return -1;
2033                 }
2034                 else if (self->m_attr_dict) {
2035                         PyErr_Clear(); /* PyDict_DelItem sets an error when it fails */
2036                 }
2037         }
2038         else { /* ob["key"] = value */
2039                 int set = 0;
2040
2041                 if (self->m_attr_dict==NULL) /* lazy init */
2042                         self->m_attr_dict= PyDict_New();
2043                 
2044                 
2045                 if(PyDict_SetItem(self->m_attr_dict, key, val)==0)
2046                         set= 1;
2047                 else
2048                         PyErr_SetString(PyExc_KeyError, "scene[key] = value: KX_Scene, key not be added to internal dictionary");
2049         
2050                 if(set==0)
2051                         return -1; /* pythons error value */
2052                 
2053         }
2054         
2055         return 0; /* success */
2056 }
2057
2058 static int Seq_Contains(PyObject *self_v, PyObject *value)
2059 {
2060         KX_Scene* self= static_cast<KX_Scene*>BGE_PROXY_REF(self_v);
2061         
2062         if (self==NULL) {
2063                 PyErr_SetString(PyExc_SystemError, "val in scene: KX_Scene, "BGE_PROXY_ERROR_MSG);
2064                 return -1;
2065         }
2066         
2067         if (self->m_attr_dict && PyDict_GetItem(self->m_attr_dict, value))
2068                 return 1;
2069         
2070         return 0;
2071 }
2072
2073 PyMappingMethods KX_Scene::Mapping = {
2074         (lenfunc)NULL                                   ,                       /*inquiry mp_length */
2075         (binaryfunc)Map_GetItem,                /*binaryfunc mp_subscript */
2076         (objobjargproc)Map_SetItem,     /*objobjargproc mp_ass_subscript */
2077 };
2078
2079 PySequenceMethods KX_Scene::Sequence = {
2080         NULL,           /* Cant set the len otherwise it can evaluate as false */
2081         NULL,           /* sq_concat */
2082         NULL,           /* sq_repeat */
2083         NULL,           /* sq_item */
2084         NULL,           /* sq_slice */
2085         NULL,           /* sq_ass_item */
2086         NULL,           /* sq_ass_slice */
2087         (objobjproc)Seq_Contains,       /* sq_contains */
2088         (binaryfunc) NULL, /* sq_inplace_concat */
2089         (ssizeargfunc) NULL, /* sq_inplace_repeat */
2090 };
2091
2092 PyObject* KX_Scene::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2093 {
2094         KX_Scene* self= static_cast<KX_Scene*>(self_v);
2095         return PyUnicode_FromString(self->GetName().ReadPtr());
2096 }
2097
2098 PyObject* KX_Scene::pyattr_get_objects(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2099 {
2100         KX_Scene* self= static_cast<KX_Scene*>(self_v);
2101         return self->GetObjectList()->GetProxy();
2102 }
2103
2104 PyObject* KX_Scene::pyattr_get_objects_inactive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2105 {
2106         KX_Scene* self= static_cast<KX_Scene*>(self_v);
2107         return self->GetInactiveList()->GetProxy();
2108 }
2109
2110 PyObject* KX_Scene::pyattr_get_lights(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2111 {
2112         KX_Scene* self= static_cast<KX_Scene*>(self_v);
2113         return self->GetLightList()->GetProxy();
2114 }
2115
2116 PyObject* KX_Scene::pyattr_get_cameras(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2117 {
2118         /* With refcounts in this case...
2119          * the new CListValue is owned by python, so its possible python holds onto it longer then the BGE
2120          * however this is the same with "scene.objects + []", when you make a copy by adding lists.
2121          */
2122         
2123         KX_Scene* self= static_cast<KX_Scene*>(self_v);
2124         CListValue* clist = new CListValue();
2125         
2126         /* return self->GetCameras()->GetProxy(); */
2127         
2128         list<KX_Camera*>::iterator it = self->GetCameras()->begin();
2129         while (it != self->GetCameras()->end()) {
2130                 clist->Add((*it)->AddRef());
2131                 it++;
2132         }
2133         
2134         return clist->NewProxy(true);
2135 }
2136
2137 PyObject* KX_Scene::pyattr_get_active_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2138 {
2139         KX_Scene* self= static_cast<KX_Scene*>(self_v);
2140         return self->GetActiveCamera()->GetProxy();
2141 }
2142
2143
2144 int KX_Scene::pyattr_set_active_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2145 {
2146         KX_Scene* self= static_cast<KX_Scene*>(self_v);
2147         KX_Camera *camOb;
2148         
2149         if (!ConvertPythonToCamera(value, &camOb, false, "scene.active_camera = value: KX_Scene"))
2150                 return PY_SET_ATTR_FAIL;
2151         
2152         self->SetActiveCamera(camOb);
2153         return PY_SET_ATTR_SUCCESS;
2154 }
2155
2156 PyObject* KX_Scene::pyattr_get_drawing_callback_pre(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2157 {
2158         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2159
2160         if(self->m_draw_call_pre==NULL)
2161                 self->m_draw_call_pre= PyList_New(0);
2162         Py_INCREF(self->m_draw_call_pre);
2163         return self->m_draw_call_pre;
2164 }
2165
2166 PyObject* KX_Scene::pyattr_get_drawing_callback_post(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2167 {
2168         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2169
2170         if(self->m_draw_call_post==NULL)
2171                 self->m_draw_call_post= PyList_New(0);
2172         Py_INCREF(self->m_draw_call_post);
2173         return self->m_draw_call_post;
2174 }
2175
2176 int KX_Scene::pyattr_set_drawing_callback_pre(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2177 {
2178         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2179
2180         if (!PyList_CheckExact(value))
2181         {
2182                 PyErr_SetString(PyExc_ValueError, "Expected a list");
2183                 return PY_SET_ATTR_FAIL;
2184         }
2185         Py_XDECREF(self->m_draw_call_pre);
2186
2187         Py_INCREF(value);
2188         self->m_draw_call_pre = value;
2189
2190         return PY_SET_ATTR_SUCCESS;
2191 }
2192
2193 int KX_Scene::pyattr_set_drawing_callback_post(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2194 {
2195         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2196
2197         if (!PyList_CheckExact(value))
2198         {
2199                 PyErr_SetString(PyExc_ValueError, "Expected a list");
2200                 return PY_SET_ATTR_FAIL;
2201         }
2202         Py_XDECREF(self->m_draw_call_post);
2203
2204         Py_INCREF(value);
2205         self->m_draw_call_post = value;
2206
2207         return PY_SET_ATTR_SUCCESS;
2208 }
2209
2210 PyAttributeDef KX_Scene::Attributes[] = {
2211         KX_PYATTRIBUTE_RO_FUNCTION("name",                              KX_Scene, pyattr_get_name),
2212         KX_PYATTRIBUTE_RO_FUNCTION("objects",                   KX_Scene, pyattr_get_objects),
2213         KX_PYATTRIBUTE_RO_FUNCTION("objectsInactive",   KX_Scene, pyattr_get_objects_inactive),
2214         KX_PYATTRIBUTE_RO_FUNCTION("lights",                    KX_Scene, pyattr_get_lights),
2215         KX_PYATTRIBUTE_RO_FUNCTION("cameras",                   KX_Scene, pyattr_get_cameras),
2216         KX_PYATTRIBUTE_RO_FUNCTION("lights",                    KX_Scene, pyattr_get_lights),
2217         KX_PYATTRIBUTE_RW_FUNCTION("active_camera",             KX_Scene, pyattr_get_active_camera, pyattr_set_active_camera),
2218         KX_PYATTRIBUTE_RW_FUNCTION("pre_draw",                  KX_Scene, pyattr_get_drawing_callback_pre, pyattr_set_drawing_callback_pre),
2219         KX_PYATTRIBUTE_RW_FUNCTION("post_draw",                 KX_Scene, pyattr_get_drawing_callback_post, pyattr_set_drawing_callback_post),
2220         KX_PYATTRIBUTE_BOOL_RO("suspended",                             KX_Scene, m_suspend),
2221         KX_PYATTRIBUTE_BOOL_RO("activity_culling",              KX_Scene, m_activity_culling),
2222         KX_PYATTRIBUTE_FLOAT_RW("activity_culling_radius", 0.5f, FLT_MAX, KX_Scene, m_activity_box_radius),
2223         KX_PYATTRIBUTE_BOOL_RO("dbvt_culling",                  KX_Scene, m_dbvt_culling),
2224         { NULL }        //Sentinel
2225 };
2226
2227 KX_PYMETHODDEF_DOC(KX_Scene, addObject,
2228 "addObject(object, other, time=0)\n"
2229 "Returns the added object.\n")
2230 {
2231         PyObject *pyob, *pyother;
2232         KX_GameObject *ob, *other;
2233
2234         int time = 0;
2235
2236         if (!PyArg_ParseTuple(args, "OO|i:addObject", &pyob, &pyother, &time))
2237                 return NULL;
2238
2239         if (    !ConvertPythonToGameObject(pyob, &ob, false, "scene.addObject(object, other, time): KX_Scene (first argument)") ||
2240                         !ConvertPythonToGameObject(pyother, &other, false, "scene.addObject(object, other, time): KX_Scene (second argument)") )
2241                 return NULL;
2242
2243
2244         SCA_IObject* replica = AddReplicaObject((SCA_IObject*)ob, other, time);
2245         
2246         // release here because AddReplicaObject AddRef's
2247         // the object is added to the scene so we dont want python to own a reference
2248         replica->Release();
2249         return replica->GetProxy();
2250 }
2251
2252 KX_PYMETHODDEF_DOC(KX_Scene, end,
2253 "end()\n"
2254 "Removes this scene from the game.\n")
2255 {
2256         
2257         KX_GetActiveEngine()->RemoveScene(m_sceneName);
2258         
2259         Py_RETURN_NONE;
2260 }
2261
2262 KX_PYMETHODDEF_DOC(KX_Scene, restart,
2263                                    "restart()\n"
2264                                    "Restarts this scene.\n")
2265 {
2266         KX_GetActiveEngine()->ReplaceScene(m_sceneName, m_sceneName);
2267         
2268         Py_RETURN_NONE;
2269 }
2270
2271 KX_PYMETHODDEF_DOC(KX_Scene, replace,
2272                                    "replace(newScene)\n"
2273                                    "Replaces this scene with another one.\n")
2274 {
2275         char* name;
2276         
2277         if (!PyArg_ParseTuple(args, "s:replace", &name))
2278                 return NULL;
2279         
2280         KX_GetActiveEngine()->ReplaceScene(m_sceneName, name);
2281         
2282         Py_RETURN_NONE;
2283 }
2284
2285 KX_PYMETHODDEF_DOC(KX_Scene, suspend,
2286                                         "suspend()\n"
2287                                         "Suspends this scene.\n")
2288 {
2289         Suspend();
2290         
2291         Py_RETURN_NONE;
2292 }
2293
2294 KX_PYMETHODDEF_DOC(KX_Scene, resume,
2295                                         "resume()\n"
2296                                         "Resumes this scene.\n")
2297 {
2298         Resume();
2299         
2300         Py_RETURN_NONE;
2301 }
2302
2303 KX_PYMETHODDEF_DOC(KX_Scene, drawObstacleSimulation,
2304                                    "drawObstacleSimulation()\n"
2305                                    "Draw debug visualization of obstacle simulation.\n")
2306 {
2307         if (GetObstacleSimulation())
2308                 GetObstacleSimulation()->DrawObstacles();
2309
2310         Py_RETURN_NONE;
2311 }
2312
2313 /* Matches python dict.get(key, [default]) */
2314 KX_PYMETHODDEF_DOC(KX_Scene, get, "")
2315 {
2316         PyObject *key;
2317         PyObject* def = Py_None;
2318         PyObject* ret;
2319
2320         if (!PyArg_ParseTuple(args, "O|O:get", &key, &def))
2321                 return NULL;
2322         
2323         if (m_attr_dict && (ret=PyDict_GetItem(m_attr_dict, key))) {
2324                 Py_INCREF(ret);
2325                 return ret;
2326         }
2327         
2328         Py_INCREF(def);
2329         return def;
2330 }
2331
2332 #endif // WITH_PYTHON