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