Added Joystick sensor (from snailrose)
[blender.git] / source / gameengine / Ketsji / KX_Scene.cpp
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL/BL DUAL 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. The Blender
10  * Foundation also sells licenses for use in proprietary software under
11  * the Blender License.  See http://www.blender.org/BL/ for information
12  * about this.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
24  * All rights reserved.
25  *
26  * The Original Code is: all of this file.
27  *
28  * Contributor(s): none yet.
29  *
30  * ***** END GPL/BL DUAL LICENSE BLOCK *****
31  * Ketsji scene. Holds references to all scene data.
32  */
33
34 #ifdef HAVE_CONFIG_H
35 #include <config.h>
36 #endif
37
38 #ifdef WIN32
39 #pragma warning (disable : 4786)
40 #endif //WIN32
41
42 #include "MT_assert.h"
43
44 #include "KX_KetsjiEngine.h"
45 #include "RAS_IPolygonMaterial.h"
46 #include "KX_Scene.h"
47 #include "ListValue.h"
48 #include "SCA_LogicManager.h"
49 #include "SCA_TimeEventManager.h"
50 #include "SCA_AlwaysEventManager.h"
51 #include "SCA_RandomEventManager.h"
52 #include "KX_RayEventManager.h"
53 #include "KX_TouchEventManager.h"
54 #include "SCA_KeyboardManager.h"
55 #include "SCA_MouseManager.h"
56 #include "SCA_PropertyEventManager.h"
57 #include "KX_Camera.h"
58 #include "SCA_JoystickManager.h"
59
60 #include "RAS_MeshObject.h"
61 #include "RAS_IRasterizer.h"
62 #include "RAS_BucketManager.h"
63
64 #include "FloatValue.h"
65 #include "SCA_IController.h"
66 #include "SCA_IActuator.h"
67 #include "SG_Node.h"
68 #include "SYS_System.h"
69 #include "SG_Controller.h"
70 #include "SG_IObject.h"
71 #include "SG_Tree.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
80 #include "SM_Scene.h"
81 #include "SumoPhysicsEnvironment.h"
82
83 void* KX_SceneReplicationFunc(SG_IObject* node,void* gameobj,void* scene)
84 {
85         KX_GameObject* replica = ((KX_Scene*)scene)->AddNodeReplicaObject(node,(KX_GameObject*)gameobj);
86
87         return (void*)replica;
88 }
89
90 void* KX_SceneDestructionFunc(SG_IObject* node,void* gameobj,void* scene)
91 {
92         ((KX_Scene*)scene)->RemoveNodeDestructObject(node,(KX_GameObject*)gameobj);
93
94         return NULL;
95 };
96
97 SG_Callbacks KX_Scene::m_callbacks = SG_Callbacks(KX_SceneReplicationFunc,KX_SceneDestructionFunc,KX_GameObject::UpdateTransformFunc);
98
99 // temporarily var until there is a button in the userinterface
100 // (defined in KX_PythonInit.cpp)
101 extern bool gUseVisibilityTemp;
102
103 KX_Scene::KX_Scene(class SCA_IInputDevice* keyboarddevice,
104                                    class SCA_IInputDevice* mousedevice,
105                                    class NG_NetworkDeviceInterface *ndi,
106                                    class SND_IAudioDevice* adi,
107                                    const STR_String& sceneName): 
108         PyObjectPlus(&KX_Scene::Type),
109         m_keyboardmgr(NULL),
110         m_mousemgr(NULL),
111         m_physicsEnvironment(0),
112         m_sceneName(sceneName),
113         m_adi(adi),
114         m_networkDeviceInterface(ndi),
115         m_active_camera(NULL),
116         m_ueberExecutionPriority(0)
117 {
118                 
119
120         m_activity_culling = false;
121         m_suspend = false;
122         m_isclearingZbuffer = true;
123         m_tempObjectList = new CListValue();
124         m_objectlist = new CListValue();
125         m_parentlist = new CListValue();
126         m_lightlist= new CListValue();
127         m_euthanasyobjects = new CListValue();
128
129         m_logicmgr = new SCA_LogicManager();
130         
131         m_timemgr = new SCA_TimeEventManager(m_logicmgr);
132         m_keyboardmgr = new SCA_KeyboardManager(m_logicmgr,keyboarddevice);
133         m_mousemgr = new SCA_MouseManager(m_logicmgr,mousedevice);
134         
135         SCA_AlwaysEventManager* alwaysmgr = new SCA_AlwaysEventManager(m_logicmgr);
136         SCA_PropertyEventManager* propmgr = new SCA_PropertyEventManager(m_logicmgr);
137         SCA_RandomEventManager* rndmgr = new SCA_RandomEventManager(m_logicmgr);
138         KX_RayEventManager* raymgr = new KX_RayEventManager(m_logicmgr);
139
140         KX_NetworkEventManager* netmgr = new KX_NetworkEventManager(m_logicmgr, ndi);
141         
142         SCA_JoystickManager *joymgr     = new SCA_JoystickManager(m_logicmgr);
143
144         m_logicmgr->RegisterEventManager(alwaysmgr);
145         m_logicmgr->RegisterEventManager(propmgr);
146         m_logicmgr->RegisterEventManager(m_keyboardmgr);
147         m_logicmgr->RegisterEventManager(m_mousemgr);
148         m_logicmgr->RegisterEventManager(m_timemgr);
149         m_logicmgr->RegisterEventManager(rndmgr);
150         m_logicmgr->RegisterEventManager(raymgr);
151         m_logicmgr->RegisterEventManager(netmgr);
152         m_logicmgr->RegisterEventManager(joymgr);
153
154         m_soundScene = new SND_Scene(adi);
155         MT_assert (m_networkDeviceInterface != NULL);
156         m_networkScene = new NG_NetworkScene(m_networkDeviceInterface);
157         
158         m_rootnode = NULL;
159
160         m_bucketmanager=new RAS_BucketManager();
161
162         m_canvasDesignWidth = 0;
163         m_canvasDesignHeight = 0;
164         
165         m_attrlist = PyDict_New(); /* new ref */
166 }
167
168
169
170 KX_Scene::~KX_Scene()
171 {
172         
173 //      int numobj = m_objectlist->GetCount();
174
175         //int numrootobjects = GetRootParentList()->GetCount();
176         for (int i = 0; i < GetRootParentList()->GetCount(); i++)
177         {
178                 KX_GameObject* parentobj = (KX_GameObject*) GetRootParentList()->GetValue(i);
179                 this->RemoveObject(parentobj);
180         }
181
182         if(m_objectlist)
183                 m_objectlist->Release();
184         
185         if (m_parentlist)
186                 m_parentlist->Release();
187         
188         if (m_lightlist)
189                 m_lightlist->Release();
190         
191         if (m_tempObjectList)
192                 m_tempObjectList->Release();
193
194         if (m_euthanasyobjects)
195                 m_euthanasyobjects->Release();
196
197         if (m_logicmgr)
198                 delete m_logicmgr;
199
200         if (m_physicsEnvironment)
201                 delete m_physicsEnvironment;
202
203         if (m_soundScene)
204                 delete m_soundScene;
205
206         if (m_networkScene)
207                 delete m_networkScene;
208         
209         if (m_bucketmanager)
210         {
211                 delete m_bucketmanager;
212         }
213         Py_DECREF(m_attrlist);
214 }
215
216
217
218
219 void KX_Scene::SetProjectionMatrix(MT_CmMatrix4x4& pmat)
220 {
221         m_projectionmat = pmat;
222 }
223
224
225
226 RAS_BucketManager* KX_Scene::GetBucketManager()
227 {
228         return m_bucketmanager;
229 }
230
231
232
233 CListValue* KX_Scene::GetObjectList()
234 {
235         return m_objectlist;
236 }
237
238
239
240 CListValue* KX_Scene::GetRootParentList()
241 {
242         return m_parentlist;
243 }
244
245
246
247 CListValue* KX_Scene::GetLightList()
248 {
249         return m_lightlist;
250 }
251
252 SCA_LogicManager* KX_Scene::GetLogicManager()
253 {
254         return m_logicmgr;
255 }
256
257 SCA_TimeEventManager* KX_Scene::GetTimeEventManager()
258 {
259         return m_timemgr;
260 }
261
262
263
264
265 void KX_Scene::SetFramingType(RAS_FrameSettings & frame_settings)
266 {
267         m_frame_settings = frame_settings;
268 };
269
270 /**
271  * Return a const reference to the framing 
272  * type set by the above call.
273  * The contents are not guarenteed to be sensible
274  * if you don't call the above function.
275  */
276 const RAS_FrameSettings& KX_Scene::GetFramingType() const 
277 {
278         return m_frame_settings;
279 };      
280
281
282
283 /**
284  * Store the current scene's viewport on the 
285  * game engine canvas.
286  */
287 void KX_Scene::SetSceneViewport(const RAS_Rect &viewport)
288 {
289         m_viewport = viewport;
290 }
291
292
293
294 const RAS_Rect& KX_Scene::GetSceneViewport() const 
295 {
296         return m_viewport;
297 }
298
299
300
301 void KX_Scene::SetWorldInfo(class KX_WorldInfo* worldinfo)
302 {
303         m_worldinfo = worldinfo;
304 }
305
306
307
308 class KX_WorldInfo* KX_Scene::GetWorldInfo()
309 {
310         return m_worldinfo;
311 }
312
313
314
315 SND_Scene* KX_Scene::GetSoundScene()
316 {
317         return m_soundScene;
318 }
319
320 const STR_String& KX_Scene::GetName()
321 {
322         return m_sceneName;
323 }
324
325
326 void KX_Scene::Suspend()
327 {
328         m_suspend = true;
329 }
330
331 void KX_Scene::Resume()
332 {
333         m_suspend = false;
334 }
335
336 void KX_Scene::SetActivityCulling(bool b)
337 {
338         m_activity_culling = b;
339 }
340
341 bool KX_Scene::IsSuspended()
342 {
343         return m_suspend;
344 }
345
346 bool KX_Scene::IsClearingZBuffer()
347 {
348         return m_isclearingZbuffer;
349 }
350
351 void KX_Scene::EnableZBufferClearing(bool isclearingZbuffer)
352 {
353         m_isclearingZbuffer = isclearingZbuffer;
354 }
355
356 void KX_Scene::RemoveNodeDestructObject(class SG_IObject* node,class CValue* gameobj)
357 {
358         KX_GameObject* orgobj = (KX_GameObject*)gameobj;        
359         NewRemoveObject(orgobj);
360
361         if (node)
362                 delete node;
363 }
364
365 KX_GameObject* KX_Scene::AddNodeReplicaObject(class SG_IObject* node, class CValue* gameobj)
366 {
367         KX_GameObject* orgobj = (KX_GameObject*)gameobj;
368         KX_GameObject* newobj = (KX_GameObject*)orgobj->GetReplica();
369         m_map_gameobject_to_replica.insert(orgobj, newobj);
370
371         // also register 'timers' (time properties) of the replica
372         int numprops = newobj->GetPropertyCount();
373
374         for (int i = 0; i < numprops; i++)
375         {
376                 CValue* prop = newobj->GetProperty(i);
377
378                 if (prop->GetProperty("timer"))
379                         this->m_timemgr->AddTimeProperty(prop);
380         }
381
382         if (node)
383         {
384                 newobj->SetSGNode((SG_Node*)node);
385         }
386         else
387         {
388                 m_rootnode = new SG_Node(newobj,this,KX_Scene::m_callbacks);
389         
390                 // this fixes part of the scaling-added object bug
391                 SG_Node* orgnode = orgobj->GetSGNode();
392                 m_rootnode->SetLocalScale(orgnode->GetLocalScale());
393                 m_rootnode->SetLocalPosition(orgnode->GetLocalPosition());
394                 m_rootnode->SetLocalOrientation(orgnode->GetLocalOrientation());
395
396                 // define the relationship between this node and it's parent.
397                 KX_NormalParentRelation * parent_relation = 
398                         KX_NormalParentRelation::New();
399                 m_rootnode->SetParentRelation(parent_relation);
400
401                 newobj->SetSGNode(m_rootnode);
402         }
403         
404         SG_IObject* replicanode = newobj->GetSGNode();
405         SG_Node* rootnode = (replicanode == m_rootnode ? NULL : m_rootnode);
406
407         replicanode->SetSGClientObject(newobj);
408
409         // this is the list of object that are send to the graphics pipeline
410         m_objectlist->Add(newobj);
411         newobj->Bucketize();
412
413         // logic cannot be replicated, until the whole hierarchy is replicated.
414         m_logicHierarchicalGameObjects.push_back(newobj);
415         //replicate controllers of this node
416         SGControllerList        scenegraphcontrollers = orgobj->GetSGNode()->GetSGControllerList();
417         replicanode->RemoveAllControllers();
418         SGControllerList::iterator cit;
419         //int numcont = scenegraphcontrollers.size();
420         
421         for (cit = scenegraphcontrollers.begin();!(cit==scenegraphcontrollers.end());++cit)
422         {
423                 // controller replication is quite complicated
424                 // only replicate ipo and physics controller for now
425
426                 SG_Controller* replicacontroller = (*cit)->GetReplica((SG_Node*) replicanode);
427                 if (replicacontroller)
428                 {
429                         replicacontroller->SetObject(replicanode);
430                         replicanode->AddSGController(replicacontroller);
431                 }
432         }
433         
434         return newobj;
435 }
436
437
438
439 // before calling this method KX_Scene::ReplicateLogic(), make sure to
440 // have called 'GameObject::ReParentLogic' for each object this
441 // hierarchy that's because first ALL bricks must exist in the new
442 // replica of the hierarchy in order to make cross-links work properly
443 // !
444 void KX_Scene::ReplicateLogic(KX_GameObject* newobj)
445 {
446         // also relink the controller to sensors/actuators
447         SCA_ControllerList& controllers = newobj->GetControllers();
448         //SCA_SensorList&     sensors     = newobj->GetSensors();
449         //SCA_ActuatorList&   actuators   = newobj->GetActuators();
450
451         for (SCA_ControllerList::iterator itc = controllers.begin(); !(itc==controllers.end());itc++)
452         {
453                 SCA_IController* cont = (*itc);
454                 cont->SetUeberExecutePriority(m_ueberExecutionPriority);
455                 vector<SCA_ISensor*> linkedsensors = cont->GetLinkedSensors();
456                 vector<SCA_IActuator*> linkedactuators = cont->GetLinkedActuators();
457
458                 // disconnect the sensors and actuators
459                 cont->UnlinkAllSensors();
460                 cont->UnlinkAllActuators();
461                 
462                 // now relink each sensor
463                 for (vector<SCA_ISensor*>::iterator its = linkedsensors.begin();!(its==linkedsensors.end());its++)
464                 {
465                         SCA_ISensor* oldsensor = (*its);
466                         STR_String name = oldsensor->GetName();
467                         //find this name in the list
468                         SCA_ISensor* newsensor = newobj->FindSensor(name);
469                 
470                         if (newsensor)
471                         {
472                                 // relink this newsensor to the controller
473                                 m_logicmgr->RegisterToSensor(cont,newsensor);
474                         }
475                         else
476                         {
477                                 // it can be linked somewhere in the hierarchy or...
478                                 for (vector<KX_GameObject*>::iterator git = m_logicHierarchicalGameObjects.begin();
479                                 !(git==m_logicHierarchicalGameObjects.end());++git)
480                                 {
481                                         newsensor = (*git)->FindSensor(name);
482                                         if (newsensor)
483                                                 break;
484                                 } 
485
486                                 if (newsensor)
487                                 {
488                                         // relink this newsensor to the controller somewhere else within this
489                                         // hierarchy
490                                         m_logicmgr->RegisterToSensor(cont,newsensor);
491                                 }
492                                 else
493                                 {
494                                         // must be an external sensor, so...
495                                         m_logicmgr->RegisterToSensor(cont,oldsensor);
496                                 }
497                         }
498                 }
499                 
500                 // now relink each actuator
501                 for (vector<SCA_IActuator*>::iterator ita = linkedactuators.begin();!(ita==linkedactuators.end());ita++)
502                 {
503                         SCA_IActuator* oldactuator = (*ita);
504                         STR_String name = oldactuator->GetName();
505                         //find this name in the list
506                         SCA_IActuator* newactuator = newobj->FindActuator(name);
507                         if (newactuator)
508                         {
509                                 // relink this newsensor to the controller
510                                 m_logicmgr->RegisterToActuator(cont,newactuator);
511                                 newactuator->SetUeberExecutePriority(m_ueberExecutionPriority);
512                         }
513                         else
514                         {
515                                 // it can be linked somewhere in the hierarchy or...
516                                 for (vector<KX_GameObject*>::iterator git = m_logicHierarchicalGameObjects.begin();
517                                 !(git==m_logicHierarchicalGameObjects.end());++git)
518                                 {
519                                         newactuator= (*git)->FindActuator(name);
520                                         if (newactuator)
521                                                 break;
522                                 } 
523
524                                 if (newactuator)
525                                 {
526                                         // relink this actuator to the controller somewhere else within this
527                                         // hierarchy
528                                         m_logicmgr->RegisterToActuator(cont,newactuator);
529                                         newactuator->SetUeberExecutePriority(m_ueberExecutionPriority);
530                                 }
531                                 else
532                                 {
533                                         // must be an external actuator, so...
534                                         m_logicmgr->RegisterToActuator(cont,oldactuator);
535                                 }
536                         }
537                 }
538         }
539 }
540
541
542
543 SCA_IObject* KX_Scene::AddReplicaObject(class CValue* originalobject,
544                                                                                 class CValue* parentobject,
545                                                                                 int lifespan)
546 {
547
548         m_logicHierarchicalGameObjects.clear();
549         m_map_gameobject_to_replica.clear();
550
551         // todo: place a timebomb in the object, for temporarily objects :)
552         // lifespan of zero means 'this object lives forever'
553         KX_GameObject* originalobj = (KX_GameObject*) originalobject;
554         KX_GameObject* parentobj = (KX_GameObject*) parentobject;
555
556         m_ueberExecutionPriority++;
557
558         // lets create a replica
559         KX_GameObject* replica = (KX_GameObject*) AddNodeReplicaObject(NULL,originalobj);
560
561         if (lifespan > 0)
562         {
563                 // add a timebomb to this object
564                 // for now, convert between so called frames and realtime
565                 m_tempObjectList->Add(replica->AddRef());
566                 replica->SetProperty("::timebomb",new CFloatValue(lifespan*0.02));
567         }
568
569         // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame)
570         m_parentlist->Add(replica->AddRef());
571
572         // recurse replication into children nodes
573
574         NodeList& children = originalobj->GetSGNode()->GetSGChildren();
575
576         replica->GetSGNode()->ClearSGChildren();
577         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
578         {
579                 SG_Node* orgnode = (*childit);
580                 SG_Node* childreplicanode = orgnode->GetSGReplica();
581                 replica->GetSGNode()->AddChild(childreplicanode);
582         }
583
584         //      relink any pointers as necessary, sort of a temporary solution
585         vector<KX_GameObject*>::iterator git;
586         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
587         {
588                 (*git)->Relink(&m_map_gameobject_to_replica);
589         }
590
591         // now replicate logic
592         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
593         {
594                 (*git)->ReParentLogic();
595         }
596         
597         // replicate crosslinks etc. between logic bricks
598         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
599         {
600                 ReplicateLogic((*git));
601         }
602         
603         MT_Point3 newpos = ((KX_GameObject*) parentobject)->NodeGetWorldPosition();
604         replica->NodeSetLocalPosition(newpos);
605
606         MT_Matrix3x3 newori = ((KX_GameObject*) parentobject)->NodeGetWorldOrientation();
607         replica->NodeSetLocalOrientation(newori);
608         
609         // get the rootnode's scale
610         MT_Vector3 newscale = parentobj->GetSGNode()->GetRootSGParent()->GetLocalScale();
611
612         // set the replica's relative scale with the rootnode's scale
613         replica->NodeSetRelativeScale(newscale);
614
615         if (replica->GetPhysicsController())
616         {
617                 replica->GetPhysicsController()->setPosition(newpos);
618                 replica->GetPhysicsController()->setOrientation(newori.getRotation());
619                 replica->GetPhysicsController()->setScaling(newscale);
620         }
621
622         // here we want to set the relative scale: the rootnode's scale will override all other
623         // scalings, so lets better prepare for it
624
625
626         replica->GetSGNode()->UpdateWorldData(0);
627         replica->GetSGNode()->SetBBox(originalobj->GetSGNode()->BBox());
628         replica->GetSGNode()->SetRadius(originalobj->GetSGNode()->Radius());
629         
630         return replica;
631 }
632
633
634
635 void KX_Scene::RemoveObject(class CValue* gameobj)
636 {
637         KX_GameObject* newobj = (KX_GameObject*) gameobj;
638
639         // first disconnect child from parent
640         SG_Node* node = newobj->GetSGNode();
641
642         if (node)
643         {
644                 node->DisconnectFromParent();
645
646                 // recursively destruct
647                 node->Destruct();
648         }
649 }
650
651
652
653 void KX_Scene::DelayedRemoveObject(class CValue* gameobj)
654 {
655         //KX_GameObject* newobj = (KX_GameObject*) gameobj;
656         if (!m_euthanasyobjects->SearchValue(gameobj))
657         {
658                 m_euthanasyobjects->Add(gameobj->AddRef());
659         } 
660 }
661
662
663
664 void KX_Scene::NewRemoveObject(class CValue* gameobj)
665 {
666         KX_GameObject* newobj = (KX_GameObject*) gameobj;
667         //SM_Object* sumoObj = newobj->GetSumoObject();
668         //if (sumoObj)
669         //{
670         //      this->GetSumoScene()->remove(*sumoObj);
671         //}
672         // remove all sensors/controllers/actuators from logicsystem...
673         
674         SCA_SensorList& sensors = newobj->GetSensors();
675         for (SCA_SensorList::iterator its = sensors.begin();
676                  !(its==sensors.end());its++)
677         {
678                 m_logicmgr->RemoveSensor(*its);
679         }
680         
681     SCA_ControllerList& controllers = newobj->GetControllers();
682         for (SCA_ControllerList::iterator itc = controllers.begin();
683                  !(itc==controllers.end());itc++)
684         {
685                 (*itc)->UnlinkAllSensors();
686                 (*itc)->UnlinkAllActuators();
687         }
688
689         SCA_ActuatorList& actuators = newobj->GetActuators();
690         for (SCA_ActuatorList::iterator ita = actuators.begin();
691                  !(ita==actuators.end());ita++)
692         {
693                 m_logicmgr->RemoveDestroyedActuator(*ita);
694         }
695
696         // now remove the timer properties from the time manager
697         int numprops = newobj->GetPropertyCount();
698
699         for (int i = 0; i < numprops; i++)
700         {
701                 CValue* propval = newobj->GetProperty(i);
702                 if (propval->GetProperty("timer"))
703                 {
704                         m_timemgr->RemoveTimeProperty(propval);
705                 }
706         }
707         
708         newobj->RemoveMeshes();
709         if (m_objectlist->RemoveValue(newobj))
710                 newobj->Release();
711         if (m_tempObjectList->RemoveValue(newobj))
712                 newobj->Release();
713         if (m_parentlist->RemoveValue(newobj))
714                 newobj->Release();
715         if (m_euthanasyobjects->RemoveValue(newobj))
716                 newobj->Release();
717                 
718         if (newobj == m_active_camera)
719         {
720                 m_active_camera = NULL;
721         }
722 }
723
724
725
726 void KX_Scene::ReplaceMesh(class CValue* gameobj,void* meshobj)
727 {
728         KX_GameObject* newobj = (KX_GameObject*) gameobj;
729         newobj->RemoveMeshes();
730         newobj->AddMesh((RAS_MeshObject*)meshobj);
731         newobj->Bucketize();
732 }
733
734
735
736 MT_CmMatrix4x4& KX_Scene::GetViewMatrix()
737 {
738         MT_Scalar cammat[16];
739         m_active_camera->GetWorldToCamera().getValue(cammat);
740         m_viewmat = cammat;
741         return m_viewmat;
742 }
743
744
745
746 MT_CmMatrix4x4& KX_Scene::GetProjectionMatrix()
747 {
748         return m_projectionmat;
749 }
750
751
752 KX_Camera* KX_Scene::FindCamera(KX_Camera* cam)
753 {
754         set<KX_Camera*>::iterator it = m_cameras.begin();
755
756         while ( (it != m_cameras.end()) 
757                         && ((*it) != cam) ) {
758           it++;
759         }
760
761         return ((it == m_cameras.end()) ? NULL : (*it));
762 }
763
764
765 KX_Camera* KX_Scene::FindCamera(STR_String& name)
766 {
767         set<KX_Camera*>::iterator it = m_cameras.begin();
768
769         while ( (it != m_cameras.end()) 
770                         && ((*it)->GetName() != name) ) {
771           it++;
772         }
773
774         return ((it == m_cameras.end()) ? NULL : (*it));
775 }
776
777 void KX_Scene::AddCamera(KX_Camera* cam)
778 {
779         m_cameras.insert(cam);
780 }
781
782 KX_Camera* KX_Scene::GetActiveCamera()
783 {       
784         // NULL if not defined
785         return m_active_camera;
786 }
787
788
789 void KX_Scene::SetActiveCamera(KX_Camera* cam)
790 {
791         // only set if the cam is in the active list? Or add it otherwise?
792         if (!FindCamera(cam)){
793                 AddCamera(cam);
794                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
795         } 
796
797         m_active_camera = cam;
798 }
799
800
801
802 void KX_Scene::UpdateMeshTransformations()
803 {
804         // do this incrementally in the future
805         for (int i = 0; i < m_objectlist->GetCount(); i++)
806         {
807                 KX_GameObject* gameobj = (KX_GameObject*)m_objectlist->GetValue(i);
808                 gameobj->GetOpenGLMatrix();
809 //              gameobj->UpdateNonDynas();
810         }
811 }
812
813 void KX_Scene::MarkVisible(SG_Tree *node, RAS_IRasterizer* rasty)
814 {
815         int intersect = KX_Camera::INTERSECT;
816         KX_GameObject *gameobj = node->Client()?(KX_GameObject*) node->Client()->GetSGClientObject():NULL;
817         bool dotest = (gameobj && gameobj->GetVisible()) || node->Left() || node->Right();
818         
819         /* If the camera is inside the box, assume intersect. */
820         if (dotest && !node->inside(GetActiveCamera()->NodeGetWorldPosition()))
821         {
822                 MT_Scalar radius = node->Radius();
823                 MT_Point3 centre = node->Centre();
824                 
825                 intersect = GetActiveCamera()->SphereInsideFrustum(centre, radius); 
826                 
827                 if (intersect == KX_Camera::INTERSECT)
828                 {
829                         MT_Point3 box[8];
830                         node->get(box);
831                         intersect = GetActiveCamera()->BoxInsideFrustum(box);
832                 }
833         }
834
835         switch (intersect)
836         {
837                 case KX_Camera::OUTSIDE:
838                         MarkSubTreeVisible(node, rasty, false);
839                         break;
840                 case KX_Camera::INTERSECT:
841                         if (gameobj)
842                                 MarkVisible(rasty, gameobj);
843                         if (node->Left())
844                                 MarkVisible(node->Left(), rasty);
845                         if (node->Right())
846                                 MarkVisible(node->Right(), rasty);
847                         break;
848                 case KX_Camera::INSIDE:
849                         MarkSubTreeVisible(node, rasty, true);
850                         break;
851         }
852 }
853
854 void KX_Scene::MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool visible)
855 {
856         if (node->Client())
857         {
858                 KX_GameObject *gameobj = (KX_GameObject*) node->Client()->GetSGClientObject();
859                 if (gameobj->GetVisible())
860                 {
861                         if (visible)
862                         {
863                                 int nummeshes = gameobj->GetMeshCount();
864                                 MT_Transform t( GetActiveCamera()->GetWorldToCamera() * gameobj->GetSGNode()->GetWorldTransform());
865         
866                                 
867                                 for (int m=0;m<nummeshes;m++)
868                                 {
869                                         // this adds the vertices to the display list
870                                         (gameobj->GetMesh(m))->SchedulePolygons(t, rasty->GetDrawingMode());
871                                 }
872                         }
873                         gameobj->MarkVisible(visible);
874                 }
875         }
876         if (node->Left())
877                 MarkSubTreeVisible(node->Left(), rasty, visible);
878         if (node->Right())
879                 MarkSubTreeVisible(node->Right(), rasty, visible);
880 }
881
882 void KX_Scene::MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj)
883 {
884         // User (Python/Actuator) has forced object invisible...
885         if (!gameobj->GetVisible())
886                 return;
887         // If Frustum culling is off, the object is always visible.
888         bool vis = !GetActiveCamera()->GetFrustumCulling();
889         
890         // If the camera is inside this node, then the object is visible.
891         if (!vis)
892         {
893                 vis = gameobj->GetSGNode()->inside( GetActiveCamera()->GetCameraLocation() );
894         }
895                 
896         // Test the object's bound sphere against the view frustum.
897         if (!vis)
898         {
899                 MT_Vector3 scale = gameobj->GetSGNode()->GetWorldScaling();
900                 MT_Scalar radius = fabs(scale[scale.closestAxis()] * gameobj->GetSGNode()->Radius());
901                 switch (GetActiveCamera()->SphereInsideFrustum(gameobj->NodeGetWorldPosition(), radius))
902                 {
903                         case KX_Camera::INSIDE:
904                                 vis = true;
905                                 break;
906                         case KX_Camera::OUTSIDE:
907                                 vis = false;
908                                 break;
909                         case KX_Camera::INTERSECT:
910                                 // Test the object's bound box against the view frustum.
911                                 MT_Point3 box[8];
912                                 gameobj->GetSGNode()->getBBox(box); 
913                                 vis = GetActiveCamera()->BoxInsideFrustum(box) != KX_Camera::OUTSIDE;
914                                 break;
915                 }
916         }
917         
918         if (vis)
919         {
920                 int nummeshes = gameobj->GetMeshCount();
921                 MT_Transform t(GetActiveCamera()->GetWorldToCamera() * gameobj->GetSGNode()->GetWorldTransform());
922                 
923                 for (int m=0;m<nummeshes;m++)
924                 {
925                         // this adds the vertices to the display list
926                         (gameobj->GetMesh(m))->SchedulePolygons(t, rasty->GetDrawingMode());
927                 }
928                 // Visibility/ non-visibility are marked
929                 // elsewhere now.
930                 gameobj->MarkVisible();
931         } else {
932                 gameobj->MarkVisible(false);
933         }
934 }
935
936 void KX_Scene::CalculateVisibleMeshes(RAS_IRasterizer* rasty)
937 {
938 // FIXME: When tree is operational
939 #if 1
940         // do this incrementally in the future
941         for (int i = 0; i < m_objectlist->GetCount(); i++)
942         {
943                 MarkVisible(rasty, static_cast<KX_GameObject*>(m_objectlist->GetValue(i)));
944         }
945 #else
946         if (GetActiveCamera()->GetFrustumCulling())
947                 MarkVisible(m_objecttree, rasty);
948         else
949                 MarkSubTreeVisible(m_objecttree, rasty, true);
950 #endif
951 }
952
953 // logic stuff
954 void KX_Scene::LogicBeginFrame(double curtime)
955 {
956         // have a look at temp objects ...
957         int lastobj = m_tempObjectList->GetCount() - 1;
958         
959         for (int i = lastobj; i >= 0; i--)
960         {
961                 CValue* objval = m_tempObjectList->GetValue(i);
962                 CFloatValue* propval = (CFloatValue*) objval->GetProperty("::timebomb");
963                 
964                 if (propval)
965                 {
966                         float timeleft = propval->GetNumber() - 1.0/KX_KetsjiEngine::GetTicRate();
967                         
968                         if (timeleft > 0)
969                         {
970                                 propval->SetFloat(timeleft);
971                         }
972                         else
973                         {
974                                 DelayedRemoveObject(objval);
975                                 // remove obj
976                         }
977                 }
978                 else
979                 {
980                         // all object is the tempObjectList should have a clock
981                 }
982         }
983         m_logicmgr->BeginFrame(curtime, 1.0/KX_KetsjiEngine::GetTicRate());
984 }
985
986
987
988 void KX_Scene::LogicUpdateFrame(double curtime, bool frame)
989 {
990         m_logicmgr->UpdateFrame(curtime, frame);
991 }
992
993
994
995 void KX_Scene::LogicEndFrame()
996 {
997         m_logicmgr->EndFrame();
998         int numobj = m_euthanasyobjects->GetCount();
999
1000         for (int i = numobj - 1; i >= 0; i--)
1001         {
1002                 KX_GameObject* gameobj = (KX_GameObject*)m_euthanasyobjects->GetValue(i);
1003                 this->RemoveObject(gameobj);
1004         }
1005 }
1006
1007
1008
1009 /**
1010   * UpdateParents: SceneGraph transformation update.
1011   */
1012 void KX_Scene::UpdateParents(double curtime)
1013 {
1014 //      int numrootobjects = GetRootParentList()->GetCount();
1015
1016         for (int i=0; i<GetRootParentList()->GetCount(); i++)
1017         {
1018                 KX_GameObject* parentobj = (KX_GameObject*)GetRootParentList()->GetValue(i);
1019                 parentobj->NodeUpdateGS(curtime,true);
1020         }
1021 }
1022
1023
1024
1025 RAS_MaterialBucket* KX_Scene::FindBucket(class RAS_IPolyMaterial* polymat)
1026 {
1027         return m_bucketmanager->RAS_BucketManagerFindBucket(polymat);
1028 }
1029
1030
1031
1032 void KX_Scene::RenderBuckets(const MT_Transform & cameratransform,
1033                                                          class RAS_IRasterizer* rasty,
1034                                                          class RAS_IRenderTools* rendertools)
1035 {
1036         m_bucketmanager->Renderbuckets(cameratransform,rasty,rendertools);
1037 }
1038
1039
1040
1041 void KX_Scene::UpdateObjectActivity(void) 
1042 {
1043         if (m_activity_culling) {
1044                 /* determine the activity criterium and set objects accordingly */
1045                 int i=0;
1046                 
1047                 MT_Point3 camloc = GetActiveCamera()->NodeGetWorldPosition(); //GetCameraLocation();
1048                 
1049                 for (i=0;i<GetObjectList()->GetCount();i++)
1050                 {
1051                         KX_GameObject* ob = (KX_GameObject*) GetObjectList()->GetValue(i);
1052                         
1053                         if (!ob->GetIgnoreActivityCulling()) {
1054                                 /* Simple test: more than 10 away from the camera, count
1055                                  * Manhattan distance. */
1056                                 MT_Point3 obpos = ob->NodeGetWorldPosition();
1057                                 
1058                                 if ( (fabs(camloc[0] - obpos[0]) > m_activity_box_radius)
1059                                          || (fabs(camloc[1] - obpos[1]) > m_activity_box_radius)
1060                                          || (fabs(camloc[2] - obpos[2]) > m_activity_box_radius) )
1061                                 {                       
1062                                         ob->Suspend();
1063                                 } else {
1064                                         ob->Resume();
1065                                 }
1066                         }
1067                 }               
1068         }
1069 }
1070
1071 void KX_Scene::SetActivityCullingRadius(float f)
1072 {
1073         if (f < 0.5)
1074                 f = 0.5;
1075         m_activity_box_radius = f;
1076 }
1077         
1078 NG_NetworkDeviceInterface* KX_Scene::GetNetworkDeviceInterface()
1079 {
1080         return m_networkDeviceInterface;
1081 }
1082
1083 NG_NetworkScene* KX_Scene::GetNetworkScene()
1084 {
1085         return m_networkScene;
1086 }
1087
1088 void KX_Scene::SetNetworkDeviceInterface(NG_NetworkDeviceInterface* newInterface)
1089 {
1090         m_networkDeviceInterface = newInterface;
1091 }
1092
1093 void KX_Scene::SetNetworkScene(NG_NetworkScene *newScene)
1094 {
1095         m_networkScene = newScene;
1096 }
1097
1098
1099 void    KX_Scene::SetGravity(const MT_Vector3& gravity)
1100 {
1101         GetPhysicsEnvironment()->setGravity(gravity[0],gravity[1],gravity[2]);
1102 }
1103
1104 void KX_Scene::SetNodeTree(SG_Tree* root)
1105 {
1106         m_objecttree = root;
1107 }
1108
1109 void KX_Scene::SetPhysicsEnvironment(class PHY_IPhysicsEnvironment* physEnv)
1110 {
1111         SumoPhysicsEnvironment *sme = dynamic_cast<SumoPhysicsEnvironment *>(physEnv);
1112         m_physicsEnvironment = physEnv;
1113         if (sme)
1114         {
1115                 KX_TouchEventManager* touchmgr = new KX_TouchEventManager(m_logicmgr, sme->GetSumoScene());
1116                 m_logicmgr->RegisterEventManager(touchmgr);
1117                 return;
1118         }
1119 }
1120
1121 //----------------------------------------------------------------------------
1122 //Python
1123
1124 PyMethodDef KX_Scene::Methods[] = {
1125         KX_PYMETHODTABLE(KX_Scene, getLightList),
1126         KX_PYMETHODTABLE(KX_Scene, getObjectList),
1127         KX_PYMETHODTABLE(KX_Scene, getName),
1128         
1129         {NULL,NULL} //Sentinel
1130 };
1131
1132 PyTypeObject KX_Scene::Type = {
1133         PyObject_HEAD_INIT(&PyType_Type)
1134                 0,
1135                 "KX_Scene",
1136                 sizeof(KX_Scene),
1137                 0,
1138                 PyDestructor,
1139                 0,
1140                 __getattr,
1141                 __setattr,
1142                 0, //&MyPyCompare,
1143                 __repr,
1144                 0, //&cvalue_as_number,
1145                 0,
1146                 0,
1147                 0,
1148                 0, 0, 0, 0, 0, 0
1149 };
1150
1151 PyParentObject KX_Scene::Parents[] = {
1152         &KX_Scene::Type,
1153                 &CValue::Type,
1154                 NULL
1155 };
1156
1157 PyObject* KX_Scene::_getattr(const STR_String& attr)
1158 {
1159         if (attr == "name")
1160                 return PyString_FromString(GetName());
1161         
1162         if (attr == "active_camera")
1163         {
1164                 KX_Camera *camera = GetActiveCamera();
1165                 camera->AddRef();
1166                 return (PyObject*) camera;
1167         }
1168         
1169         if (attr == "suspended")
1170                 return PyInt_FromLong(m_suspend);
1171         
1172         if (attr == "activity_culling")
1173                 return PyInt_FromLong(m_activity_culling);
1174         
1175         if (attr == "activity_culling_radius")
1176                 return PyFloat_FromDouble(m_activity_box_radius);
1177         
1178         PyObject* value = PyDict_GetItemString(m_attrlist, const_cast<char *>(attr.ReadPtr()));
1179         if (value)
1180         {
1181                 Py_INCREF(value);
1182                 return value;
1183         }
1184         
1185         _getattr_up(PyObjectPlus);
1186 }
1187
1188 int KX_Scene::_delattr(const STR_String &attr)
1189 {
1190         PyDict_DelItemString(m_attrlist, const_cast<char *>(attr.ReadPtr()));
1191         return 0;
1192 }
1193
1194 int KX_Scene::_setattr(const STR_String &attr, PyObject *pyvalue)
1195 {
1196
1197         if (!PyDict_SetItemString(m_attrlist, const_cast<char *>(attr.ReadPtr()), pyvalue))
1198                 return 0;
1199
1200         return PyObjectPlus::_setattr(attr, pyvalue);
1201 }
1202
1203 KX_PYMETHODDEF_DOC(KX_Scene, getLightList,
1204 "getLightList() -> list [KX_Light]\n"
1205 "Returns a list of all lights in the scene.\n"
1206 )
1207 {
1208         m_lightlist->AddRef();
1209         return (PyObject*) m_lightlist;
1210 }
1211
1212 KX_PYMETHODDEF_DOC(KX_Scene, getObjectList,
1213 "getObjectList() -> list [KX_GameObject]\n"
1214 "Returns a list of all game objects in the scene.\n"
1215 )
1216 {
1217         m_objectlist->AddRef();
1218         return (PyObject*) m_objectlist;
1219 }
1220
1221 KX_PYMETHODDEF_DOC(KX_Scene, getName,
1222 "getName() -> string\n"
1223 "Returns the name of the scene.\n"
1224 )
1225 {
1226         return PyString_FromString(GetName());
1227 }