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