Building the game engine with Solid/Sumo is now optional for scons using WITH_BF_SOLID.
[blender-staging.git] / source / gameengine / Ketsji / KX_KetsjiEngine.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  * The engine ties all game modules together. 
29  */
30
31 #ifdef WIN32
32 #pragma warning (disable : 4786)
33 #endif //WIN32
34
35 #include <iostream>
36
37 #include "KX_KetsjiEngine.h"
38
39 #include "ListValue.h"
40 #include "IntValue.h"
41 #include "VectorValue.h"
42 #include "BoolValue.h"
43 #include "FloatValue.h"
44
45 #define KX_NUM_ITERATIONS 4
46 #include "RAS_BucketManager.h"
47 #include "RAS_Rect.h"
48 #include "RAS_IRasterizer.h"
49 #include "RAS_IRenderTools.h"
50 #include "RAS_ICanvas.h"
51 #include "STR_String.h"
52 #include "MT_Vector3.h"
53 #include "MT_Transform.h"
54 #include "SCA_IInputDevice.h"
55 #include "KX_Scene.h"
56 #include "MT_CmMatrix4x4.h"
57 #include "KX_Camera.h"
58 #include "KX_Light.h"
59 #include "KX_PythonInit.h"
60 #include "KX_PyConstraintBinding.h"
61 #include "PHY_IPhysicsEnvironment.h"
62
63 #ifdef USE_SUMO_SOLID
64 #include "SumoPhysicsEnvironment.h"
65 #endif
66
67 #include "SND_Scene.h"
68 #include "SND_IAudioDevice.h"
69
70 #include "NG_NetworkScene.h"
71 #include "NG_NetworkDeviceInterface.h"
72
73 #include "KX_WorldInfo.h"
74 #include "KX_ISceneConverter.h"
75 #include "KX_TimeCategoryLogger.h"
76
77 #include "RAS_FramingManager.h"
78 #include "stdio.h"
79
80 // If define: little test for Nzc: guarded drawing. If the canvas is
81 // not valid, skip rendering this frame.
82 //#define NZC_GUARDED_OUTPUT
83 #define DEFAULT_LOGIC_TIC_RATE 60.0
84 #define DEFAULT_PHYSICS_TIC_RATE 60.0
85
86 const char KX_KetsjiEngine::m_profileLabels[tc_numCategories][15] = {
87         "Physics:",             // tc_physics
88         "Logic",                // tc_logic
89         "Network:",             // tc_network
90         "Scenegraph:",  // tc_scenegraph
91         "Sound:",               // tc_sound
92         "Rasterizer:",  // tc_rasterizer
93         "Services:",    // tc_services
94         "Overhead:",    // tc_overhead
95         "Outside:"              // tc_outside
96 };
97
98 double KX_KetsjiEngine::m_ticrate = DEFAULT_LOGIC_TIC_RATE;
99 double KX_KetsjiEngine::m_anim_framerate = 25.0;
100 double KX_KetsjiEngine::m_suspendedtime = 0.0;
101 double KX_KetsjiEngine::m_suspendeddelta = 0.0;
102 double KX_KetsjiEngine::m_average_framerate = 0.0;
103
104
105 /**
106  *      Constructor of the Ketsji Engine
107  */
108 KX_KetsjiEngine::KX_KetsjiEngine(KX_ISystem* system)
109      :  m_canvas(NULL),
110         m_rasterizer(NULL),
111         m_kxsystem(system),
112         m_rendertools(NULL),
113         m_sceneconverter(NULL),
114         m_networkdevice(NULL),
115         m_audiodevice(NULL),
116         m_pythondictionary(NULL),
117         m_keyboarddevice(NULL),
118         m_mousedevice(NULL),
119
120         m_propertiesPresent(false),
121
122         m_bInitialized(false),
123         m_activecam(0),
124         m_bFixedTime(false),
125         
126         m_firstframe(true),
127         
128         m_frameTime(0.f),
129         m_clockTime(0.f),
130         m_previousClockTime(0.f),
131
132
133         m_exitcode(KX_EXIT_REQUEST_NO_REQUEST),
134         m_exitstring(""),
135         
136         m_drawingmode(5),
137         m_cameraZoom(1.0),
138         
139         m_overrideCam(false),
140         m_overrideCamUseOrtho(false),
141         m_overrideCamNear(0.0),
142         m_overrideCamFar(0.0),
143
144         m_stereo(false),
145         m_curreye(0),
146
147         m_logger(NULL),
148         
149         // Set up timing info display variables
150         m_show_framerate(false),
151         m_show_profile(false),
152         m_showProperties(false),
153         m_showBackground(false),
154         m_show_debug_properties(false),
155
156         m_game2ipo(false),
157
158         // Default behavior is to hide the cursor every frame.
159         m_hideCursor(false),
160
161         m_overrideFrameColor(false),
162         m_overrideFrameColorR(0.0),
163         m_overrideFrameColorG(0.0),
164         m_overrideFrameColorB(0.0)
165 {
166         // Initialize the time logger
167         m_logger = new KX_TimeCategoryLogger (25);
168
169         for (int i = tc_first; i < tc_numCategories; i++)
170                 m_logger->AddCategory((KX_TimeCategory)i);
171                 
172 }
173
174
175
176 /**
177  *      Destructor of the Ketsji Engine, release all memory
178  */
179 KX_KetsjiEngine::~KX_KetsjiEngine()
180 {
181         delete m_logger;
182 }
183
184
185
186 void KX_KetsjiEngine::SetKeyboardDevice(SCA_IInputDevice* keyboarddevice)
187 {
188         MT_assert(keyboarddevice);
189         m_keyboarddevice = keyboarddevice;
190 }
191
192
193
194 void KX_KetsjiEngine::SetMouseDevice(SCA_IInputDevice* mousedevice)
195 {
196         MT_assert(mousedevice);
197         m_mousedevice = mousedevice;
198 }
199
200
201
202 void KX_KetsjiEngine::SetNetworkDevice(NG_NetworkDeviceInterface* networkdevice)
203 {
204         MT_assert(networkdevice);
205         m_networkdevice = networkdevice;
206 }
207
208
209
210 void KX_KetsjiEngine::SetAudioDevice(SND_IAudioDevice* audiodevice)
211 {
212         MT_assert(audiodevice);
213         m_audiodevice = audiodevice;
214 }
215
216
217
218 void KX_KetsjiEngine::SetCanvas(RAS_ICanvas* canvas)
219 {
220         MT_assert(canvas);
221         m_canvas = canvas;
222 }
223
224
225
226 void KX_KetsjiEngine::SetRenderTools(RAS_IRenderTools* rendertools)
227 {
228         MT_assert(rendertools);
229         m_rendertools = rendertools;
230 }
231
232
233
234 void KX_KetsjiEngine::SetRasterizer(RAS_IRasterizer* rasterizer)
235 {
236         MT_assert(rasterizer);
237         m_rasterizer = rasterizer;
238 }
239
240
241 /*
242  * At the moment the GameLogic module is imported into 'pythondictionary' after this function is called.
243  * if this function ever changes to assign a copy, make sure the game logic module is imported into this dictionary before hand.
244  */
245 void KX_KetsjiEngine::SetPythonDictionary(PyObject* pythondictionary)
246 {
247         MT_assert(pythondictionary);
248         m_pythondictionary = pythondictionary;
249 }
250
251
252
253 void KX_KetsjiEngine::SetSceneConverter(KX_ISceneConverter* sceneconverter)
254 {
255         MT_assert(sceneconverter);
256         m_sceneconverter = sceneconverter;
257 }
258
259
260
261 /**
262  * Ketsji Init(), Initializes datastructures and converts data from
263  * Blender into Ketsji native (realtime) format also sets up the
264  * graphics context
265  */
266 void KX_KetsjiEngine::StartEngine(bool clearIpo)
267 {
268         m_clockTime = m_kxsystem->GetTimeInSeconds();
269         m_frameTime = m_kxsystem->GetTimeInSeconds();
270         m_previousClockTime = m_kxsystem->GetTimeInSeconds();
271
272         m_firstframe = true;
273         m_bInitialized = true;
274         m_ticrate = DEFAULT_LOGIC_TIC_RATE;
275         
276         if (m_game2ipo)
277         {
278                 m_sceneconverter->ResetPhysicsObjectsAnimationIpo(clearIpo);
279                 m_sceneconverter->WritePhysicsObjectToAnimationIpo(m_currentFrame);
280         }
281
282 }
283
284 void KX_KetsjiEngine::ClearFrame()
285 {
286         // clear unless we're drawing overlapping stereo
287         if(m_rasterizer->InterlacedStereo() &&
288                 m_rasterizer->GetEye() == RAS_IRasterizer::RAS_STEREO_RIGHTEYE)
289                 return;
290
291         // clear the viewports with the background color of the first scene
292         bool doclear = false;
293         KX_SceneList::iterator sceneit;
294         RAS_Rect clearvp, area, viewport;
295
296         for (sceneit = m_scenes.begin(); sceneit != m_scenes.end(); sceneit++)
297         {
298                 KX_Scene* scene = *sceneit;
299                 //const RAS_FrameSettings &framesettings = scene->GetFramingType();
300                 list<class KX_Camera*>* cameras = scene->GetCameras();
301
302                 list<KX_Camera*>::iterator it;
303                 for(it = cameras->begin(); it != cameras->end(); it++)
304                 {
305                         GetSceneViewport(scene, (*it), area, viewport);
306
307                         if(!doclear) {
308                                 clearvp = viewport;
309                                 doclear = true;
310                         }
311                         else {
312                                 if(viewport.GetLeft() < clearvp.GetLeft())
313                                         clearvp.SetLeft(viewport.GetLeft());
314                                 if(viewport.GetBottom() < clearvp.GetBottom())
315                                         clearvp.SetBottom(viewport.GetBottom());
316                                 if(viewport.GetRight() > clearvp.GetRight())
317                                         clearvp.SetRight(viewport.GetRight());
318                                 if(viewport.GetTop() > clearvp.GetTop())
319                                         clearvp.SetTop(viewport.GetTop());
320
321                         }
322                 }
323         }
324
325         if(doclear) {
326                 KX_Scene* firstscene = *m_scenes.begin();
327                 SetBackGround(firstscene->GetWorldInfo());
328
329                 m_canvas->SetViewPort(clearvp.GetLeft(), clearvp.GetBottom(),
330                         clearvp.GetRight(), clearvp.GetTop());  
331                 m_rasterizer->ClearColorBuffer();
332         }
333 }
334
335 bool KX_KetsjiEngine::BeginFrame()
336 {
337         // set the area used for rendering (stereo can assign only a subset)
338         m_rasterizer->SetRenderArea();
339
340         if (m_canvas->BeginDraw())
341         {
342                 ClearFrame();
343
344                 m_rasterizer->BeginFrame(m_drawingmode , m_kxsystem->GetTimeInSeconds());
345                 m_rendertools->BeginFrame(m_rasterizer);
346
347                 return true;
348         }
349         
350         return false;
351 }               
352
353
354 void KX_KetsjiEngine::EndFrame()
355 {
356         // Show profiling info
357         m_logger->StartLog(tc_overhead, m_kxsystem->GetTimeInSeconds(), true);
358         if (m_show_framerate || m_show_profile || (m_show_debug_properties && m_propertiesPresent))
359         {
360                 RenderDebugProperties();
361         }
362
363         m_average_framerate = m_logger->GetAverage();
364         if (m_average_framerate < 1e-6)
365                 m_average_framerate = 1e-6;
366         m_average_framerate = 1.0/m_average_framerate;
367
368         // Go to next profiling measurement, time spend after this call is shown in the next frame.
369         m_logger->NextMeasurement(m_kxsystem->GetTimeInSeconds());
370
371         m_logger->StartLog(tc_rasterizer, m_kxsystem->GetTimeInSeconds(), true);
372         m_rasterizer->EndFrame();
373         // swap backbuffer (drawing into this buffer) <-> front/visible buffer
374         m_rasterizer->SwapBuffers();
375         m_rendertools->EndFrame(m_rasterizer);
376
377         
378         m_canvas->EndDraw();
379 }
380
381 //#include "PIL_time.h"
382 //#include "LinearMath/btQuickprof.h"
383
384
385 bool KX_KetsjiEngine::NextFrame()
386 {
387
388 //      static hidden::Clock sClock;
389
390 m_logger->StartLog(tc_services, m_kxsystem->GetTimeInSeconds(),true);
391
392 //float dt = sClock.getTimeMicroseconds() * 0.000001f;
393 //sClock.reset();
394
395 if (m_bFixedTime)
396         m_clockTime += 1./m_ticrate;
397 else
398 {
399
400 //      m_clockTime += dt;
401         m_clockTime = m_kxsystem->GetTimeInSeconds();
402 }
403         
404         double deltatime = m_clockTime - m_frameTime;
405         if (deltatime<0.f)
406         {
407                 printf("problem with clock\n");
408                 deltatime = 0.f;
409                 m_clockTime = 0.f;
410                 m_frameTime = 0.f;
411         }
412
413
414         // Compute the number of logic frames to do each update (fixed tic bricks)
415         int frames =int(deltatime*m_ticrate);
416 //      if (frames>1)
417 //              printf("****************************************");
418 //      printf("dt = %f, deltatime = %f, frames = %d\n",dt, deltatime,frames);
419         
420 //      if (!frames)
421 //              PIL_sleep_ms(1);
422         
423         KX_SceneList::iterator sceneit;
424         int frameOut = 5;
425         
426         if (frames>frameOut)
427         {
428         
429         //      printf("framedOut: %d\n",frames);
430                 m_frameTime+=(frames-frameOut)*(1.0/m_ticrate);
431                 frames = frameOut;
432         }
433         
434
435         bool doRender = frames>0;
436
437         while (frames)
438         {
439         
440
441                 m_frameTime += 1.0/m_ticrate;
442                 
443                 for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); ++sceneit)
444                 // for each scene, call the proceed functions
445                 {
446                         KX_Scene* scene = *sceneit;
447         
448                         /* Suspension holds the physics and logic processing for an
449                         * entire scene. Objects can be suspended individually, and
450                         * the settings for that preceed the logic and physics
451                         * update. */
452                         m_logger->StartLog(tc_logic, m_kxsystem->GetTimeInSeconds(), true);
453
454                         m_sceneconverter->resetNoneDynamicObjectToIpo();//this is for none dynamic objects with ipo
455
456                         scene->UpdateObjectActivity();
457         
458                         if (!scene->IsSuspended())
459                         {
460                                 // if the scene was suspended recalcutlate the delta tu "curtime"
461                                 m_suspendedtime = scene->getSuspendedTime();
462                                 if (scene->getSuspendedTime()!=0.0)
463                                         scene->setSuspendedDelta(scene->getSuspendedDelta()+m_clockTime-scene->getSuspendedTime());
464                                 m_suspendeddelta = scene->getSuspendedDelta();
465
466                                 
467                                 m_logger->StartLog(tc_network, m_kxsystem->GetTimeInSeconds(), true);
468                                 scene->GetNetworkScene()->proceed(m_frameTime);
469         
470                                 m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
471                                 scene->UpdateParents(m_frameTime);
472                                 
473                                 m_logger->StartLog(tc_physics, m_kxsystem->GetTimeInSeconds(), true);
474                                 // set Python hooks for each scene
475                                 PHY_SetActiveEnvironment(scene->GetPhysicsEnvironment());
476                                 KX_SetActiveScene(scene);
477         
478                                 scene->GetPhysicsEnvironment()->endFrame();
479                                 
480                                 // Update scenegraph after physics step. This maps physics calculations
481                                 // into node positions.         
482                                 m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
483                                 scene->UpdateParents(m_frameTime);
484                                 
485                                 // Process sensors, and controllers
486                                 m_logger->StartLog(tc_logic, m_kxsystem->GetTimeInSeconds(), true);
487                                 scene->LogicBeginFrame(m_frameTime);
488         
489                                 // Scenegraph needs to be updated again, because Logic Controllers 
490                                 // can affect the local matrices.
491                                 m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
492                                 scene->UpdateParents(m_frameTime);
493         
494                                 // Process actuators
495         
496                                 // Do some cleanup work for this logic frame
497                                 m_logger->StartLog(tc_logic, m_kxsystem->GetTimeInSeconds(), true);
498                                 scene->LogicUpdateFrame(m_frameTime, true);
499                                 
500                                 scene->LogicEndFrame();
501         
502                                 // Actuators can affect the scenegraph
503                                 m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
504                                 scene->UpdateParents(m_frameTime);
505                                 
506                                 m_logger->StartLog(tc_physics, m_kxsystem->GetTimeInSeconds(), true);
507                                 scene->GetPhysicsEnvironment()->beginFrame();
508                 
509                                 // Perform physics calculations on the scene. This can involve 
510                                 // many iterations of the physics solver.
511                                 scene->GetPhysicsEnvironment()->proceedDeltaTime(m_frameTime,1.0/m_ticrate);//m_deltatimerealDeltaTime);
512
513                                 m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
514                                 scene->UpdateParents(m_frameTime);
515                         
516                         
517                                 if (m_game2ipo)
518                                 {                                       
519                                         m_sceneconverter->WritePhysicsObjectToAnimationIpo(++m_currentFrame);
520                                 }
521
522                                 scene->setSuspendedTime(0.0);
523                         } // suspended
524                         else
525                                 if(scene->getSuspendedTime()==0.0)
526                                         scene->setSuspendedTime(m_clockTime);
527         
528                         DoSound(scene);
529                         
530                         m_logger->StartLog(tc_services, m_kxsystem->GetTimeInSeconds(), true);
531                 }
532
533                 // update system devices
534                 m_logger->StartLog(tc_logic, m_kxsystem->GetTimeInSeconds(), true);
535                 if (m_keyboarddevice)
536                         m_keyboarddevice->NextFrame();
537         
538                 if (m_mousedevice)
539                         m_mousedevice->NextFrame();
540                 
541                 if (m_networkdevice)
542                         m_networkdevice->NextFrame();
543         
544                 if (m_audiodevice)
545                         m_audiodevice->NextFrame();
546         
547                 // scene management
548                 ProcessScheduledScenes();
549                 
550                 frames--;
551         }
552
553         bool bUseAsyncLogicBricks= false;//true;
554
555         if (bUseAsyncLogicBricks)
556         {       
557                 // Logic update sub frame: this will let some logic bricks run at the
558                 // full frame rate.
559                 for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); ++sceneit)
560                 // for each scene, call the proceed functions
561                 {
562                         KX_Scene* scene = *sceneit;
563
564                         if (!scene->IsSuspended())
565                         {
566                                 // if the scene was suspended recalcutlate the delta tu "curtime"
567                                 m_suspendedtime = scene->getSuspendedTime();
568                                 if (scene->getSuspendedTime()!=0.0)
569                                         scene->setSuspendedDelta(scene->getSuspendedDelta()+m_clockTime-scene->getSuspendedTime());
570                                 m_suspendeddelta = scene->getSuspendedDelta();
571                                 
572                                 // set Python hooks for each scene
573                                 PHY_SetActiveEnvironment(scene->GetPhysicsEnvironment());
574                                 KX_SetActiveScene(scene);
575                                 
576                                 m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
577                                 scene->UpdateParents(m_clockTime);
578
579                                 // Perform physics calculations on the scene. This can involve 
580                                 // many iterations of the physics solver.
581                                 m_logger->StartLog(tc_physics, m_kxsystem->GetTimeInSeconds(), true);
582                                 scene->GetPhysicsEnvironment()->proceedDeltaTime(m_clockTime,0.f);
583                                 // Update scenegraph after physics step. This maps physics calculations
584                                 // into node positions.         
585                                 m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
586                                 scene->UpdateParents(m_clockTime);
587                                 
588                                 // Do some cleanup work for this logic frame
589                                 m_logger->StartLog(tc_logic, m_kxsystem->GetTimeInSeconds(), true);
590                                 scene->LogicUpdateFrame(m_clockTime, false);
591
592                                 // Actuators can affect the scenegraph
593                                 m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
594                                 scene->UpdateParents(m_clockTime);
595                                  
596                                 scene->setSuspendedTime(0.0);
597                         } // suspended
598                         else
599                                 if(scene->getSuspendedTime()==0.0)
600                                         scene->setSuspendedTime(m_clockTime);
601
602                         DoSound(scene);
603
604                         m_logger->StartLog(tc_services, m_kxsystem->GetTimeInSeconds(), true);
605                 }
606         }
607
608
609         m_previousClockTime = m_clockTime;
610         
611         // Start logging time spend outside main loop
612         m_logger->StartLog(tc_outside, m_kxsystem->GetTimeInSeconds(), true);
613         
614         return doRender;
615 }
616
617
618
619 void KX_KetsjiEngine::Render()
620 {
621         KX_Scene* firstscene = *m_scenes.begin();
622         const RAS_FrameSettings &framesettings = firstscene->GetFramingType();
623
624         m_logger->StartLog(tc_rasterizer, m_kxsystem->GetTimeInSeconds(), true);
625
626         // hiding mouse cursor each frame
627         // (came back when going out of focus and then back in again)
628         if (m_hideCursor)
629                 m_canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);
630
631         // clear the entire game screen with the border color
632         // only once per frame
633         m_canvas->BeginDraw();
634         if (m_drawingmode == RAS_IRasterizer::KX_TEXTURED) {
635                 m_canvas->SetViewPort(0, 0, m_canvas->GetWidth(), m_canvas->GetHeight());
636                 if (m_overrideFrameColor)
637                 {
638                         // Do not use the framing bar color set in the Blender scenes
639                         m_canvas->ClearColor(
640                                 m_overrideFrameColorR,
641                                 m_overrideFrameColorG,
642                                 m_overrideFrameColorB,
643                                 1.0
644                                 );
645                 }
646                 else
647                 {
648                         // Use the framing bar color set in the Blender scenes
649                         m_canvas->ClearColor(
650                                 framesettings.BarRed(),
651                                 framesettings.BarGreen(),
652                                 framesettings.BarBlue(),
653                                 1.0
654                                 );
655                 }
656                 // clear the -whole- viewport
657                 m_canvas->ClearBuffer(RAS_ICanvas::COLOR_BUFFER|RAS_ICanvas::DEPTH_BUFFER);
658         }
659
660         m_rasterizer->SetEye(RAS_IRasterizer::RAS_STEREO_LEFTEYE);
661
662         // BeginFrame() sets the actual drawing area. You can use a part of the window
663         if (!BeginFrame())
664                 return;
665
666         KX_SceneList::iterator sceneit;
667         for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); sceneit++)
668         // for each scene, call the proceed functions
669         {
670                 KX_Scene* scene = *sceneit;
671                 KX_Camera* cam = scene->GetActiveCamera();
672                 // pass the scene's worldsettings to the rasterizer
673                 SetWorldSettings(scene->GetWorldInfo());
674
675                 // shadow buffers
676                 RenderShadowBuffers(scene);
677
678                 // Avoid drawing the scene with the active camera twice when it's viewport is enabled
679                 if(cam && !cam->GetViewport())
680                 {
681                         if (scene->IsClearingZBuffer())
682                                 m_rasterizer->ClearDepthBuffer();
683         
684                         m_rendertools->SetAuxilaryClientInfo(scene);
685         
686                         // do the rendering
687                         RenderFrame(scene, cam);
688                 }
689                 
690                 list<class KX_Camera*>* cameras = scene->GetCameras();
691                 
692                 // Draw the scene once for each camera with an enabled viewport
693                 list<KX_Camera*>::iterator it = cameras->begin();
694                 while(it != cameras->end())
695                 {
696                         if((*it)->GetViewport())
697                         {
698                                 if (scene->IsClearingZBuffer())
699                                         m_rasterizer->ClearDepthBuffer();
700                 
701                                 m_rendertools->SetAuxilaryClientInfo(scene);
702                 
703                                 // do the rendering
704                                 RenderFrame(scene, (*it));
705                         }
706                         
707                         it++;
708                 }
709         }
710
711         // only one place that checks for stereo
712         if(m_rasterizer->Stereo())
713         {
714                 m_rasterizer->SetEye(RAS_IRasterizer::RAS_STEREO_RIGHTEYE);
715
716                 if (!BeginFrame())
717                         return;
718
719
720                 for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); sceneit++)
721                 // for each scene, call the proceed functions
722                 {
723                         KX_Scene* scene = *sceneit;
724                         KX_Camera* cam = scene->GetActiveCamera();
725
726                         // pass the scene's worldsettings to the rasterizer
727                         SetWorldSettings(scene->GetWorldInfo());
728                 
729                         if (scene->IsClearingZBuffer())
730                                 m_rasterizer->ClearDepthBuffer();
731
732                         //pass the scene, for picking and raycasting (shadows)
733                         m_rendertools->SetAuxilaryClientInfo(scene);
734
735                         // do the rendering
736                         //RenderFrame(scene);
737                         RenderFrame(scene, cam);
738
739                         list<class KX_Camera*>* cameras = scene->GetCameras();                  
740         
741                         // Draw the scene once for each camera with an enabled viewport
742                         list<KX_Camera*>::iterator it = cameras->begin();
743                         while(it != cameras->end())
744                         {
745                                 if((*it)->GetViewport())
746                                 {
747                                         if (scene->IsClearingZBuffer())
748                                                 m_rasterizer->ClearDepthBuffer();
749                         
750                                         m_rendertools->SetAuxilaryClientInfo(scene);
751                         
752                                         // do the rendering
753                                         RenderFrame(scene, (*it));
754                                 }
755                                 
756                                 it++;
757                         }
758                 }
759         } // if(m_rasterizer->Stereo())
760
761         EndFrame();
762 }
763
764
765
766 void KX_KetsjiEngine::RequestExit(int exitrequestmode)
767 {
768         m_exitcode = exitrequestmode;
769 }
770
771
772
773 void KX_KetsjiEngine::SetNameNextGame(const STR_String& nextgame)
774 {
775         m_exitstring = nextgame;
776 }
777
778
779
780 int KX_KetsjiEngine::GetExitCode()
781 {
782         // if a gameactuator has set an exitcode or if there are no scenes left
783         if (!m_exitcode)
784         {
785                 if (m_scenes.begin()==m_scenes.end())
786                         m_exitcode = KX_EXIT_REQUEST_NO_SCENES_LEFT;
787         }
788
789         return m_exitcode;
790 }
791
792
793
794 const STR_String& KX_KetsjiEngine::GetExitString()
795 {
796         return m_exitstring;
797 }
798
799
800
801 void KX_KetsjiEngine::DoSound(KX_Scene* scene)
802 {
803         m_logger->StartLog(tc_sound, m_kxsystem->GetTimeInSeconds(), true);
804
805         KX_Camera* cam = scene->GetActiveCamera();
806         if (!cam)
807                 return;
808         MT_Point3 listenerposition = cam->NodeGetWorldPosition();
809         MT_Vector3 listenervelocity = cam->GetLinearVelocity();
810         MT_Matrix3x3 listenerorientation = cam->NodeGetWorldOrientation();
811
812         SND_Scene* soundscene = scene->GetSoundScene();
813         soundscene->SetListenerTransform(
814                 listenerposition,
815                 listenervelocity,
816                 listenerorientation);
817
818         soundscene->Proceed();
819 }
820
821
822
823 void KX_KetsjiEngine::SetBackGround(KX_WorldInfo* wi)
824 {
825         if (wi->hasWorld())
826         {
827                 if (m_drawingmode == RAS_IRasterizer::KX_TEXTURED)
828                 {       
829                         m_rasterizer->SetBackColor(
830                                 wi->getBackColorRed(),
831                                 wi->getBackColorGreen(),
832                                 wi->getBackColorBlue(),
833                                 0.0
834                         );
835                 }
836         }
837 }
838
839
840
841 void KX_KetsjiEngine::SetWorldSettings(KX_WorldInfo* wi)
842 {
843         if (wi->hasWorld())
844         {
845                 // ...
846                 m_rasterizer->SetAmbientColor(
847                         wi->getAmbientColorRed(),
848                         wi->getAmbientColorGreen(),
849                         wi->getAmbientColorBlue()
850                 );
851
852                 if (m_drawingmode == RAS_IRasterizer::KX_TEXTURED)
853                 {       
854                         if (wi->hasMist())
855                         {
856                                 m_rasterizer->SetFog(
857                                         wi->getMistStart(),
858                                         wi->getMistDistance(),
859                                         wi->getMistColorRed(),
860                                         wi->getMistColorGreen(),
861                                         wi->getMistColorBlue()
862                                 );
863                         }
864                         else
865                         {
866                                 m_rasterizer->DisableFog();
867                         }
868                 }
869         }
870 }
871
872
873
874 void KX_KetsjiEngine::SetDrawType(int drawingmode)
875 {
876         m_drawingmode = drawingmode;
877 }
878
879
880         
881 void KX_KetsjiEngine::EnableCameraOverride(const STR_String& forscene)
882 {
883         m_overrideCam = true;
884         m_overrideSceneName = forscene;
885 }
886
887
888
889 void KX_KetsjiEngine::SetCameraZoom(float camzoom)
890 {
891         m_cameraZoom = camzoom;
892 }
893
894
895
896 void KX_KetsjiEngine::SetCameraOverrideUseOrtho(bool useOrtho)
897 {
898         m_overrideCamUseOrtho = useOrtho;
899 }
900
901
902
903 void KX_KetsjiEngine::SetCameraOverrideProjectionMatrix(const MT_CmMatrix4x4& mat)
904 {
905         m_overrideCamProjMat = mat;
906 }
907
908
909 void KX_KetsjiEngine::SetCameraOverrideViewMatrix(const MT_CmMatrix4x4& mat)
910 {
911         m_overrideCamViewMat = mat;
912 }
913
914 void KX_KetsjiEngine::SetCameraOverrideClipping(float near, float far)
915 {
916         m_overrideCamNear = near;
917         m_overrideCamFar = far;
918 }
919
920 void KX_KetsjiEngine::GetSceneViewport(KX_Scene *scene, KX_Camera* cam, RAS_Rect& area, RAS_Rect& viewport)
921 {
922         // In this function we make sure the rasterizer settings are upto
923         // date. We compute the viewport so that logic
924         // using this information is upto date.
925
926         // Note we postpone computation of the projection matrix
927         // so that we are using the latest camera position.
928         if (cam->GetViewport()) {
929                 RAS_Rect userviewport;
930
931                 userviewport.SetLeft(cam->GetViewportLeft()); 
932                 userviewport.SetBottom(cam->GetViewportBottom());
933                 userviewport.SetRight(cam->GetViewportRight());
934                 userviewport.SetTop(cam->GetViewportTop());
935
936                 // Don't do bars on user specified viewport
937                 RAS_FrameSettings settings = scene->GetFramingType();
938                 if(settings.FrameType() == RAS_FrameSettings::e_frame_bars)
939                         settings.SetFrameType(RAS_FrameSettings::e_frame_extend);
940
941                 RAS_FramingManager::ComputeViewport(
942                         scene->GetFramingType(),
943                         userviewport,
944                         viewport
945                 );
946
947                 area = userviewport;
948         }
949         else if ( m_overrideCam || (scene->GetName() != m_overrideSceneName) ||  m_overrideCamUseOrtho ) {
950                 RAS_FramingManager::ComputeViewport(
951                         scene->GetFramingType(),
952                         m_canvas->GetDisplayArea(),
953                         viewport
954                 );
955
956                 area = m_canvas->GetDisplayArea();
957         } else {
958                 viewport.SetLeft(0); 
959                 viewport.SetBottom(0);
960                 viewport.SetRight(int(m_canvas->GetWidth()));
961                 viewport.SetTop(int(m_canvas->GetHeight()));
962
963                 area = m_canvas->GetDisplayArea();
964         }
965 }
966
967 void KX_KetsjiEngine::RenderShadowBuffers(KX_Scene *scene)
968 {
969         CListValue *objectlist = scene->GetObjectList();
970         int i, drawmode;
971
972         m_rendertools->SetAuxilaryClientInfo(scene);
973
974         for(i=0; i<objectlist->GetCount(); i++) {
975                 KX_GameObject *gameobj = (KX_GameObject*)objectlist->GetValue(i);
976
977                 if(!gameobj->IsLight())
978                         continue;
979
980                 KX_LightObject *light = (KX_LightObject*)gameobj;
981
982                 light->Update();
983
984                 if(m_drawingmode == RAS_IRasterizer::KX_TEXTURED && light->HasShadowBuffer()) {
985                         /* make temporary camera */
986                         RAS_CameraData camdata = RAS_CameraData();
987                         KX_Camera *cam = new KX_Camera(scene, scene->m_callbacks, camdata, false);
988                         cam->SetName("__shadow__cam__");
989
990                         MT_Transform camtrans;
991
992                         /* switch drawmode for speed */
993                         drawmode = m_rasterizer->GetDrawingMode();
994                         m_rasterizer->SetDrawingMode(RAS_IRasterizer::KX_SHADOW);
995
996                         /* binds framebuffer object, sets up camera .. */
997                         light->BindShadowBuffer(m_rasterizer, cam, camtrans);
998
999                         /* update scene */
1000                         scene->UpdateMeshTransformations();
1001                         scene->CalculateVisibleMeshes(m_rasterizer, cam, light->GetShadowLayer());
1002
1003                         /* render */
1004                         m_rasterizer->ClearDepthBuffer();
1005                         scene->RenderBuckets(camtrans, m_rasterizer, m_rendertools);
1006
1007                         /* unbind framebuffer object, restore drawmode, free camera */
1008                         light->UnbindShadowBuffer(m_rasterizer);
1009                         m_rasterizer->SetDrawingMode(drawmode);
1010                         cam->Release();
1011                 }
1012         }
1013 }
1014         
1015 // update graphics
1016 void KX_KetsjiEngine::RenderFrame(KX_Scene* scene, KX_Camera* cam)
1017 {
1018         bool override_camera;
1019         RAS_Rect viewport, area;
1020         float left, right, bottom, top, nearfrust, farfrust, focallength;
1021         const float ortho = 100.0;
1022 //      KX_Camera* cam = scene->GetActiveCamera();
1023         
1024         if (!cam)
1025                 return;
1026
1027         GetSceneViewport(scene, cam, area, viewport);
1028
1029         // store the computed viewport in the scene
1030         scene->SetSceneViewport(viewport);      
1031
1032         // set the viewport for this frame and scene
1033         m_canvas->SetViewPort(viewport.GetLeft(), viewport.GetBottom(),
1034                 viewport.GetRight(), viewport.GetTop());        
1035         
1036         // see KX_BlenderMaterial::Activate
1037         //m_rasterizer->SetAmbient();
1038         m_rasterizer->DisplayFog();
1039
1040         override_camera = m_overrideCam && (scene->GetName() == m_overrideSceneName);
1041         override_camera = override_camera && (cam->GetName() == "__default__cam__");
1042
1043         if (override_camera && m_overrideCamUseOrtho) {
1044                 MT_CmMatrix4x4 projmat = m_overrideCamProjMat;
1045                 m_rasterizer->SetProjectionMatrix(projmat);
1046         } else if (cam->hasValidProjectionMatrix() && !cam->GetViewport() )
1047         {
1048                 m_rasterizer->SetProjectionMatrix(cam->GetProjectionMatrix());
1049         } else
1050         {
1051                 RAS_FrameFrustum frustum;
1052                 float lens = cam->GetLens();
1053                 bool orthographic = !cam->GetCameraData()->m_perspective;
1054                 nearfrust = cam->GetCameraNear();
1055                 farfrust = cam->GetCameraFar();
1056                 focallength = cam->GetFocalLength();
1057
1058                 if(override_camera) {
1059                         nearfrust = m_overrideCamNear;
1060                         farfrust = m_overrideCamFar;
1061                 }
1062
1063                 if (orthographic) {
1064                         lens *= ortho;
1065                         nearfrust = (nearfrust + 1.0)*ortho;
1066                         farfrust *= ortho;
1067                 }
1068                 
1069                 RAS_FramingManager::ComputeFrustum(
1070                         scene->GetFramingType(),
1071                         area,
1072                         viewport,
1073                         lens,
1074                         nearfrust,
1075                         farfrust,
1076                         frustum
1077                 );
1078
1079                 left = frustum.x1 * m_cameraZoom;
1080                 right = frustum.x2 * m_cameraZoom;
1081                 bottom = frustum.y1 * m_cameraZoom;
1082                 top = frustum.y2 * m_cameraZoom;
1083                 nearfrust = frustum.camnear;
1084                 farfrust = frustum.camfar;
1085
1086                 MT_Matrix4x4 projmat = m_rasterizer->GetFrustumMatrix(
1087                         left, right, bottom, top, nearfrust, farfrust, focallength);
1088
1089                 cam->SetProjectionMatrix(projmat);
1090                 
1091                 // Otherwise the projection matrix for each eye will be the same...
1092                 if (m_rasterizer->Stereo())
1093                         cam->InvalidateProjectionMatrix();
1094         }
1095
1096         MT_Transform camtrans(cam->GetWorldToCamera());
1097         if (!cam->GetCameraData()->m_perspective)
1098                 camtrans.getOrigin()[2] *= ortho;
1099         MT_Matrix4x4 viewmat(camtrans);
1100         
1101         m_rasterizer->SetViewMatrix(viewmat, cam->NodeGetWorldPosition(),
1102                 cam->GetCameraLocation(), cam->GetCameraOrientation());
1103         cam->SetModelviewMatrix(viewmat);
1104
1105         scene->UpdateMeshTransformations();
1106
1107         // The following actually reschedules all vertices to be
1108         // redrawn. There is a cache between the actual rescheduling
1109         // and this call though. Visibility is imparted when this call
1110         // runs through the individual objects.
1111         scene->CalculateVisibleMeshes(m_rasterizer,cam);
1112
1113         scene->RenderBuckets(camtrans, m_rasterizer, m_rendertools);
1114         
1115         PostRenderFrame();
1116 }
1117
1118 void KX_KetsjiEngine::PostRenderFrame()
1119 {
1120         m_rendertools->PushMatrix();
1121         m_rendertools->Render2DFilters(m_canvas);
1122         m_rendertools->MotionBlur(m_rasterizer);
1123         m_rendertools->PopMatrix();
1124 }
1125
1126 void KX_KetsjiEngine::StopEngine()
1127 {
1128         if (m_bInitialized)
1129         {
1130
1131                 if (m_game2ipo)
1132                 {
1133 //                      printf("TestHandlesPhysicsObjectToAnimationIpo\n");
1134                         m_sceneconverter->TestHandlesPhysicsObjectToAnimationIpo();
1135                 }
1136
1137                 KX_SceneList::iterator sceneit;
1138                 for (sceneit = m_scenes.begin();sceneit != m_scenes.end() ; sceneit++)
1139                 {
1140                         KX_Scene* scene = *sceneit;
1141                         m_sceneconverter->RemoveScene(scene);
1142                 }       
1143                 m_scenes.clear();
1144
1145                 // cleanup all the stuff                
1146                 m_rasterizer->Exit();
1147         }
1148 }
1149
1150 // Scene Management is able to switch between scenes
1151 // and have several scene's running in parallel
1152 void KX_KetsjiEngine::AddScene(KX_Scene* scene)
1153
1154         m_scenes.push_back(scene);
1155         PostProcessScene(scene);
1156         SceneListsChanged();
1157 }
1158
1159
1160
1161 void KX_KetsjiEngine::PostProcessScene(KX_Scene* scene)
1162 {
1163         bool override_camera = (m_overrideCam && (scene->GetName() == m_overrideSceneName));
1164         
1165                 // if there is no activecamera, or the camera is being
1166                 // overridden we need to construct a temporarily camera
1167         if (!scene->GetActiveCamera() || override_camera)
1168         {
1169                 KX_Camera* activecam = NULL;
1170
1171                 RAS_CameraData camdata = RAS_CameraData();
1172                 activecam = new KX_Camera(scene,KX_Scene::m_callbacks,camdata, false);
1173                 activecam->SetName("__default__cam__");
1174         
1175                         // set transformation
1176                 if (override_camera) {
1177                         const MT_CmMatrix4x4& cammatdata = m_overrideCamViewMat;
1178                         MT_Transform trans = MT_Transform(cammatdata.getPointer());
1179                         MT_Transform camtrans;
1180                         camtrans.invert(trans);
1181                         
1182                         activecam->NodeSetLocalPosition(camtrans.getOrigin());
1183                         activecam->NodeSetLocalOrientation(camtrans.getBasis());
1184                         activecam->NodeUpdateGS(0,true);
1185                 } else {
1186                         activecam->NodeSetLocalPosition(MT_Point3(0.0, 0.0, 0.0));
1187                         activecam->NodeSetLocalOrientation(MT_Vector3(0.0, 0.0, 0.0));
1188                         activecam->NodeUpdateGS(0,true);
1189                 }
1190
1191                 scene->AddCamera(activecam);
1192                 scene->SetActiveCamera(activecam);
1193                 scene->GetObjectList()->Add(activecam->AddRef());
1194                 scene->GetRootParentList()->Add(activecam->AddRef());
1195                 //done with activecam
1196                 activecam->Release();
1197         }
1198         
1199         scene->UpdateParents(0.0);
1200 }
1201
1202
1203
1204 void KX_KetsjiEngine::RenderDebugProperties()
1205 {
1206         STR_String debugtxt;
1207         int xcoord = 10;        // mmmm, these constants were taken from blender source
1208         int ycoord = 14;        // to 'mimic' behaviour
1209
1210         float tottime = m_logger->GetAverage();
1211         if (tottime < 1e-6f) {
1212                 tottime = 1e-6f;
1213         }
1214
1215         // Set viewport to entire canvas
1216         RAS_Rect viewport;
1217         m_canvas->SetViewPort(0, 0, int(m_canvas->GetWidth()), int(m_canvas->GetHeight()));
1218         
1219         /* Framerate display */
1220         if (m_show_framerate) {
1221                 debugtxt.Format("swap : %.3f (%.3f frames per second)", tottime, 1.0/tottime);
1222                 m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED, 
1223                                                                         debugtxt.Ptr(),
1224                                                                         xcoord,
1225                                                                         ycoord, 
1226                                                                         m_canvas->GetWidth() /* RdV, TODO ?? */, 
1227                                                                         m_canvas->GetHeight() /* RdV, TODO ?? */);
1228                 ycoord += 14;
1229         }
1230
1231         /* Profile and framerate display */
1232         if (m_show_profile)
1233         {               
1234                 for (int j = tc_first; j < tc_numCategories; j++)
1235                 {
1236                         debugtxt.Format(m_profileLabels[j]);
1237                         m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED, 
1238                                                                                 debugtxt.Ptr(),
1239                                                                                 xcoord,ycoord,
1240                                                                                 m_canvas->GetWidth(), 
1241                                                                                 m_canvas->GetHeight());
1242                         double time = m_logger->GetAverage((KX_TimeCategory)j);
1243                         debugtxt.Format("%2.2f %%", time/tottime * 100.f);
1244                         m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED, 
1245                                                                                 debugtxt.Ptr(),
1246                                                                                 xcoord + 60 ,ycoord,
1247                                                                                 m_canvas->GetWidth(), 
1248                                                                                 m_canvas->GetHeight());
1249                         ycoord += 14;
1250                 }
1251         }
1252
1253         /* Property display*/
1254         if (m_show_debug_properties && m_propertiesPresent)
1255         {
1256                 KX_SceneList::iterator sceneit;
1257                 for (sceneit = m_scenes.begin();sceneit != m_scenes.end() ; sceneit++)
1258                 {
1259                         KX_Scene* scene = *sceneit;
1260                         /* the 'normal' debug props */
1261                         vector<SCA_DebugProp*>& debugproplist = scene->GetDebugProperties();
1262                         
1263                         for (vector<SCA_DebugProp*>::iterator it = debugproplist.begin();
1264                                  !(it==debugproplist.end());it++)
1265                         {
1266                                 CValue* propobj = (*it)->m_obj;
1267                                 STR_String objname = propobj->GetName();
1268                                 STR_String propname = (*it)->m_name;
1269                                 if (propname == "__state__")
1270                                 {
1271                                         // reserve name for object state
1272                                         KX_GameObject* gameobj = static_cast<KX_GameObject*>(propobj);
1273                                         unsigned int state = gameobj->GetState();
1274                                         debugtxt = objname + "." + propname + " = ";
1275                                         bool first = true;
1276                                         for (int statenum=1;state;state >>= 1, statenum++)
1277                                         {
1278                                                 if (state & 1)
1279                                                 {
1280                                                         if (!first)
1281                                                         {
1282                                                                 debugtxt += ",";
1283                                                         }
1284                                                         debugtxt += STR_String(statenum);
1285                                                         first = false;
1286                                                 }
1287                                         }
1288                                         m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED, 
1289                                                                                                         debugtxt.Ptr(),
1290                                                                                                         xcoord,
1291                                                                                                         ycoord,
1292                                                                                                         m_canvas->GetWidth(),
1293                                                                                                         m_canvas->GetHeight());
1294                                         ycoord += 14;
1295                                 }
1296                                 else
1297                                 {
1298                                         CValue* propval = propobj->GetProperty(propname);
1299                                         if (propval)
1300                                         {
1301                                                 STR_String text = propval->GetText();
1302                                                 debugtxt = objname + "." + propname + " = " + text;
1303                                                 m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED, 
1304                                                                                                         debugtxt.Ptr(),
1305                                                                                                         xcoord,
1306                                                                                                         ycoord,
1307                                                                                                         m_canvas->GetWidth(),
1308                                                                                                         m_canvas->GetHeight());
1309                                                 ycoord += 14;
1310                                         }
1311                                 }
1312                         }
1313                 }
1314         }
1315 }
1316
1317
1318 KX_SceneList* KX_KetsjiEngine::CurrentScenes()
1319 {
1320         return &m_scenes;       
1321 }
1322
1323
1324
1325 KX_Scene* KX_KetsjiEngine::FindScene(const STR_String& scenename)
1326 {
1327         KX_SceneList::iterator sceneit = m_scenes.begin();
1328
1329         // bit risky :) better to split the second clause 
1330         while ( (sceneit != m_scenes.end()) 
1331                         && ((*sceneit)->GetName() != scenename))
1332         {
1333                 sceneit++;
1334         }
1335
1336         return ((sceneit == m_scenes.end()) ? NULL : *sceneit); 
1337 }
1338
1339
1340
1341 void KX_KetsjiEngine::ConvertAndAddScene(const STR_String& scenename,bool overlay)
1342 {
1343         // only add scene when it doesn't exist!
1344         if (FindScene(scenename))
1345         {
1346                 STR_String tmpname = scenename;
1347                 printf("warning: scene %s already exists, not added!\n",tmpname.Ptr());
1348         }
1349         else
1350         {
1351                 if (overlay)
1352                 {
1353                         m_addingOverlayScenes.insert(scenename);
1354                 }
1355                 else
1356                 {
1357                         m_addingBackgroundScenes.insert(scenename);
1358                 }
1359         }
1360 }
1361
1362
1363
1364
1365 void KX_KetsjiEngine::RemoveScene(const STR_String& scenename)
1366 {
1367         if (FindScene(scenename))
1368         {
1369                 m_removingScenes.insert(scenename);
1370         }
1371         else
1372         {
1373 //              STR_String tmpname = scenename;
1374                 std::cout << "warning: scene " << scenename << " does not exist, not removed!" << std::endl;
1375         }
1376 }
1377
1378
1379
1380 void KX_KetsjiEngine::RemoveScheduledScenes()
1381 {
1382         if (m_removingScenes.size())
1383         {
1384                 set<STR_String>::iterator scenenameit;
1385                 for (scenenameit=m_removingScenes.begin();scenenameit != m_removingScenes.end();scenenameit++)
1386                 {
1387                         STR_String scenename = *scenenameit;
1388
1389                         KX_SceneList::iterator sceneit;
1390                         for (sceneit = m_scenes.begin();sceneit != m_scenes.end() ; sceneit++)
1391                         {
1392                                 KX_Scene* scene = *sceneit;
1393                                 if (scene->GetName()==scenename)
1394                                 {
1395                                         m_sceneconverter->RemoveScene(scene);
1396                                         m_scenes.erase(sceneit);
1397                                         break;
1398                                 }
1399                         }       
1400                 }
1401                 m_removingScenes.clear();
1402         }
1403 }
1404
1405
1406
1407 KX_Scene* KX_KetsjiEngine::CreateScene(const STR_String& scenename)
1408 {
1409         Scene *scene = m_sceneconverter->GetBlenderSceneForName(scenename);
1410         KX_Scene* tmpscene = new KX_Scene(m_keyboarddevice,
1411                                                                           m_mousedevice,
1412                                                                           m_networkdevice,
1413                                                                           m_audiodevice,
1414                                                                           scenename,
1415                                                                           scene);
1416
1417         m_sceneconverter->ConvertScene(scenename,
1418                                                           tmpscene,
1419                                                           m_pythondictionary,
1420                                                           m_keyboarddevice,
1421                                                           m_rendertools,
1422                                                           m_canvas);
1423
1424         return tmpscene;
1425 }
1426
1427
1428
1429 void KX_KetsjiEngine::AddScheduledScenes()
1430 {
1431         set<STR_String>::iterator scenenameit;
1432
1433         if (m_addingOverlayScenes.size())
1434         {
1435                 for (scenenameit = m_addingOverlayScenes.begin();
1436                         scenenameit != m_addingOverlayScenes.end();
1437                         scenenameit++)
1438                 {
1439                         STR_String scenename = *scenenameit;
1440                         KX_Scene* tmpscene = CreateScene(scenename);
1441                         m_scenes.push_back(tmpscene);
1442                         PostProcessScene(tmpscene);
1443                 }
1444                 m_addingOverlayScenes.clear();
1445         }
1446         
1447         if (m_addingBackgroundScenes.size())
1448         {
1449                 for (scenenameit = m_addingBackgroundScenes.begin();
1450                         scenenameit != m_addingBackgroundScenes.end();
1451                         scenenameit++)
1452                 {
1453                         STR_String scenename = *scenenameit;
1454                         KX_Scene* tmpscene = CreateScene(scenename);
1455                         m_scenes.insert(m_scenes.begin(),tmpscene);
1456                         PostProcessScene(tmpscene);
1457
1458                 }
1459                 m_addingBackgroundScenes.clear();
1460         }
1461 }
1462
1463
1464
1465 void KX_KetsjiEngine::ReplaceScene(const STR_String& oldscene,const STR_String& newscene)
1466 {
1467         m_replace_scenes.insert(std::make_pair(oldscene,newscene));
1468 }
1469
1470 // replace scene is not the same as removing and adding because the
1471 // scene must be in exact the same place (to maintain drawingorder)
1472 // (nzc) - should that not be done with a scene-display list? It seems
1473 // stupid to rely on the mem allocation order...
1474 void KX_KetsjiEngine::ReplaceScheduledScenes()
1475 {
1476         if (m_replace_scenes.size())
1477         {
1478                 set<pair<STR_String,STR_String> >::iterator scenenameit;
1479                 
1480                 for (scenenameit = m_replace_scenes.begin();
1481                         scenenameit != m_replace_scenes.end();
1482                         scenenameit++)
1483                 {
1484                         STR_String oldscenename = (*scenenameit).first;
1485                         STR_String newscenename = (*scenenameit).second;
1486                         int i=0;
1487                         /* Scenes are not supposed to be included twice... I think */
1488                         KX_SceneList::iterator sceneit;
1489                         for (sceneit = m_scenes.begin();sceneit != m_scenes.end() ; sceneit++)
1490                         {
1491                                 KX_Scene* scene = *sceneit;
1492                                 if (scene->GetName() == oldscenename)
1493                                 {
1494                                         m_sceneconverter->RemoveScene(scene);
1495                                         KX_Scene* tmpscene = CreateScene(newscenename);
1496                                         m_scenes[i]=tmpscene;
1497                                         PostProcessScene(tmpscene);
1498                                 }
1499                                 i++;
1500                         }
1501                 }
1502                 m_replace_scenes.clear();
1503         }       
1504 }
1505
1506
1507
1508 void KX_KetsjiEngine::SuspendScene(const STR_String& scenename)
1509 {
1510         KX_Scene*  scene = FindScene(scenename);
1511         if (scene) scene->Suspend();
1512 }
1513
1514
1515
1516 void KX_KetsjiEngine::ResumeScene(const STR_String& scenename)
1517 {
1518         KX_Scene*  scene = FindScene(scenename);
1519         if (scene) scene->Resume();
1520 }
1521
1522
1523
1524 void KX_KetsjiEngine::SetUseFixedTime(bool bUseFixedTime)
1525 {
1526         m_bFixedTime = bUseFixedTime;
1527 }
1528
1529
1530 void    KX_KetsjiEngine::SetGame2IpoMode(bool game2ipo,int startFrame)
1531 {
1532         m_game2ipo = game2ipo;
1533         if (game2ipo)
1534         {
1535                 //when recording physics keyframes, always run at a fixed framerate
1536                 m_bFixedTime = true;
1537         }
1538         m_currentFrame = startFrame;
1539 }
1540
1541 bool KX_KetsjiEngine::GetUseFixedTime(void) const
1542 {
1543         return m_bFixedTime;
1544 }
1545
1546 double KX_KetsjiEngine::GetSuspendedDelta()
1547 {
1548         return m_suspendeddelta;
1549 }
1550
1551 double KX_KetsjiEngine::GetTicRate()
1552 {
1553         return m_ticrate;
1554 }
1555
1556 void KX_KetsjiEngine::SetTicRate(double ticrate)
1557 {
1558         m_ticrate = ticrate;
1559 }
1560
1561 double KX_KetsjiEngine::GetAnimFrameRate()
1562 {
1563         return m_anim_framerate;
1564 }
1565
1566 double KX_KetsjiEngine::GetClockTime(void) const
1567 {
1568         return m_clockTime;
1569 }
1570
1571 void KX_KetsjiEngine::SetAnimFrameRate(double framerate)
1572 {
1573         m_anim_framerate = framerate;
1574 }
1575
1576 double KX_KetsjiEngine::GetAverageFrameRate()
1577 {
1578         return m_average_framerate;
1579 }
1580
1581 void KX_KetsjiEngine::SetTimingDisplay(bool frameRate, bool profile, bool properties)
1582 {
1583         m_show_framerate = frameRate;
1584         m_show_profile = profile;
1585         m_show_debug_properties = properties;
1586 }
1587
1588
1589
1590 void KX_KetsjiEngine::GetTimingDisplay(bool& frameRate, bool& profile, bool& properties) const
1591 {
1592         frameRate = m_show_framerate;
1593         profile = m_show_profile;
1594         properties = m_show_debug_properties;
1595 }
1596
1597
1598
1599 void KX_KetsjiEngine::ProcessScheduledScenes(void)
1600 {
1601         // Check whether there will be changes to the list of scenes
1602         if (m_addingOverlayScenes.size() ||
1603                 m_addingBackgroundScenes.size() ||
1604                 m_replace_scenes.size() ||
1605                 m_removingScenes.size()) {
1606
1607                 // Change the scene list
1608                 ReplaceScheduledScenes();
1609                 RemoveScheduledScenes();
1610                 AddScheduledScenes();
1611
1612                 // Notify
1613                 SceneListsChanged();
1614         }
1615 }
1616
1617
1618
1619 void KX_KetsjiEngine::SceneListsChanged(void)
1620 {
1621         m_propertiesPresent = false;
1622         KX_SceneList::iterator sceneit = m_scenes.begin();
1623         while ((sceneit != m_scenes.end()) && (!m_propertiesPresent))
1624         {
1625                 KX_Scene* scene = *sceneit;
1626                 vector<SCA_DebugProp*>& debugproplist = scene->GetDebugProperties();    
1627                 m_propertiesPresent = !debugproplist.empty();
1628                 sceneit++;
1629         }
1630 }
1631
1632
1633 void KX_KetsjiEngine::SetHideCursor(bool hideCursor)
1634 {
1635         m_hideCursor = hideCursor;
1636 }
1637
1638
1639 bool KX_KetsjiEngine::GetHideCursor(void) const
1640 {
1641         return m_hideCursor;
1642 }
1643
1644
1645 void KX_KetsjiEngine::SetUseOverrideFrameColor(bool overrideFrameColor)
1646 {
1647         m_overrideFrameColor = overrideFrameColor;
1648 }
1649
1650
1651 bool KX_KetsjiEngine::GetUseOverrideFrameColor(void) const
1652 {
1653         return m_overrideFrameColor;
1654 }
1655
1656
1657 void KX_KetsjiEngine::SetOverrideFrameColor(float r, float g, float b)
1658 {
1659         m_overrideFrameColorR = r;
1660         m_overrideFrameColorG = g;
1661         m_overrideFrameColorB = b;
1662 }
1663
1664
1665 void KX_KetsjiEngine::GetOverrideFrameColor(float& r, float& g, float& b) const
1666 {
1667         r = m_overrideFrameColorR;
1668         g = m_overrideFrameColorG;
1669         b = m_overrideFrameColorB;
1670 }
1671
1672
1673