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