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