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