97b4213b8bd4e9a5dcc93c893c424333b6fa819a
[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         if (scene->GetPhysicsEnvironment())
1116                 scene->GetPhysicsEnvironment()->debugDrawWorld();
1117         
1118         m_rasterizer->FlushDebugLines();
1119
1120         PostRenderFrame();
1121 }
1122
1123 void KX_KetsjiEngine::PostRenderFrame()
1124 {
1125         m_rendertools->PushMatrix();
1126         m_rendertools->Render2DFilters(m_canvas);
1127         m_rendertools->MotionBlur(m_rasterizer);
1128         m_rendertools->PopMatrix();
1129 }
1130
1131 void KX_KetsjiEngine::StopEngine()
1132 {
1133         if (m_bInitialized)
1134         {
1135
1136                 if (m_game2ipo)
1137                 {
1138 //                      printf("TestHandlesPhysicsObjectToAnimationIpo\n");
1139                         m_sceneconverter->TestHandlesPhysicsObjectToAnimationIpo();
1140                 }
1141
1142                 KX_SceneList::iterator sceneit;
1143                 for (sceneit = m_scenes.begin();sceneit != m_scenes.end() ; sceneit++)
1144                 {
1145                         KX_Scene* scene = *sceneit;
1146                         m_sceneconverter->RemoveScene(scene);
1147                 }       
1148                 m_scenes.clear();
1149
1150                 // cleanup all the stuff                
1151                 m_rasterizer->Exit();
1152         }
1153 }
1154
1155 // Scene Management is able to switch between scenes
1156 // and have several scene's running in parallel
1157 void KX_KetsjiEngine::AddScene(KX_Scene* scene)
1158
1159         m_scenes.push_back(scene);
1160         PostProcessScene(scene);
1161         SceneListsChanged();
1162 }
1163
1164
1165
1166 void KX_KetsjiEngine::PostProcessScene(KX_Scene* scene)
1167 {
1168         bool override_camera = (m_overrideCam && (scene->GetName() == m_overrideSceneName));
1169         
1170                 // if there is no activecamera, or the camera is being
1171                 // overridden we need to construct a temporarily camera
1172         if (!scene->GetActiveCamera() || override_camera)
1173         {
1174                 KX_Camera* activecam = NULL;
1175
1176                 RAS_CameraData camdata = RAS_CameraData();
1177                 activecam = new KX_Camera(scene,KX_Scene::m_callbacks,camdata, false);
1178                 activecam->SetName("__default__cam__");
1179         
1180                         // set transformation
1181                 if (override_camera) {
1182                         const MT_CmMatrix4x4& cammatdata = m_overrideCamViewMat;
1183                         MT_Transform trans = MT_Transform(cammatdata.getPointer());
1184                         MT_Transform camtrans;
1185                         camtrans.invert(trans);
1186                         
1187                         activecam->NodeSetLocalPosition(camtrans.getOrigin());
1188                         activecam->NodeSetLocalOrientation(camtrans.getBasis());
1189                         activecam->NodeUpdateGS(0,true);
1190                 } else {
1191                         activecam->NodeSetLocalPosition(MT_Point3(0.0, 0.0, 0.0));
1192                         activecam->NodeSetLocalOrientation(MT_Vector3(0.0, 0.0, 0.0));
1193                         activecam->NodeUpdateGS(0,true);
1194                 }
1195
1196                 scene->AddCamera(activecam);
1197                 scene->SetActiveCamera(activecam);
1198                 scene->GetObjectList()->Add(activecam->AddRef());
1199                 scene->GetRootParentList()->Add(activecam->AddRef());
1200                 //done with activecam
1201                 activecam->Release();
1202         }
1203         
1204         scene->UpdateParents(0.0);
1205 }
1206
1207
1208
1209 void KX_KetsjiEngine::RenderDebugProperties()
1210 {
1211         STR_String debugtxt;
1212         int xcoord = 10;        // mmmm, these constants were taken from blender source
1213         int ycoord = 14;        // to 'mimic' behaviour
1214
1215         float tottime = m_logger->GetAverage();
1216         if (tottime < 1e-6f) {
1217                 tottime = 1e-6f;
1218         }
1219
1220         // Set viewport to entire canvas
1221         RAS_Rect viewport;
1222         m_canvas->SetViewPort(0, 0, int(m_canvas->GetWidth()), int(m_canvas->GetHeight()));
1223         
1224         /* Framerate display */
1225         if (m_show_framerate) {
1226                 debugtxt.Format("swap : %.3f (%.3f frames per second)", tottime, 1.0/tottime);
1227                 m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED, 
1228                                                                         debugtxt.Ptr(),
1229                                                                         xcoord,
1230                                                                         ycoord, 
1231                                                                         m_canvas->GetWidth() /* RdV, TODO ?? */, 
1232                                                                         m_canvas->GetHeight() /* RdV, TODO ?? */);
1233                 ycoord += 14;
1234         }
1235
1236         /* Profile and framerate display */
1237         if (m_show_profile)
1238         {               
1239                 for (int j = tc_first; j < tc_numCategories; j++)
1240                 {
1241                         debugtxt.Format(m_profileLabels[j]);
1242                         m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED, 
1243                                                                                 debugtxt.Ptr(),
1244                                                                                 xcoord,ycoord,
1245                                                                                 m_canvas->GetWidth(), 
1246                                                                                 m_canvas->GetHeight());
1247                         double time = m_logger->GetAverage((KX_TimeCategory)j);
1248                         debugtxt.Format("%2.2f %%", time/tottime * 100.f);
1249                         m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED, 
1250                                                                                 debugtxt.Ptr(),
1251                                                                                 xcoord + 60 ,ycoord,
1252                                                                                 m_canvas->GetWidth(), 
1253                                                                                 m_canvas->GetHeight());
1254                         ycoord += 14;
1255                 }
1256         }
1257
1258         /* Property display*/
1259         if (m_show_debug_properties && m_propertiesPresent)
1260         {
1261                 KX_SceneList::iterator sceneit;
1262                 for (sceneit = m_scenes.begin();sceneit != m_scenes.end() ; sceneit++)
1263                 {
1264                         KX_Scene* scene = *sceneit;
1265                         /* the 'normal' debug props */
1266                         vector<SCA_DebugProp*>& debugproplist = scene->GetDebugProperties();
1267                         
1268                         for (vector<SCA_DebugProp*>::iterator it = debugproplist.begin();
1269                                  !(it==debugproplist.end());it++)
1270                         {
1271                                 CValue* propobj = (*it)->m_obj;
1272                                 STR_String objname = propobj->GetName();
1273                                 STR_String propname = (*it)->m_name;
1274                                 if (propname == "__state__")
1275                                 {
1276                                         // reserve name for object state
1277                                         KX_GameObject* gameobj = static_cast<KX_GameObject*>(propobj);
1278                                         unsigned int state = gameobj->GetState();
1279                                         debugtxt = objname + "." + propname + " = ";
1280                                         bool first = true;
1281                                         for (int statenum=1;state;state >>= 1, statenum++)
1282                                         {
1283                                                 if (state & 1)
1284                                                 {
1285                                                         if (!first)
1286                                                         {
1287                                                                 debugtxt += ",";
1288                                                         }
1289                                                         debugtxt += STR_String(statenum);
1290                                                         first = false;
1291                                                 }
1292                                         }
1293                                         m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED, 
1294                                                                                                         debugtxt.Ptr(),
1295                                                                                                         xcoord,
1296                                                                                                         ycoord,
1297                                                                                                         m_canvas->GetWidth(),
1298                                                                                                         m_canvas->GetHeight());
1299                                         ycoord += 14;
1300                                 }
1301                                 else
1302                                 {
1303                                         CValue* propval = propobj->GetProperty(propname);
1304                                         if (propval)
1305                                         {
1306                                                 STR_String text = propval->GetText();
1307                                                 debugtxt = objname + "." + propname + " = " + text;
1308                                                 m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED, 
1309                                                                                                         debugtxt.Ptr(),
1310                                                                                                         xcoord,
1311                                                                                                         ycoord,
1312                                                                                                         m_canvas->GetWidth(),
1313                                                                                                         m_canvas->GetHeight());
1314                                                 ycoord += 14;
1315                                         }
1316                                 }
1317                         }
1318                 }
1319         }
1320 }
1321
1322
1323 KX_SceneList* KX_KetsjiEngine::CurrentScenes()
1324 {
1325         return &m_scenes;       
1326 }
1327
1328
1329
1330 KX_Scene* KX_KetsjiEngine::FindScene(const STR_String& scenename)
1331 {
1332         KX_SceneList::iterator sceneit = m_scenes.begin();
1333
1334         // bit risky :) better to split the second clause 
1335         while ( (sceneit != m_scenes.end()) 
1336                         && ((*sceneit)->GetName() != scenename))
1337         {
1338                 sceneit++;
1339         }
1340
1341         return ((sceneit == m_scenes.end()) ? NULL : *sceneit); 
1342 }
1343
1344
1345
1346 void KX_KetsjiEngine::ConvertAndAddScene(const STR_String& scenename,bool overlay)
1347 {
1348         // only add scene when it doesn't exist!
1349         if (FindScene(scenename))
1350         {
1351                 STR_String tmpname = scenename;
1352                 printf("warning: scene %s already exists, not added!\n",tmpname.Ptr());
1353         }
1354         else
1355         {
1356                 if (overlay)
1357                 {
1358                         m_addingOverlayScenes.insert(scenename);
1359                 }
1360                 else
1361                 {
1362                         m_addingBackgroundScenes.insert(scenename);
1363                 }
1364         }
1365 }
1366
1367
1368
1369
1370 void KX_KetsjiEngine::RemoveScene(const STR_String& scenename)
1371 {
1372         if (FindScene(scenename))
1373         {
1374                 m_removingScenes.insert(scenename);
1375         }
1376         else
1377         {
1378 //              STR_String tmpname = scenename;
1379                 std::cout << "warning: scene " << scenename << " does not exist, not removed!" << std::endl;
1380         }
1381 }
1382
1383
1384
1385 void KX_KetsjiEngine::RemoveScheduledScenes()
1386 {
1387         if (m_removingScenes.size())
1388         {
1389                 set<STR_String>::iterator scenenameit;
1390                 for (scenenameit=m_removingScenes.begin();scenenameit != m_removingScenes.end();scenenameit++)
1391                 {
1392                         STR_String scenename = *scenenameit;
1393
1394                         KX_SceneList::iterator sceneit;
1395                         for (sceneit = m_scenes.begin();sceneit != m_scenes.end() ; sceneit++)
1396                         {
1397                                 KX_Scene* scene = *sceneit;
1398                                 if (scene->GetName()==scenename)
1399                                 {
1400                                         m_sceneconverter->RemoveScene(scene);
1401                                         m_scenes.erase(sceneit);
1402                                         break;
1403                                 }
1404                         }       
1405                 }
1406                 m_removingScenes.clear();
1407         }
1408 }
1409
1410
1411
1412 KX_Scene* KX_KetsjiEngine::CreateScene(const STR_String& scenename)
1413 {
1414         Scene *scene = m_sceneconverter->GetBlenderSceneForName(scenename);
1415         KX_Scene* tmpscene = new KX_Scene(m_keyboarddevice,
1416                                                                           m_mousedevice,
1417                                                                           m_networkdevice,
1418                                                                           m_audiodevice,
1419                                                                           scenename,
1420                                                                           scene);
1421
1422         m_sceneconverter->ConvertScene(scenename,
1423                                                           tmpscene,
1424                                                           m_pythondictionary,
1425                                                           m_keyboarddevice,
1426                                                           m_rendertools,
1427                                                           m_canvas);
1428
1429         return tmpscene;
1430 }
1431
1432
1433
1434 void KX_KetsjiEngine::AddScheduledScenes()
1435 {
1436         set<STR_String>::iterator scenenameit;
1437
1438         if (m_addingOverlayScenes.size())
1439         {
1440                 for (scenenameit = m_addingOverlayScenes.begin();
1441                         scenenameit != m_addingOverlayScenes.end();
1442                         scenenameit++)
1443                 {
1444                         STR_String scenename = *scenenameit;
1445                         KX_Scene* tmpscene = CreateScene(scenename);
1446                         m_scenes.push_back(tmpscene);
1447                         PostProcessScene(tmpscene);
1448                 }
1449                 m_addingOverlayScenes.clear();
1450         }
1451         
1452         if (m_addingBackgroundScenes.size())
1453         {
1454                 for (scenenameit = m_addingBackgroundScenes.begin();
1455                         scenenameit != m_addingBackgroundScenes.end();
1456                         scenenameit++)
1457                 {
1458                         STR_String scenename = *scenenameit;
1459                         KX_Scene* tmpscene = CreateScene(scenename);
1460                         m_scenes.insert(m_scenes.begin(),tmpscene);
1461                         PostProcessScene(tmpscene);
1462
1463                 }
1464                 m_addingBackgroundScenes.clear();
1465         }
1466 }
1467
1468
1469
1470 void KX_KetsjiEngine::ReplaceScene(const STR_String& oldscene,const STR_String& newscene)
1471 {
1472         m_replace_scenes.insert(std::make_pair(oldscene,newscene));
1473 }
1474
1475 // replace scene is not the same as removing and adding because the
1476 // scene must be in exact the same place (to maintain drawingorder)
1477 // (nzc) - should that not be done with a scene-display list? It seems
1478 // stupid to rely on the mem allocation order...
1479 void KX_KetsjiEngine::ReplaceScheduledScenes()
1480 {
1481         if (m_replace_scenes.size())
1482         {
1483                 set<pair<STR_String,STR_String> >::iterator scenenameit;
1484                 
1485                 for (scenenameit = m_replace_scenes.begin();
1486                         scenenameit != m_replace_scenes.end();
1487                         scenenameit++)
1488                 {
1489                         STR_String oldscenename = (*scenenameit).first;
1490                         STR_String newscenename = (*scenenameit).second;
1491                         int i=0;
1492                         /* Scenes are not supposed to be included twice... I think */
1493                         KX_SceneList::iterator sceneit;
1494                         for (sceneit = m_scenes.begin();sceneit != m_scenes.end() ; sceneit++)
1495                         {
1496                                 KX_Scene* scene = *sceneit;
1497                                 if (scene->GetName() == oldscenename)
1498                                 {
1499                                         m_sceneconverter->RemoveScene(scene);
1500                                         KX_Scene* tmpscene = CreateScene(newscenename);
1501                                         m_scenes[i]=tmpscene;
1502                                         PostProcessScene(tmpscene);
1503                                 }
1504                                 i++;
1505                         }
1506                 }
1507                 m_replace_scenes.clear();
1508         }       
1509 }
1510
1511
1512
1513 void KX_KetsjiEngine::SuspendScene(const STR_String& scenename)
1514 {
1515         KX_Scene*  scene = FindScene(scenename);
1516         if (scene) scene->Suspend();
1517 }
1518
1519
1520
1521 void KX_KetsjiEngine::ResumeScene(const STR_String& scenename)
1522 {
1523         KX_Scene*  scene = FindScene(scenename);
1524         if (scene) scene->Resume();
1525 }
1526
1527
1528
1529 void KX_KetsjiEngine::SetUseFixedTime(bool bUseFixedTime)
1530 {
1531         m_bFixedTime = bUseFixedTime;
1532 }
1533
1534
1535 void    KX_KetsjiEngine::SetGame2IpoMode(bool game2ipo,int startFrame)
1536 {
1537         m_game2ipo = game2ipo;
1538         if (game2ipo)
1539         {
1540                 //when recording physics keyframes, always run at a fixed framerate
1541                 m_bFixedTime = true;
1542         }
1543         m_currentFrame = startFrame;
1544 }
1545
1546 bool KX_KetsjiEngine::GetUseFixedTime(void) const
1547 {
1548         return m_bFixedTime;
1549 }
1550
1551 double KX_KetsjiEngine::GetSuspendedDelta()
1552 {
1553         return m_suspendeddelta;
1554 }
1555
1556 double KX_KetsjiEngine::GetTicRate()
1557 {
1558         return m_ticrate;
1559 }
1560
1561 void KX_KetsjiEngine::SetTicRate(double ticrate)
1562 {
1563         m_ticrate = ticrate;
1564 }
1565
1566 double KX_KetsjiEngine::GetAnimFrameRate()
1567 {
1568         return m_anim_framerate;
1569 }
1570
1571 double KX_KetsjiEngine::GetClockTime(void) const
1572 {
1573         return m_clockTime;
1574 }
1575
1576 void KX_KetsjiEngine::SetAnimFrameRate(double framerate)
1577 {
1578         m_anim_framerate = framerate;
1579 }
1580
1581 double KX_KetsjiEngine::GetAverageFrameRate()
1582 {
1583         return m_average_framerate;
1584 }
1585
1586 void KX_KetsjiEngine::SetTimingDisplay(bool frameRate, bool profile, bool properties)
1587 {
1588         m_show_framerate = frameRate;
1589         m_show_profile = profile;
1590         m_show_debug_properties = properties;
1591 }
1592
1593
1594
1595 void KX_KetsjiEngine::GetTimingDisplay(bool& frameRate, bool& profile, bool& properties) const
1596 {
1597         frameRate = m_show_framerate;
1598         profile = m_show_profile;
1599         properties = m_show_debug_properties;
1600 }
1601
1602
1603
1604 void KX_KetsjiEngine::ProcessScheduledScenes(void)
1605 {
1606         // Check whether there will be changes to the list of scenes
1607         if (m_addingOverlayScenes.size() ||
1608                 m_addingBackgroundScenes.size() ||
1609                 m_replace_scenes.size() ||
1610                 m_removingScenes.size()) {
1611
1612                 // Change the scene list
1613                 ReplaceScheduledScenes();
1614                 RemoveScheduledScenes();
1615                 AddScheduledScenes();
1616
1617                 // Notify
1618                 SceneListsChanged();
1619         }
1620 }
1621
1622
1623
1624 void KX_KetsjiEngine::SceneListsChanged(void)
1625 {
1626         m_propertiesPresent = false;
1627         KX_SceneList::iterator sceneit = m_scenes.begin();
1628         while ((sceneit != m_scenes.end()) && (!m_propertiesPresent))
1629         {
1630                 KX_Scene* scene = *sceneit;
1631                 vector<SCA_DebugProp*>& debugproplist = scene->GetDebugProperties();    
1632                 m_propertiesPresent = !debugproplist.empty();
1633                 sceneit++;
1634         }
1635 }
1636
1637
1638 void KX_KetsjiEngine::SetHideCursor(bool hideCursor)
1639 {
1640         m_hideCursor = hideCursor;
1641 }
1642
1643
1644 bool KX_KetsjiEngine::GetHideCursor(void) const
1645 {
1646         return m_hideCursor;
1647 }
1648
1649
1650 void KX_KetsjiEngine::SetUseOverrideFrameColor(bool overrideFrameColor)
1651 {
1652         m_overrideFrameColor = overrideFrameColor;
1653 }
1654
1655
1656 bool KX_KetsjiEngine::GetUseOverrideFrameColor(void) const
1657 {
1658         return m_overrideFrameColor;
1659 }
1660
1661
1662 void KX_KetsjiEngine::SetOverrideFrameColor(float r, float g, float b)
1663 {
1664         m_overrideFrameColorR = r;
1665         m_overrideFrameColorG = g;
1666         m_overrideFrameColorB = b;
1667 }
1668
1669
1670 void KX_KetsjiEngine::GetOverrideFrameColor(float& r, float& g, float& b) const
1671 {
1672         r = m_overrideFrameColorR;
1673         g = m_overrideFrameColorG;
1674         b = m_overrideFrameColorB;
1675 }
1676
1677
1678