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