8f912642127d8be1120b1c5511b728d7284e1e8c
[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
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
160
161
162 KX_Scene::~KX_Scene()
163 {
164         
165 //      int numobj = m_objectlist->GetCount();
166
167         //int numrootobjects = GetRootParentList()->GetCount();
168         for (int i = 0; i < GetRootParentList()->GetCount(); i++)
169         {
170                 KX_GameObject* parentobj = (KX_GameObject*) GetRootParentList()->GetValue(i);
171                 this->RemoveObject(parentobj);
172         }
173
174         if(m_objectlist)
175                 m_objectlist->Release();
176         
177         if (m_parentlist)
178                 m_parentlist->Release();
179         
180         if (m_lightlist)
181                 m_lightlist->Release();
182         
183         if (m_tempObjectList)
184                 m_tempObjectList->Release();
185
186         if (m_euthanasyobjects)
187                 m_euthanasyobjects->Release();
188         
189         if (m_logicmgr)
190                 delete m_logicmgr;
191
192         if (m_physicsEnvironment)
193                 delete m_physicsEnvironment;
194
195         if (m_soundScene)
196                 delete m_soundScene;
197
198         if (m_networkScene)
199                 delete m_networkScene;
200         
201         if (m_bucketmanager)
202         {
203                 delete m_bucketmanager;
204         }
205 }
206
207
208
209
210 void KX_Scene::SetProjectionMatrix(MT_CmMatrix4x4& pmat)
211 {
212         m_projectionmat = pmat;
213 }
214
215
216
217 RAS_BucketManager* KX_Scene::GetBucketManager()
218 {
219         return m_bucketmanager;
220 }
221
222
223
224 CListValue* KX_Scene::GetObjectList()
225 {
226         return m_objectlist;
227 }
228
229
230
231 CListValue* KX_Scene::GetRootParentList()
232 {
233         return m_parentlist;
234 }
235
236
237
238 CListValue* KX_Scene::GetLightList()
239 {
240         return m_lightlist;
241 }
242
243 SCA_LogicManager* KX_Scene::GetLogicManager()
244 {
245         return m_logicmgr;
246 }
247
248 SCA_TimeEventManager* KX_Scene::GetTimeEventManager()
249 {
250         return m_timemgr;
251 }
252
253
254
255
256 void KX_Scene::SetFramingType(RAS_FrameSettings & frame_settings)
257 {
258         m_frame_settings = frame_settings;
259 };
260
261 /**
262  * Return a const reference to the framing 
263  * type set by the above call.
264  * The contents are not guarenteed to be sensible
265  * if you don't call the above function.
266  */
267 const RAS_FrameSettings& KX_Scene::GetFramingType() const 
268 {
269         return m_frame_settings;
270 };      
271
272
273
274 /**
275  * Store the current scene's viewport on the 
276  * game engine canvas.
277  */
278 void KX_Scene::SetSceneViewport(const RAS_Rect &viewport)
279 {
280         m_viewport = viewport;
281 }
282
283
284
285 const RAS_Rect& KX_Scene::GetSceneViewport() const 
286 {
287         return m_viewport;
288 }
289
290
291
292 void KX_Scene::SetWorldInfo(class KX_WorldInfo* worldinfo)
293 {
294         m_worldinfo = worldinfo;
295 }
296
297
298
299 class KX_WorldInfo* KX_Scene::GetWorldInfo()
300 {
301         return m_worldinfo;
302 }
303
304
305
306 SND_Scene* KX_Scene::GetSoundScene()
307 {
308         return m_soundScene;
309 }
310
311 const STR_String& KX_Scene::GetName()
312 {
313         return m_sceneName;
314 }
315
316
317 void KX_Scene::Suspend()
318 {
319         m_suspend = true;
320 }
321
322 void KX_Scene::Resume()
323 {
324         m_suspend = false;
325 }
326
327 void KX_Scene::SetActivityCulling(bool b)
328 {
329         m_activity_culling = b;
330 }
331
332 bool KX_Scene::IsSuspended()
333 {
334         return m_suspend;
335 }
336
337 bool KX_Scene::IsClearingZBuffer()
338 {
339         return m_isclearingZbuffer;
340 }
341
342 void KX_Scene::EnableZBufferClearing(bool isclearingZbuffer)
343 {
344         m_isclearingZbuffer = isclearingZbuffer;
345 }
346
347 void KX_Scene::RemoveNodeDestructObject(class SG_IObject* node,class CValue* gameobj)
348 {
349         KX_GameObject* orgobj = (KX_GameObject*)gameobj;        
350         NewRemoveObject(orgobj);
351
352         if (node)
353                 delete node;
354 }
355
356 KX_GameObject* KX_Scene::AddNodeReplicaObject(class SG_IObject* node, class CValue* gameobj)
357 {
358         KX_GameObject* orgobj = (KX_GameObject*)gameobj;
359         KX_GameObject* newobj = (KX_GameObject*)orgobj->GetReplica();
360         m_map_gameobject_to_replica.insert(orgobj, newobj);
361
362         // also register 'timers' (time properties) of the replica
363         int numprops = newobj->GetPropertyCount();
364
365         for (int i = 0; i < numprops; i++)
366         {
367                 CValue* prop = newobj->GetProperty(i);
368
369                 if (prop->GetProperty("timer"))
370                         this->m_timemgr->AddTimeProperty(prop);
371         }
372
373         if (node)
374         {
375                 newobj->SetSGNode((SG_Node*)node);
376         }
377         else
378         {
379                 m_rootnode = new SG_Node(newobj,this,KX_Scene::m_callbacks);
380         
381                 // this fixes part of the scaling-added object bug
382                 SG_Node* orgnode = orgobj->GetSGNode();
383                 m_rootnode->SetLocalScale(orgnode->GetLocalScale());
384                 m_rootnode->SetLocalPosition(orgnode->GetLocalPosition());
385                 m_rootnode->SetLocalOrientation(orgnode->GetLocalOrientation());
386
387                 // define the relationship between this node and it's parent.
388                 KX_NormalParentRelation * parent_relation = 
389                         KX_NormalParentRelation::New();
390                 m_rootnode->SetParentRelation(parent_relation);
391
392                 newobj->SetSGNode(m_rootnode);
393         }
394         
395         SG_IObject* replicanode = newobj->GetSGNode();
396         SG_Node* rootnode = (replicanode == m_rootnode ? NULL : m_rootnode);
397
398         replicanode->SetSGClientObject(newobj);
399
400         // this is the list of object that are send to the graphics pipeline
401         m_objectlist->Add(newobj);
402         newobj->Bucketize();
403
404         // logic cannot be replicated, until the whole hierarchy is replicated.
405         m_logicHierarchicalGameObjects.push_back(newobj);
406         //replicate controllers of this node
407         SGControllerList        scenegraphcontrollers = orgobj->GetSGNode()->GetSGControllerList();
408         replicanode->RemoveAllControllers();
409         SGControllerList::iterator cit;
410         //int numcont = scenegraphcontrollers.size();
411         
412         for (cit = scenegraphcontrollers.begin();!(cit==scenegraphcontrollers.end());++cit)
413         {
414                 // controller replication is quite complicated
415                 // only replicate ipo and physics controller for now
416
417                 SG_Controller* replicacontroller = (*cit)->GetReplica((SG_Node*) replicanode);
418                 if (replicacontroller)
419                 {
420                         replicacontroller->SetObject(replicanode);
421                         replicanode->AddSGController(replicacontroller);
422                 }
423         }
424         
425         return newobj;
426 }
427
428
429
430 // before calling this method KX_Scene::ReplicateLogic(), make sure to
431 // have called 'GameObject::ReParentLogic' for each object this
432 // hierarchy that's because first ALL bricks must exist in the new
433 // replica of the hierarchy in order to make cross-links work properly
434 // !
435 void KX_Scene::ReplicateLogic(KX_GameObject* newobj)
436 {
437         // also relink the controller to sensors/actuators
438         SCA_ControllerList& controllers = newobj->GetControllers();
439         //SCA_SensorList&     sensors     = newobj->GetSensors();
440         //SCA_ActuatorList&   actuators   = newobj->GetActuators();
441
442         for (SCA_ControllerList::iterator itc = controllers.begin(); !(itc==controllers.end());itc++)
443         {
444                 SCA_IController* cont = (*itc);
445                 cont->SetUeberExecutePriority(m_ueberExecutionPriority);
446                 vector<SCA_ISensor*> linkedsensors = cont->GetLinkedSensors();
447                 vector<SCA_IActuator*> linkedactuators = cont->GetLinkedActuators();
448
449                 // disconnect the sensors and actuators
450                 cont->UnlinkAllSensors();
451                 cont->UnlinkAllActuators();
452                 
453                 // now relink each sensor
454                 for (vector<SCA_ISensor*>::iterator its = linkedsensors.begin();!(its==linkedsensors.end());its++)
455                 {
456                         SCA_ISensor* oldsensor = (*its);
457                         STR_String name = oldsensor->GetName();
458                         //find this name in the list
459                         SCA_ISensor* newsensor = newobj->FindSensor(name);
460                 
461                         if (newsensor)
462                         {
463                                 // relink this newsensor to the controller
464                                 m_logicmgr->RegisterToSensor(cont,newsensor);
465                         }
466                         else
467                         {
468                                 // it can be linked somewhere in the hierarchy or...
469                                 for (vector<KX_GameObject*>::iterator git = m_logicHierarchicalGameObjects.begin();
470                                 !(git==m_logicHierarchicalGameObjects.end());++git)
471                                 {
472                                         newsensor = (*git)->FindSensor(name);
473                                         if (newsensor)
474                                                 break;
475                                 } 
476
477                                 if (newsensor)
478                                 {
479                                         // relink this newsensor to the controller somewhere else within this
480                                         // hierarchy
481                                         m_logicmgr->RegisterToSensor(cont,newsensor);
482                                 }
483                                 else
484                                 {
485                                         // must be an external sensor, so...
486                                         m_logicmgr->RegisterToSensor(cont,oldsensor);
487                                 }
488                         }
489                 }
490                 
491                 // now relink each actuator
492                 for (vector<SCA_IActuator*>::iterator ita = linkedactuators.begin();!(ita==linkedactuators.end());ita++)
493                 {
494                         SCA_IActuator* oldactuator = (*ita);
495                         STR_String name = oldactuator->GetName();
496                         //find this name in the list
497                         SCA_IActuator* newactuator = newobj->FindActuator(name);
498                         if (newactuator)
499                         {
500                                 // relink this newsensor to the controller
501                                 m_logicmgr->RegisterToActuator(cont,newactuator);
502                                 newactuator->SetUeberExecutePriority(m_ueberExecutionPriority);
503                         }
504                         else
505                         {
506                                 // it can be linked somewhere in the hierarchy or...
507                                 for (vector<KX_GameObject*>::iterator git = m_logicHierarchicalGameObjects.begin();
508                                 !(git==m_logicHierarchicalGameObjects.end());++git)
509                                 {
510                                         newactuator= (*git)->FindActuator(name);
511                                         if (newactuator)
512                                                 break;
513                                 } 
514
515                                 if (newactuator)
516                                 {
517                                         // relink this actuator to the controller somewhere else within this
518                                         // hierarchy
519                                         m_logicmgr->RegisterToActuator(cont,newactuator);
520                                         newactuator->SetUeberExecutePriority(m_ueberExecutionPriority);
521                                 }
522                                 else
523                                 {
524                                         // must be an external actuator, so...
525                                         m_logicmgr->RegisterToActuator(cont,oldactuator);
526                                 }
527                         }
528                 }
529         }
530 }
531
532
533
534 SCA_IObject* KX_Scene::AddReplicaObject(class CValue* originalobject,
535                                                                                 class CValue* parentobject,
536                                                                                 int lifespan)
537 {
538
539         m_logicHierarchicalGameObjects.clear();
540         m_map_gameobject_to_replica.clear();
541
542         // todo: place a timebomb in the object, for temporarily objects :)
543         // lifespan of zero means 'this object lives forever'
544         KX_GameObject* originalobj = (KX_GameObject*) originalobject;
545         KX_GameObject* parentobj = (KX_GameObject*) parentobject;
546
547         m_ueberExecutionPriority++;
548
549         // lets create a replica
550         KX_GameObject* replica = (KX_GameObject*) AddNodeReplicaObject(NULL,originalobj);
551
552         if (lifespan > 0)
553         {
554                 // add a timebomb to this object
555                 // for now, convert between so called frames and realtime
556                 m_tempObjectList->Add(replica->AddRef());
557                 replica->SetProperty("::timebomb",new CFloatValue(lifespan*0.02));
558         }
559
560         // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame)
561         m_parentlist->Add(replica->AddRef());
562
563         // recurse replication into children nodes
564
565         NodeList& children = originalobj->GetSGNode()->GetSGChildren();
566
567         replica->GetSGNode()->ClearSGChildren();
568         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
569         {
570                 SG_Node* orgnode = (*childit);
571                 SG_Node* childreplicanode = orgnode->GetSGReplica();
572                 replica->GetSGNode()->AddChild(childreplicanode);
573         }
574
575         //      relink any pointers as necessary, sort of a temporary solution
576         vector<KX_GameObject*>::iterator git;
577         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
578         {
579                 (*git)->Relink(&m_map_gameobject_to_replica);
580         }
581
582         // now replicate logic
583         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
584         {
585                 (*git)->ReParentLogic();
586         }
587         
588         // replicate crosslinks etc. between logic bricks
589         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
590         {
591                 ReplicateLogic((*git));
592         }
593         
594         MT_Point3 newpos = ((KX_GameObject*) parentobject)->NodeGetWorldPosition();
595         replica->NodeSetLocalPosition(newpos);
596
597         MT_Matrix3x3 newori = ((KX_GameObject*) parentobject)->NodeGetWorldOrientation();
598         replica->NodeSetLocalOrientation(newori);
599
600         if (replica->GetPhysicsController())
601         {
602                 replica->GetPhysicsController()->setPosition(newpos);
603                 replica->GetPhysicsController()->setOrientation(newori.getRotation());
604         }
605
606         // here we want to set the relative scale: the rootnode's scale will override all other
607         // scalings, so lets better prepare for it
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         replica->GetSGNode()->UpdateWorldData(0);
616         replica->GetSGNode()->SetBBox(originalobj->GetSGNode()->BBox());
617         replica->GetSGNode()->SetRadius(originalobj->GetSGNode()->Radius());
618         
619         return replica;
620 }
621
622
623
624 void KX_Scene::RemoveObject(class CValue* gameobj)
625 {
626         KX_GameObject* newobj = (KX_GameObject*) gameobj;
627
628         // first disconnect child from parent
629         SG_Node* node = newobj->GetSGNode();
630
631         if (node)
632         {
633                 node->DisconnectFromParent();
634
635                 // recursively destruct
636                 node->Destruct();
637         }
638 }
639
640
641
642 void KX_Scene::DelayedRemoveObject(class CValue* gameobj)
643 {
644         //KX_GameObject* newobj = (KX_GameObject*) gameobj;
645         if (!m_euthanasyobjects->SearchValue(gameobj))
646         {
647                 m_euthanasyobjects->Add(gameobj->AddRef());
648         } 
649 }
650
651
652
653 void KX_Scene::NewRemoveObject(class CValue* gameobj)
654 {
655         KX_GameObject* newobj = (KX_GameObject*) gameobj;
656         //SM_Object* sumoObj = newobj->GetSumoObject();
657         //if (sumoObj)
658         //{
659         //      this->GetSumoScene()->remove(*sumoObj);
660         //}
661         // remove all sensors/controllers/actuators from logicsystem...
662         
663         SCA_SensorList& sensors = newobj->GetSensors();
664         for (SCA_SensorList::iterator its = sensors.begin();
665                  !(its==sensors.end());its++)
666         {
667                 m_logicmgr->RemoveSensor(*its);
668         }
669         
670     SCA_ControllerList& controllers = newobj->GetControllers();
671         for (SCA_ControllerList::iterator itc = controllers.begin();
672                  !(itc==controllers.end());itc++)
673         {
674                 (*itc)->UnlinkAllSensors();
675                 (*itc)->UnlinkAllActuators();
676         }
677
678         SCA_ActuatorList& actuators = newobj->GetActuators();
679         for (SCA_ActuatorList::iterator ita = actuators.begin();
680                  !(ita==actuators.end());ita++)
681         {
682                 m_logicmgr->RemoveDestroyedActuator(*ita);
683         }
684
685         // now remove the timer properties from the time manager
686         int numprops = newobj->GetPropertyCount();
687
688         for (int i = 0; i < numprops; i++)
689         {
690                 CValue* propval = newobj->GetProperty(i);
691                 if (propval->GetProperty("timer"))
692                 {
693                         m_timemgr->RemoveTimeProperty(propval);
694                 }
695         }
696         
697         newobj->RemoveMeshes();
698         if (m_objectlist->RemoveValue(newobj))
699                 newobj->Release();
700         if (m_tempObjectList->RemoveValue(newobj))
701                 newobj->Release();
702         if (m_parentlist->RemoveValue(newobj))
703                 newobj->Release();
704         if (m_euthanasyobjects->RemoveValue(newobj))
705                 newobj->Release();
706                 
707         if (newobj == m_active_camera)
708         {
709                 m_active_camera = NULL;
710         }
711 }
712
713
714
715 void KX_Scene::ReplaceMesh(class CValue* gameobj,void* meshobj)
716 {
717         KX_GameObject* newobj = (KX_GameObject*) gameobj;
718         newobj->RemoveMeshes();
719         newobj->AddMesh((RAS_MeshObject*)meshobj);
720         newobj->Bucketize();
721 }
722
723
724
725 MT_CmMatrix4x4& KX_Scene::GetViewMatrix()
726 {
727         MT_Scalar cammat[16];
728         m_active_camera->GetWorldToCamera().getValue(cammat);
729         m_viewmat = cammat;
730         return m_viewmat;
731 }
732
733
734
735 MT_CmMatrix4x4& KX_Scene::GetProjectionMatrix()
736 {
737         return m_projectionmat;
738 }
739
740
741 KX_Camera* KX_Scene::FindCamera(KX_Camera* cam)
742 {
743         set<KX_Camera*>::iterator it = m_cameras.begin();
744
745         while ( (it != m_cameras.end()) 
746                         && ((*it) != cam) ) {
747           it++;
748         }
749
750         return ((it == m_cameras.end()) ? NULL : (*it));
751 }
752
753
754 KX_Camera* KX_Scene::FindCamera(STR_String& name)
755 {
756         set<KX_Camera*>::iterator it = m_cameras.begin();
757
758         while ( (it != m_cameras.end()) 
759                         && ((*it)->GetName() != name) ) {
760           it++;
761         }
762
763         return ((it == m_cameras.end()) ? NULL : (*it));
764 }
765
766 void KX_Scene::AddCamera(KX_Camera* cam)
767 {
768         m_cameras.insert(cam);
769 }
770
771
772 KX_Camera* KX_Scene::GetActiveCamera()
773 {       
774         // NULL if not defined
775         return m_active_camera;
776 }
777
778
779 void KX_Scene::SetActiveCamera(KX_Camera* cam)
780 {
781         // only set if the cam is in the active list? Or add it otherwise?
782         if (!FindCamera(cam)){
783                 AddCamera(cam);
784                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
785         } 
786
787         m_active_camera = cam;
788 }
789
790
791
792 void KX_Scene::UpdateMeshTransformations()
793 {
794         // do this incrementally in the future
795         for (int i = 0; i < m_objectlist->GetCount(); i++)
796         {
797                 KX_GameObject* gameobj = (KX_GameObject*)m_objectlist->GetValue(i);
798                 gameobj->GetOpenGLMatrix();
799 //              gameobj->UpdateNonDynas();
800         }
801 }
802
803 void KX_Scene::MarkVisible(SG_Tree *node, RAS_IRasterizer* rasty)
804 {
805         int intersect = KX_Camera::INTERSECT;
806         KX_GameObject *gameobj = node->Client()?(KX_GameObject*) node->Client()->GetSGClientObject():NULL;
807         
808         /* If the camera is inside the box, assume intersect. */
809         if (!node->inside(GetActiveCamera()->NodeGetWorldPosition()))
810         {
811                 MT_Scalar radius = node->Radius();
812                 MT_Point3 centre = node->Centre();
813                 
814                 intersect = GetActiveCamera()->SphereInsideFrustum(centre, radius);
815                 
816                 if (intersect == KX_Camera::INTERSECT)
817                 {
818                         MT_Point3 box[8];
819                         node->get(box);
820                         intersect = GetActiveCamera()->BoxInsideFrustum(box);
821                 }
822         }
823
824         switch (intersect)
825         {
826                 case KX_Camera::OUTSIDE:
827                         MarkSubTreeVisible(node, rasty, false);
828                         break;
829                 case KX_Camera::INTERSECT:
830                         if (gameobj)
831                         {
832                                 int nummeshes = gameobj->GetMeshCount();
833                                 MT_Transform t(GetActiveCamera()->GetWorldToCamera() * gameobj->GetSGNode()->GetWorldTransform());
834                                 
835                                 for (int m=0;m<nummeshes;m++)
836                                 {
837                                         // this adds the vertices to the display list
838                                         (gameobj->GetMesh(m))->SchedulePolygons(t, rasty->GetDrawingMode(),rasty);
839                                 }
840                                 gameobj->MarkVisible();
841                         }
842                         if (node->Left())
843                                 MarkVisible(node->Left(), rasty);
844                         if (node->Right())
845                                 MarkVisible(node->Right(), rasty);
846                         break;
847                 case KX_Camera::INSIDE:
848                         MarkSubTreeVisible(node, rasty, true);
849                         break;
850         }
851 }
852
853 void KX_Scene::MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool visible)
854 {
855         if (node->Client())
856         {
857                 KX_GameObject *gameobj = (KX_GameObject*) node->Client()->GetSGClientObject();
858                 if (visible)
859                 {
860                         int nummeshes = gameobj->GetMeshCount();
861                         MT_Transform t( GetActiveCamera()->GetWorldToCamera() * gameobj->GetSGNode()->GetWorldTransform());
862
863                         
864                         for (int m=0;m<nummeshes;m++)
865                         {
866                                 // this adds the vertices to the display list
867                                 (gameobj->GetMesh(m))->SchedulePolygons(t, rasty->GetDrawingMode(),rasty);
868                         }
869                 }
870                 gameobj->MarkVisible(visible && gameobj->GetVisible());
871         }
872         if (node->Left())
873                 MarkSubTreeVisible(node->Left(), rasty, visible);
874         if (node->Right())
875                 MarkSubTreeVisible(node->Right(), rasty, visible);
876 }
877
878
879 void KX_Scene::CalculateVisibleMeshes(RAS_IRasterizer* rasty)
880 {
881 // FIXME: When tree is operational
882 #if 1
883         // do this incrementally in the future
884         for (int i = 0; i < m_objectlist->GetCount(); i++)
885         {
886                 KX_GameObject* gameobj = (KX_GameObject*)m_objectlist->GetValue(i);
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(),rasty);
927                         }
928                         // Visibility/ non-visibility are marked
929                         // elsewhere now.
930                         gameobj->MarkVisible();
931                 } else {
932                         gameobj->MarkVisible(false);
933                 }
934         }
935 #else
936         if (GetActiveCamera()->GetFrustumCulling())
937                 MarkVisible(m_objecttree, rasty);
938         else
939                 MarkSubTreeVisible(m_objecttree, rasty, true);
940 #endif
941 }
942
943 // logic stuff
944 void KX_Scene::LogicBeginFrame(double curtime,double deltatime)
945 {
946         // have a look at temp objects ...
947         int lastobj = m_tempObjectList->GetCount() - 1;
948         
949         for (int i = lastobj; i >= 0; i--)
950         {
951                 CValue* objval = m_tempObjectList->GetValue(i);
952                 CFloatValue* propval = (CFloatValue*) objval->GetProperty("::timebomb");
953                 
954                 if (propval)
955                 {
956                         float timeleft = propval->GetNumber() - deltatime;
957                         
958                         if (timeleft > 0)
959                         {
960                                 propval->SetFloat(timeleft);
961                         }
962                         else
963                         {
964                                 DelayedRemoveObject(objval);
965                                 // remove obj
966                         }
967                 }
968                 else
969                 {
970                         // all object is the tempObjectList should have a clock
971                 }
972         }
973         m_logicmgr->BeginFrame(curtime,deltatime);
974 }
975
976
977
978 void KX_Scene::LogicUpdateFrame(double curtime,double deltatime)
979 {
980         m_logicmgr->UpdateFrame(curtime,deltatime);
981 }
982
983
984
985 void KX_Scene::LogicEndFrame()
986 {
987         m_logicmgr->EndFrame();
988         int numobj = m_euthanasyobjects->GetCount();
989
990         for (int i = numobj - 1; i >= 0; i--)
991         {
992                 KX_GameObject* gameobj = (KX_GameObject*)m_euthanasyobjects->GetValue(i);
993                 this->RemoveObject(gameobj);
994         }
995         
996         numobj = m_euthanasyobjects->GetCount();
997         if (numobj != 0)
998         {
999                 // huh?
1000                 int ii=0;
1001         }
1002         // numobj is 0 we hope
1003 }
1004
1005
1006
1007 /**
1008   * UpdateParents: SceneGraph transformation update.
1009   */
1010 void KX_Scene::UpdateParents(double curtime)
1011 {
1012 //      int numrootobjects = GetRootParentList()->GetCount();
1013
1014         for (int i=0; i<GetRootParentList()->GetCount(); i++)
1015         {
1016                 KX_GameObject* parentobj = (KX_GameObject*)GetRootParentList()->GetValue(i);
1017                 parentobj->NodeUpdateGS(curtime,true);
1018         }
1019 }
1020
1021
1022
1023 RAS_MaterialBucket* KX_Scene::FindBucket(class RAS_IPolyMaterial* polymat)
1024 {
1025         return m_bucketmanager->RAS_BucketManagerFindBucket(polymat);
1026 }
1027
1028
1029
1030 void KX_Scene::RenderBuckets(const MT_Transform & cameratransform,
1031                                                          class RAS_IRasterizer* rasty,
1032                                                          class RAS_IRenderTools* rendertools)
1033 {
1034         m_bucketmanager->Renderbuckets(cameratransform,rasty,rendertools);
1035 }
1036
1037
1038
1039 void KX_Scene::UpdateObjectActivity(void) 
1040 {
1041         if (m_activity_culling) {
1042                 /* determine the activity criterium and set objects accordingly */
1043                 int i=0;
1044                 
1045                 MT_Point3 camloc = GetActiveCamera()->NodeGetWorldPosition(); //GetCameraLocation();
1046                 
1047                 for (i=0;i<GetObjectList()->GetCount();i++)
1048                 {
1049                         KX_GameObject* ob = (KX_GameObject*) GetObjectList()->GetValue(i);
1050                         
1051                         if (!ob->GetIgnoreActivityCulling()) {
1052                                 /* Simple test: more than 10 away from the camera, count
1053                                  * Manhattan distance. */
1054                                 MT_Point3 obpos = ob->NodeGetWorldPosition();
1055                                 
1056                                 if ( (fabs(camloc[0] - obpos[0]) > m_activity_box_radius)
1057                                          || (fabs(camloc[1] - obpos[1]) > m_activity_box_radius)
1058                                          || (fabs(camloc[2] - obpos[2]) > m_activity_box_radius) )
1059                                 {                       
1060                                         ob->Suspend();
1061                                 } else {
1062                                         ob->Resume();
1063                                 }
1064                         }
1065                 }               
1066         }
1067 }
1068
1069 void KX_Scene::SetActivityCullingRadius(float f)
1070 {
1071         if (f < 0.5)
1072                 f = 0.5;
1073         m_activity_box_radius = f;
1074 }
1075         
1076 NG_NetworkDeviceInterface* KX_Scene::GetNetworkDeviceInterface()
1077 {
1078         return m_networkDeviceInterface;
1079 }
1080
1081 NG_NetworkScene* KX_Scene::GetNetworkScene()
1082 {
1083         return m_networkScene;
1084 }
1085
1086 void KX_Scene::SetNetworkDeviceInterface(NG_NetworkDeviceInterface* newInterface)
1087 {
1088         m_networkDeviceInterface = newInterface;
1089 }
1090
1091 void KX_Scene::SetNetworkScene(NG_NetworkScene *newScene)
1092 {
1093         m_networkScene = newScene;
1094 }
1095
1096
1097 void    KX_Scene::SetGravity(const MT_Vector3& gravity)
1098 {
1099         GetPhysicsEnvironment()->setGravity(gravity[0],gravity[1],gravity[2]);
1100 }
1101
1102 void KX_Scene::SetNodeTree(SG_Tree* root)
1103 {
1104         m_objecttree = root;
1105 }
1106
1107 void KX_Scene::SetPhysicsEnvironment(class PHY_IPhysicsEnvironment* physEnv)
1108 {
1109         SumoPhysicsEnvironment *sme = dynamic_cast<SumoPhysicsEnvironment *>(physEnv);
1110         m_physicsEnvironment = physEnv;
1111         if (sme)
1112         {
1113                 KX_TouchEventManager* touchmgr = new KX_TouchEventManager(m_logicmgr, sme->GetSumoScene());
1114                 m_logicmgr->RegisterEventManager(touchmgr);
1115                 return;
1116         }
1117 }