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