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