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