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