421e642a6df6255f7de62e66bc9759e28ed4402a
[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         "Sound:",               // tc_sound
100         "Rasterizer:",  // tc_rasterizer
101         "Services:",    // tc_services
102         "Overhead:",    // tc_overhead
103         "Outside:"              // tc_outside
104 };
105
106 double KX_KetsjiEngine::m_ticrate = DEFAULT_LOGIC_TIC_RATE;
107 int        KX_KetsjiEngine::m_maxLogicFrame = 5;
108 int        KX_KetsjiEngine::m_maxPhysicsFrame = 5;
109 double KX_KetsjiEngine::m_anim_framerate = 25.0;
110 double KX_KetsjiEngine::m_suspendedtime = 0.0;
111 double KX_KetsjiEngine::m_suspendeddelta = 0.0;
112 double KX_KetsjiEngine::m_average_framerate = 0.0;
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                                 // Handle animations
660                                 double anim_timestep = 1.0/scene->GetAnimationFPS();
661                                 if (m_clockTime - m_previousAnimTime > anim_timestep)
662                                 {
663                                         m_previousAnimTime = m_clockTime;
664                                         m_logger->StartLog(tc_animations, m_kxsystem->GetTimeInSeconds(), true);
665                                         SG_SetActiveStage(SG_STAGE_ANIMATION_UPDATE);
666                                         scene->UpdateAnimations(m_frameTime);
667                                 }
668         
669                                 // Actuators can affect the scenegraph
670                                 m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
671                                 SG_SetActiveStage(SG_STAGE_ACTUATOR_UPDATE);
672                                 scene->UpdateParents(m_frameTime);
673                                 
674                                 m_logger->StartLog(tc_physics, m_kxsystem->GetTimeInSeconds(), true);
675                                 SG_SetActiveStage(SG_STAGE_PHYSICS2);
676                                 scene->GetPhysicsEnvironment()->beginFrame();
677                 
678                                 // Perform physics calculations on the scene. This can involve 
679                                 // many iterations of the physics solver.
680                                 scene->GetPhysicsEnvironment()->proceedDeltaTime(m_frameTime,timestep,framestep);//m_deltatimerealDeltaTime);
681
682                                 m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
683                                 SG_SetActiveStage(SG_STAGE_PHYSICS2_UPDATE);
684                                 scene->UpdateParents(m_frameTime);
685                         
686                         
687                                 if (m_animation_record)
688                                 {                                       
689                                         m_sceneconverter->WritePhysicsObjectToAnimationIpo(++m_currentFrame);
690                                 }
691
692                                 scene->setSuspendedTime(0.0);
693                         } // suspended
694                         else
695                                 if(scene->getSuspendedTime()==0.0)
696                                         scene->setSuspendedTime(m_clockTime);
697         
698                         DoSound(scene);
699                         
700                         m_logger->StartLog(tc_services, m_kxsystem->GetTimeInSeconds(), true);
701                 }
702
703                 // update system devices
704                 m_logger->StartLog(tc_logic, m_kxsystem->GetTimeInSeconds(), true);
705                 if (m_keyboarddevice)
706                         m_keyboarddevice->NextFrame();
707         
708                 if (m_mousedevice)
709                         m_mousedevice->NextFrame();
710                 
711                 if (m_networkdevice)
712                         m_networkdevice->NextFrame();
713
714                 // scene management
715                 ProcessScheduledScenes();
716                 
717                 frames--;
718         }
719
720         bool bUseAsyncLogicBricks= false;//true;
721
722         if (bUseAsyncLogicBricks)
723         {       
724                 // Logic update sub frame: this will let some logic bricks run at the
725                 // full frame rate.
726                 for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); ++sceneit)
727                 // for each scene, call the proceed functions
728                 {
729                         KX_Scene* scene = *sceneit;
730
731                         if (!scene->IsSuspended())
732                         {
733                                 // if the scene was suspended recalcutlate the delta tu "curtime"
734                                 m_suspendedtime = scene->getSuspendedTime();
735                                 if (scene->getSuspendedTime()!=0.0)
736                                         scene->setSuspendedDelta(scene->getSuspendedDelta()+m_clockTime-scene->getSuspendedTime());
737                                 m_suspendeddelta = scene->getSuspendedDelta();
738                                 
739                                 // set Python hooks for each scene
740 #ifdef WITH_PYTHON
741                                 PHY_SetActiveEnvironment(scene->GetPhysicsEnvironment());
742 #endif
743                                 KX_SetActiveScene(scene);
744                                 
745                                 m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
746                                 SG_SetActiveStage(SG_STAGE_PHYSICS1);
747                                 scene->UpdateParents(m_clockTime);
748
749                                 // Perform physics calculations on the scene. This can involve 
750                                 // many iterations of the physics solver.
751                                 m_logger->StartLog(tc_physics, m_kxsystem->GetTimeInSeconds(), true);
752                                 scene->GetPhysicsEnvironment()->proceedDeltaTime(m_clockTime,timestep,timestep);
753                                 // Update scenegraph after physics step. This maps physics calculations
754                                 // into node positions.         
755                                 m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
756                                 SG_SetActiveStage(SG_STAGE_PHYSICS2);
757                                 scene->UpdateParents(m_clockTime);
758                                 
759                                 // Do some cleanup work for this logic frame
760                                 m_logger->StartLog(tc_logic, m_kxsystem->GetTimeInSeconds(), true);
761                                 scene->LogicUpdateFrame(m_clockTime, false);
762
763                                 // Actuators can affect the scenegraph
764                                 m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
765                                 SG_SetActiveStage(SG_STAGE_ACTUATOR);
766                                 scene->UpdateParents(m_clockTime);
767                                  
768                                 scene->setSuspendedTime(0.0);
769                         } // suspended
770                         else
771                                 if(scene->getSuspendedTime()==0.0)
772                                         scene->setSuspendedTime(m_clockTime);
773
774                         DoSound(scene);
775
776                         m_logger->StartLog(tc_services, m_kxsystem->GetTimeInSeconds(), true);
777                 }
778         }
779
780
781         m_previousClockTime = m_clockTime;
782         
783         // Start logging time spend outside main loop
784         m_logger->StartLog(tc_outside, m_kxsystem->GetTimeInSeconds(), true);
785         
786         return doRender;
787 }
788
789
790
791 void KX_KetsjiEngine::Render()
792 {
793         if(m_usedome){
794                 RenderDome();
795                 return;
796         }
797         KX_Scene* firstscene = *m_scenes.begin();
798         const RAS_FrameSettings &framesettings = firstscene->GetFramingType();
799
800         m_logger->StartLog(tc_rasterizer, m_kxsystem->GetTimeInSeconds(), true);
801         SG_SetActiveStage(SG_STAGE_RENDER);
802
803         // hiding mouse cursor each frame
804         // (came back when going out of focus and then back in again)
805         if (m_hideCursor)
806                 m_canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);
807
808         // clear the entire game screen with the border color
809         // only once per frame
810         m_canvas->BeginDraw();
811         if (m_drawingmode == RAS_IRasterizer::KX_TEXTURED) {
812                 m_canvas->SetViewPort(0, 0, m_canvas->GetWidth(), m_canvas->GetHeight());
813                 if (m_overrideFrameColor)
814                 {
815                         // Do not use the framing bar color set in the Blender scenes
816                         m_canvas->ClearColor(
817                                 m_overrideFrameColorR,
818                                 m_overrideFrameColorG,
819                                 m_overrideFrameColorB,
820                                 1.0
821                                 );
822                 }
823                 else
824                 {
825                         // Use the framing bar color set in the Blender scenes
826                         m_canvas->ClearColor(
827                                 framesettings.BarRed(),
828                                 framesettings.BarGreen(),
829                                 framesettings.BarBlue(),
830                                 1.0
831                                 );
832                 }
833                 // clear the -whole- viewport
834                 m_canvas->ClearBuffer(RAS_ICanvas::COLOR_BUFFER|RAS_ICanvas::DEPTH_BUFFER);
835         }
836
837         m_rasterizer->SetEye(RAS_IRasterizer::RAS_STEREO_LEFTEYE);
838
839         // BeginFrame() sets the actual drawing area. You can use a part of the window
840         if (!BeginFrame())
841                 return;
842
843         KX_SceneList::iterator sceneit;
844         for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); sceneit++)
845         // for each scene, call the proceed functions
846         {
847                 KX_Scene* scene = *sceneit;
848                 KX_Camera* cam = scene->GetActiveCamera();
849                 // pass the scene's worldsettings to the rasterizer
850                 SetWorldSettings(scene->GetWorldInfo());
851
852                 // this is now done incrementatlly in KX_Scene::CalculateVisibleMeshes
853                 //scene->UpdateMeshTransformations();
854
855                 // shadow buffers
856                 RenderShadowBuffers(scene);
857
858                 // Avoid drawing the scene with the active camera twice when it's viewport is enabled
859                 if(cam && !cam->GetViewport())
860                 {
861                         if (scene->IsClearingZBuffer())
862                                 m_rasterizer->ClearDepthBuffer();
863         
864                         m_rendertools->SetAuxilaryClientInfo(scene);
865         
866                         // do the rendering
867                         RenderFrame(scene, cam);
868                 }
869                 
870                 list<class KX_Camera*>* cameras = scene->GetCameras();
871                 
872                 // Draw the scene once for each camera with an enabled viewport
873                 list<KX_Camera*>::iterator it = cameras->begin();
874                 while(it != cameras->end())
875                 {
876                         if((*it)->GetViewport())
877                         {
878                                 if (scene->IsClearingZBuffer())
879                                         m_rasterizer->ClearDepthBuffer();
880                 
881                                 m_rendertools->SetAuxilaryClientInfo(scene);
882                 
883                                 // do the rendering
884                                 RenderFrame(scene, (*it));
885                         }
886                         
887                         it++;
888                 }
889                 PostRenderScene(scene);
890         }
891
892         // only one place that checks for stereo
893         if(m_rasterizer->Stereo())
894         {
895                 m_rasterizer->SetEye(RAS_IRasterizer::RAS_STEREO_RIGHTEYE);
896
897                 if (!BeginFrame())
898                         return;
899
900
901                 for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); sceneit++)
902                 // for each scene, call the proceed functions
903                 {
904                         KX_Scene* scene = *sceneit;
905                         KX_Camera* cam = scene->GetActiveCamera();
906
907                         // pass the scene's worldsettings to the rasterizer
908                         SetWorldSettings(scene->GetWorldInfo());
909                 
910                         if (scene->IsClearingZBuffer())
911                                 m_rasterizer->ClearDepthBuffer();
912
913                         //pass the scene, for picking and raycasting (shadows)
914                         m_rendertools->SetAuxilaryClientInfo(scene);
915
916                         // do the rendering
917                         //RenderFrame(scene);
918                         RenderFrame(scene, cam);
919
920                         list<class KX_Camera*>* cameras = scene->GetCameras();                  
921         
922                         // Draw the scene once for each camera with an enabled viewport
923                         list<KX_Camera*>::iterator it = cameras->begin();
924                         while(it != cameras->end())
925                         {
926                                 if((*it)->GetViewport())
927                                 {
928                                         if (scene->IsClearingZBuffer())
929                                                 m_rasterizer->ClearDepthBuffer();
930                         
931                                         m_rendertools->SetAuxilaryClientInfo(scene);
932                         
933                                         // do the rendering
934                                         RenderFrame(scene, (*it));
935                                 }
936                                 
937                                 it++;
938                         }
939                         PostRenderScene(scene);
940                 }
941         } // if(m_rasterizer->Stereo())
942
943         EndFrame();
944 }
945
946
947
948 void KX_KetsjiEngine::RequestExit(int exitrequestmode)
949 {
950         m_exitcode = exitrequestmode;
951 }
952
953
954
955 void KX_KetsjiEngine::SetNameNextGame(const STR_String& nextgame)
956 {
957         m_exitstring = nextgame;
958 }
959
960
961
962 int KX_KetsjiEngine::GetExitCode()
963 {
964         // if a gameactuator has set an exitcode or if there are no scenes left
965         if (!m_exitcode)
966         {
967                 if (m_scenes.begin()==m_scenes.end())
968                         m_exitcode = KX_EXIT_REQUEST_NO_SCENES_LEFT;
969         }
970         
971         // check if the window has been closed.
972         if(!m_exitcode)
973         {
974                 //if(!m_canvas->Check()) {
975                 //      m_exitcode = KX_EXIT_REQUEST_OUTSIDE;
976                 //}
977         }
978
979         return m_exitcode;
980 }
981
982
983
984 const STR_String& KX_KetsjiEngine::GetExitString()
985 {
986         return m_exitstring;
987 }
988
989
990
991 void KX_KetsjiEngine::DoSound(KX_Scene* scene)
992 {
993         m_logger->StartLog(tc_sound, m_kxsystem->GetTimeInSeconds(), true);
994
995         KX_Camera* cam = scene->GetActiveCamera();
996         if (!cam)
997                 return;
998
999         AUD_I3DDevice* dev = AUD_get3DDevice();
1000         if(dev)
1001         {
1002                 AUD_Vector3 v;
1003                 AUD_Quaternion q;
1004                 cam->NodeGetWorldPosition().getValue(v.get());
1005                 dev->setListenerLocation(v);
1006
1007                 cam->GetLinearVelocity().getValue(v.get());
1008                 dev->setListenerVelocity(v);
1009
1010                 cam->NodeGetWorldOrientation().getRotation().getValue(q.get());
1011                 dev->setListenerOrientation(q);
1012         }
1013 }
1014
1015
1016
1017 void KX_KetsjiEngine::SetBackGround(KX_WorldInfo* wi)
1018 {
1019         if (wi->hasWorld())
1020         {
1021                 if (m_drawingmode == RAS_IRasterizer::KX_TEXTURED)
1022                 {       
1023                         m_rasterizer->SetBackColor(
1024                                 wi->getBackColorRed(),
1025                                 wi->getBackColorGreen(),
1026                                 wi->getBackColorBlue(),
1027                                 0.0
1028                         );
1029                 }
1030         }
1031 }
1032
1033
1034
1035 void KX_KetsjiEngine::SetWorldSettings(KX_WorldInfo* wi)
1036 {
1037         if (wi->hasWorld())
1038         {
1039                 // ...
1040                 m_rasterizer->SetAmbientColor(
1041                         wi->getAmbientColorRed(),
1042                         wi->getAmbientColorGreen(),
1043                         wi->getAmbientColorBlue()
1044                 );
1045
1046                 if (m_drawingmode >= RAS_IRasterizer::KX_SOLID)
1047                 {       
1048                         if (wi->hasMist())
1049                         {
1050                                 m_rasterizer->SetFog(
1051                                         wi->getMistStart(),
1052                                         wi->getMistDistance(),
1053                                         wi->getMistColorRed(),
1054                                         wi->getMistColorGreen(),
1055                                         wi->getMistColorBlue()
1056                                 );
1057                         }
1058                 }
1059         }
1060 }
1061
1062
1063
1064 void KX_KetsjiEngine::SetDrawType(int drawingmode)
1065 {
1066         m_drawingmode = drawingmode;
1067 }
1068
1069
1070         
1071 void KX_KetsjiEngine::EnableCameraOverride(const STR_String& forscene)
1072 {
1073         m_overrideCam = true;
1074         m_overrideSceneName = forscene;
1075 }
1076
1077
1078
1079 void KX_KetsjiEngine::SetCameraZoom(float camzoom)
1080 {
1081         m_cameraZoom = camzoom;
1082 }
1083
1084
1085
1086 void KX_KetsjiEngine::SetCameraOverrideUseOrtho(bool useOrtho)
1087 {
1088         m_overrideCamUseOrtho = useOrtho;
1089 }
1090
1091
1092
1093 void KX_KetsjiEngine::SetCameraOverrideProjectionMatrix(const MT_CmMatrix4x4& mat)
1094 {
1095         m_overrideCamProjMat = mat;
1096 }
1097
1098
1099 void KX_KetsjiEngine::SetCameraOverrideViewMatrix(const MT_CmMatrix4x4& mat)
1100 {
1101         m_overrideCamViewMat = mat;
1102 }
1103
1104 void KX_KetsjiEngine::SetCameraOverrideClipping(float near, float far)
1105 {
1106         m_overrideCamNear = near;
1107         m_overrideCamFar = far;
1108 }
1109
1110 void KX_KetsjiEngine::SetCameraOverrideLens(float lens)
1111 {
1112         m_overrideCamLens = lens;
1113 }
1114
1115 void KX_KetsjiEngine::GetSceneViewport(KX_Scene *scene, KX_Camera* cam, RAS_Rect& area, RAS_Rect& viewport)
1116 {
1117         // In this function we make sure the rasterizer settings are upto
1118         // date. We compute the viewport so that logic
1119         // using this information is upto date.
1120
1121         // Note we postpone computation of the projection matrix
1122         // so that we are using the latest camera position.
1123         if (cam->GetViewport()) {
1124                 RAS_Rect userviewport;
1125
1126                 userviewport.SetLeft(cam->GetViewportLeft()); 
1127                 userviewport.SetBottom(cam->GetViewportBottom());
1128                 userviewport.SetRight(cam->GetViewportRight());
1129                 userviewport.SetTop(cam->GetViewportTop());
1130
1131                 // Don't do bars on user specified viewport
1132                 RAS_FrameSettings settings = scene->GetFramingType();
1133                 if(settings.FrameType() == RAS_FrameSettings::e_frame_bars)
1134                         settings.SetFrameType(RAS_FrameSettings::e_frame_extend);
1135
1136                 RAS_FramingManager::ComputeViewport(
1137                         scene->GetFramingType(),
1138                         userviewport,
1139                         viewport
1140                 );
1141
1142                 area = userviewport;
1143         }
1144         else if ( !m_overrideCam || (scene->GetName() != m_overrideSceneName) ||  m_overrideCamUseOrtho ) {
1145                 RAS_FramingManager::ComputeViewport(
1146                         scene->GetFramingType(),
1147                         m_canvas->GetDisplayArea(),
1148                         viewport
1149                 );
1150
1151                 area = m_canvas->GetDisplayArea();
1152         } else {
1153                 viewport.SetLeft(0); 
1154                 viewport.SetBottom(0);
1155                 viewport.SetRight(int(m_canvas->GetWidth()));
1156                 viewport.SetTop(int(m_canvas->GetHeight()));
1157
1158                 area = m_canvas->GetDisplayArea();
1159         }
1160 }
1161
1162 void KX_KetsjiEngine::RenderShadowBuffers(KX_Scene *scene)
1163 {
1164         CListValue *lightlist = scene->GetLightList();
1165         int i, drawmode;
1166
1167         m_rendertools->SetAuxilaryClientInfo(scene);
1168
1169         for(i=0; i<lightlist->GetCount(); i++) {
1170                 KX_GameObject *gameobj = (KX_GameObject*)lightlist->GetValue(i);
1171
1172                 KX_LightObject *light = (KX_LightObject*)gameobj;
1173
1174                 light->Update();
1175
1176                 if(m_drawingmode == RAS_IRasterizer::KX_TEXTURED && light->HasShadowBuffer()) {
1177                         /* make temporary camera */
1178                         RAS_CameraData camdata = RAS_CameraData();
1179                         KX_Camera *cam = new KX_Camera(scene, scene->m_callbacks, camdata, true, true);
1180                         cam->SetName("__shadow__cam__");
1181
1182                         MT_Transform camtrans;
1183
1184                         /* switch drawmode for speed */
1185                         drawmode = m_rasterizer->GetDrawingMode();
1186                         m_rasterizer->SetDrawingMode(RAS_IRasterizer::KX_SHADOW);
1187
1188                         /* binds framebuffer object, sets up camera .. */
1189                         light->BindShadowBuffer(m_rasterizer, cam, camtrans);
1190
1191                         /* update scene */
1192                         scene->CalculateVisibleMeshes(m_rasterizer, cam, light->GetShadowLayer());
1193
1194                         /* render */
1195                         m_rasterizer->ClearDepthBuffer();
1196                         scene->RenderBuckets(camtrans, m_rasterizer, m_rendertools);
1197
1198                         /* unbind framebuffer object, restore drawmode, free camera */
1199                         light->UnbindShadowBuffer(m_rasterizer);
1200                         m_rasterizer->SetDrawingMode(drawmode);
1201                         cam->Release();
1202                 }
1203         }
1204 }
1205         
1206 // update graphics
1207 void KX_KetsjiEngine::RenderFrame(KX_Scene* scene, KX_Camera* cam)
1208 {
1209         bool override_camera;
1210         RAS_Rect viewport, area;
1211         float nearfrust, farfrust, focallength;
1212 //      KX_Camera* cam = scene->GetActiveCamera();
1213         
1214         if (!cam)
1215                 return;
1216         GetSceneViewport(scene, cam, area, viewport);
1217
1218         // store the computed viewport in the scene
1219         scene->SetSceneViewport(viewport);      
1220
1221         // set the viewport for this frame and scene
1222         m_canvas->SetViewPort(viewport.GetLeft(), viewport.GetBottom(),
1223                 viewport.GetRight(), viewport.GetTop());        
1224         
1225         // see KX_BlenderMaterial::Activate
1226         //m_rasterizer->SetAmbient();
1227         m_rasterizer->DisplayFog();
1228
1229         override_camera = m_overrideCam && (scene->GetName() == m_overrideSceneName);
1230         override_camera = override_camera && (cam->GetName() == "__default__cam__");
1231
1232         if (override_camera && m_overrideCamUseOrtho) {
1233                 m_rasterizer->SetProjectionMatrix(m_overrideCamProjMat);
1234                 if (!cam->hasValidProjectionMatrix()) {
1235                         // needed to get frustrum planes for culling
1236                         MT_Matrix4x4 projmat;
1237                         projmat.setValue(m_overrideCamProjMat.getPointer());
1238                         cam->SetProjectionMatrix(projmat);
1239                 }
1240         } else if (cam->hasValidProjectionMatrix())
1241         {
1242                 m_rasterizer->SetProjectionMatrix(cam->GetProjectionMatrix());
1243         } else
1244         {
1245                 RAS_FrameFrustum frustum;
1246                 bool orthographic = !cam->GetCameraData()->m_perspective;
1247                 nearfrust = cam->GetCameraNear();
1248                 farfrust = cam->GetCameraFar();
1249                 focallength = cam->GetFocalLength();
1250                 MT_Matrix4x4 projmat;
1251
1252                 if(override_camera) {
1253                         nearfrust = m_overrideCamNear;
1254                         farfrust = m_overrideCamFar;
1255                 }
1256
1257                 if (orthographic) {
1258
1259                         RAS_FramingManager::ComputeOrtho(
1260                                 scene->GetFramingType(),
1261                                 area,
1262                                 viewport,
1263                                 cam->GetScale(),
1264                                 nearfrust,
1265                                 farfrust,
1266                                 frustum
1267                         );
1268                         if (!cam->GetViewport()) {
1269                                 frustum.x1 *= m_cameraZoom;
1270                                 frustum.x2 *= m_cameraZoom;
1271                                 frustum.y1 *= m_cameraZoom;
1272                                 frustum.y2 *= m_cameraZoom;
1273                         }
1274                         projmat = m_rasterizer->GetOrthoMatrix(
1275                                 frustum.x1, frustum.x2, frustum.y1, frustum.y2, frustum.camnear, frustum.camfar);
1276
1277                 } else {
1278                         RAS_FramingManager::ComputeFrustum(
1279                                 scene->GetFramingType(),
1280                                 area,
1281                                 viewport,
1282                                 cam->GetLens(),
1283                                 nearfrust,
1284                                 farfrust,
1285                                 frustum
1286                         );
1287
1288                         if (!cam->GetViewport()) {
1289                                 frustum.x1 *= m_cameraZoom;
1290                                 frustum.x2 *= m_cameraZoom;
1291                                 frustum.y1 *= m_cameraZoom;
1292                                 frustum.y2 *= m_cameraZoom;
1293                         }
1294                         projmat = m_rasterizer->GetFrustumMatrix(
1295                                 frustum.x1, frustum.x2, frustum.y1, frustum.y2, frustum.camnear, frustum.camfar, focallength);
1296                 }
1297                 cam->SetProjectionMatrix(projmat);
1298                 
1299                 // Otherwise the projection matrix for each eye will be the same...
1300                 if (!orthographic && m_rasterizer->Stereo())
1301                         cam->InvalidateProjectionMatrix();
1302         }
1303
1304         MT_Transform camtrans(cam->GetWorldToCamera());
1305         MT_Matrix4x4 viewmat(camtrans);
1306         
1307         m_rasterizer->SetViewMatrix(viewmat, cam->NodeGetWorldOrientation(), cam->NodeGetWorldPosition(), cam->GetCameraData()->m_perspective);
1308         cam->SetModelviewMatrix(viewmat);
1309
1310         // The following actually reschedules all vertices to be
1311         // redrawn. There is a cache between the actual rescheduling
1312         // and this call though. Visibility is imparted when this call
1313         // runs through the individual objects.
1314
1315         m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
1316         SG_SetActiveStage(SG_STAGE_CULLING);
1317
1318         scene->CalculateVisibleMeshes(m_rasterizer,cam);
1319
1320         m_logger->StartLog(tc_rasterizer, m_kxsystem->GetTimeInSeconds(), true);
1321         SG_SetActiveStage(SG_STAGE_RENDER);
1322
1323 #ifdef WITH_PYTHON
1324         // Run any pre-drawing python callbacks
1325         scene->RunDrawingCallbacks(scene->GetPreDrawCB());
1326 #endif
1327
1328         scene->RenderBuckets(camtrans, m_rasterizer, m_rendertools);
1329
1330         //render all the font objects for this scene
1331         RenderFonts(scene);
1332         
1333         if (scene->GetPhysicsEnvironment())
1334                 scene->GetPhysicsEnvironment()->debugDrawWorld();
1335 }
1336
1337 void KX_KetsjiEngine::RenderFonts(KX_Scene* scene)
1338 {
1339         list<class KX_FontObject*>* fonts = scene->GetFonts();
1340         
1341         list<KX_FontObject*>::iterator it = fonts->begin();
1342         while(it != fonts->end())
1343         {
1344                 (*it)->DrawText();
1345                 ++it;
1346         }
1347 }
1348
1349 /*
1350 To run once per scene
1351 */
1352 void KX_KetsjiEngine::PostRenderScene(KX_Scene* scene)
1353 {
1354         m_rendertools->MotionBlur(m_rasterizer);
1355         scene->Render2DFilters(m_canvas);
1356 #ifdef WITH_PYTHON
1357         scene->RunDrawingCallbacks(scene->GetPostDrawCB());     
1358 #endif
1359         m_rasterizer->FlushDebugLines();
1360 }
1361
1362 void KX_KetsjiEngine::StopEngine()
1363 {
1364         if (m_bInitialized)
1365         {
1366
1367                 if (m_animation_record)
1368                 {
1369 //                      printf("TestHandlesPhysicsObjectToAnimationIpo\n");
1370                         m_sceneconverter->TestHandlesPhysicsObjectToAnimationIpo();
1371                 }
1372
1373                 KX_SceneList::iterator sceneit;
1374                 for (sceneit = m_scenes.begin();sceneit != m_scenes.end() ; sceneit++)
1375                 {
1376                         KX_Scene* scene = *sceneit;
1377                         m_sceneconverter->RemoveScene(scene);
1378                 }       
1379                 m_scenes.clear();
1380
1381                 // cleanup all the stuff                
1382                 m_rasterizer->Exit();
1383         }
1384 }
1385
1386 // Scene Management is able to switch between scenes
1387 // and have several scene's running in parallel
1388 void KX_KetsjiEngine::AddScene(KX_Scene* scene)
1389
1390         m_scenes.push_back(scene);
1391         PostProcessScene(scene);
1392         SceneListsChanged();
1393 }
1394
1395
1396
1397 void KX_KetsjiEngine::PostProcessScene(KX_Scene* scene)
1398 {
1399         bool override_camera = (m_overrideCam && (scene->GetName() == m_overrideSceneName));
1400
1401         SG_SetActiveStage(SG_STAGE_SCENE);
1402
1403         // if there is no activecamera, or the camera is being
1404         // overridden we need to construct a temporarily camera
1405         if (!scene->GetActiveCamera() || override_camera)
1406         {
1407                 KX_Camera* activecam = NULL;
1408
1409                 RAS_CameraData camdata = RAS_CameraData();
1410                 if (override_camera) camdata.m_lens = m_overrideCamLens;
1411
1412                 activecam = new KX_Camera(scene,KX_Scene::m_callbacks,camdata);
1413                 activecam->SetName("__default__cam__");
1414         
1415                         // set transformation
1416                 if (override_camera) {
1417                         const MT_CmMatrix4x4& cammatdata = m_overrideCamViewMat;
1418                         MT_Transform trans = MT_Transform(cammatdata.getPointer());
1419                         MT_Transform camtrans;
1420                         camtrans.invert(trans);
1421                         
1422                         activecam->NodeSetLocalPosition(camtrans.getOrigin());
1423                         activecam->NodeSetLocalOrientation(camtrans.getBasis());
1424                         activecam->NodeUpdateGS(0);
1425                 } else {
1426                         activecam->NodeSetLocalPosition(MT_Point3(0.0, 0.0, 0.0));
1427                         activecam->NodeSetLocalOrientation(MT_Vector3(0.0, 0.0, 0.0));
1428                         activecam->NodeUpdateGS(0);
1429                 }
1430
1431                 scene->AddCamera(activecam);
1432                 scene->SetActiveCamera(activecam);
1433                 scene->GetObjectList()->Add(activecam->AddRef());
1434                 scene->GetRootParentList()->Add(activecam->AddRef());
1435                 //done with activecam
1436                 activecam->Release();
1437         }
1438         
1439         scene->UpdateParents(0.0);
1440 }
1441
1442
1443
1444 void KX_KetsjiEngine::RenderDebugProperties()
1445 {
1446         STR_String debugtxt;
1447         int xcoord = 10;        // mmmm, these constants were taken from blender source
1448         int ycoord = 14;        // to 'mimic' behaviour
1449
1450         float tottime = m_logger->GetAverage();
1451         if (tottime < 1e-6f) {
1452                 tottime = 1e-6f;
1453         }
1454
1455         // Set viewport to entire canvas
1456         RAS_Rect viewport;
1457         m_canvas->SetViewPort(0, 0, int(m_canvas->GetWidth()), int(m_canvas->GetHeight()));
1458         
1459         /* Framerate display */
1460         if (m_show_framerate) {
1461                 debugtxt.Format("swap : %.3f (%.3f frames per second)", tottime, 1.0/tottime);
1462                 m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED, 
1463                                                                         debugtxt.Ptr(),
1464                                                                         xcoord,
1465                                                                         ycoord, 
1466                                                                         m_canvas->GetWidth() /* RdV, TODO ?? */, 
1467                                                                         m_canvas->GetHeight() /* RdV, TODO ?? */);
1468                 ycoord += 14;
1469         }
1470
1471         /* Profile and framerate display */
1472         if (m_show_profile)
1473         {               
1474                 for (int j = tc_first; j < tc_numCategories; j++)
1475                 {
1476                         debugtxt.Format(m_profileLabels[j]);
1477                         m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED, 
1478                                                                                 debugtxt.Ptr(),
1479                                                                                 xcoord,ycoord,
1480                                                                                 m_canvas->GetWidth(), 
1481                                                                                 m_canvas->GetHeight());
1482                         double time = m_logger->GetAverage((KX_TimeCategory)j);
1483                         debugtxt.Format("%.3fms (%2.2f %%)", time*1000.f, time/tottime * 100.f);
1484                         m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED, 
1485                                                                                 debugtxt.Ptr(),
1486                                                                                 xcoord + 60 ,ycoord,
1487                                                                                 m_canvas->GetWidth(), 
1488                                                                                 m_canvas->GetHeight());
1489                         ycoord += 14;
1490                 }
1491         }
1492
1493         /* Property display*/
1494         if (m_show_debug_properties && m_propertiesPresent)
1495         {
1496                 KX_SceneList::iterator sceneit;
1497                 for (sceneit = m_scenes.begin();sceneit != m_scenes.end() ; sceneit++)
1498                 {
1499                         KX_Scene* scene = *sceneit;
1500                         /* the 'normal' debug props */
1501                         vector<SCA_DebugProp*>& debugproplist = scene->GetDebugProperties();
1502                         
1503                         for (vector<SCA_DebugProp*>::iterator it = debugproplist.begin();
1504                                  !(it==debugproplist.end());it++)
1505                         {
1506                                 CValue* propobj = (*it)->m_obj;
1507                                 STR_String objname = propobj->GetName();
1508                                 STR_String propname = (*it)->m_name;
1509                                 if (propname == "__state__")
1510                                 {
1511                                         // reserve name for object state
1512                                         KX_GameObject* gameobj = static_cast<KX_GameObject*>(propobj);
1513                                         unsigned int state = gameobj->GetState();
1514                                         debugtxt = objname + "." + propname + " = ";
1515                                         bool first = true;
1516                                         for (int statenum=1;state;state >>= 1, statenum++)
1517                                         {
1518                                                 if (state & 1)
1519                                                 {
1520                                                         if (!first)
1521                                                         {
1522                                                                 debugtxt += ",";
1523                                                         }
1524                                                         debugtxt += STR_String(statenum);
1525                                                         first = false;
1526                                                 }
1527                                         }
1528                                         m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED, 
1529                                                                                                         debugtxt.Ptr(),
1530                                                                                                         xcoord,
1531                                                                                                         ycoord,
1532                                                                                                         m_canvas->GetWidth(),
1533                                                                                                         m_canvas->GetHeight());
1534                                         ycoord += 14;
1535                                 }
1536                                 else
1537                                 {
1538                                         CValue* propval = propobj->GetProperty(propname);
1539                                         if (propval)
1540                                         {
1541                                                 STR_String text = propval->GetText();
1542                                                 debugtxt = objname + "." + propname + " = " + text;
1543                                                 m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED, 
1544                                                                                                         debugtxt.Ptr(),
1545                                                                                                         xcoord,
1546                                                                                                         ycoord,
1547                                                                                                         m_canvas->GetWidth(),
1548                                                                                                         m_canvas->GetHeight());
1549                                                 ycoord += 14;
1550                                         }
1551                                 }
1552                         }
1553                 }
1554         }
1555 }
1556
1557
1558 KX_SceneList* KX_KetsjiEngine::CurrentScenes()
1559 {
1560         return &m_scenes;       
1561 }
1562
1563
1564
1565 KX_Scene* KX_KetsjiEngine::FindScene(const STR_String& scenename)
1566 {
1567         KX_SceneList::iterator sceneit = m_scenes.begin();
1568
1569         // bit risky :) better to split the second clause 
1570         while ( (sceneit != m_scenes.end()) 
1571                         && ((*sceneit)->GetName() != scenename))
1572         {
1573                 sceneit++;
1574         }
1575
1576         return ((sceneit == m_scenes.end()) ? NULL : *sceneit); 
1577 }
1578
1579
1580
1581 void KX_KetsjiEngine::ConvertAndAddScene(const STR_String& scenename,bool overlay)
1582 {
1583         // only add scene when it doesn't exist!
1584         if (FindScene(scenename))
1585         {
1586                 STR_String tmpname = scenename;
1587                 printf("warning: scene %s already exists, not added!\n",tmpname.Ptr());
1588         }
1589         else
1590         {
1591                 if (overlay)
1592                 {
1593                         m_addingOverlayScenes.insert(scenename);
1594                 }
1595                 else
1596                 {
1597                         m_addingBackgroundScenes.insert(scenename);
1598                 }
1599         }
1600 }
1601
1602
1603
1604
1605 void KX_KetsjiEngine::RemoveScene(const STR_String& scenename)
1606 {
1607         if (FindScene(scenename))
1608         {
1609                 m_removingScenes.insert(scenename);
1610         }
1611         else
1612         {
1613 //              STR_String tmpname = scenename;
1614                 std::cout << "warning: scene " << scenename << " does not exist, not removed!" << std::endl;
1615         }
1616 }
1617
1618
1619
1620 void KX_KetsjiEngine::RemoveScheduledScenes()
1621 {
1622         if (m_removingScenes.size())
1623         {
1624                 set<STR_String>::iterator scenenameit;
1625                 for (scenenameit=m_removingScenes.begin();scenenameit != m_removingScenes.end();scenenameit++)
1626                 {
1627                         STR_String scenename = *scenenameit;
1628
1629                         KX_SceneList::iterator sceneit;
1630                         for (sceneit = m_scenes.begin();sceneit != m_scenes.end() ; sceneit++)
1631                         {
1632                                 KX_Scene* scene = *sceneit;
1633                                 if (scene->GetName()==scenename)
1634                                 {
1635                                         m_sceneconverter->RemoveScene(scene);
1636                                         m_scenes.erase(sceneit);
1637                                         break;
1638                                 }
1639                         }       
1640                 }
1641                 m_removingScenes.clear();
1642         }
1643 }
1644
1645 KX_Scene* KX_KetsjiEngine::CreateScene(Scene *scene)
1646 {
1647         KX_Scene* tmpscene = new KX_Scene(m_keyboarddevice,
1648                                                                           m_mousedevice,
1649                                                                           m_networkdevice,
1650                                                                           scene->id.name+2,
1651                                                                           scene,
1652                                                                           m_canvas);
1653
1654         m_sceneconverter->ConvertScene(tmpscene,
1655                                                           m_rendertools,
1656                                                           m_canvas);
1657
1658         return tmpscene;
1659 }
1660
1661 KX_Scene* KX_KetsjiEngine::CreateScene(const STR_String& scenename)
1662 {
1663         Scene *scene = m_sceneconverter->GetBlenderSceneForName(scenename);
1664         return CreateScene(scene);
1665 }
1666
1667 void KX_KetsjiEngine::AddScheduledScenes()
1668 {
1669         set<STR_String>::iterator scenenameit;
1670
1671         if (m_addingOverlayScenes.size())
1672         {
1673                 for (scenenameit = m_addingOverlayScenes.begin();
1674                         scenenameit != m_addingOverlayScenes.end();
1675                         scenenameit++)
1676                 {
1677                         STR_String scenename = *scenenameit;
1678                         KX_Scene* tmpscene = CreateScene(scenename);
1679                         m_scenes.push_back(tmpscene);
1680                         PostProcessScene(tmpscene);
1681                 }
1682                 m_addingOverlayScenes.clear();
1683         }
1684         
1685         if (m_addingBackgroundScenes.size())
1686         {
1687                 for (scenenameit = m_addingBackgroundScenes.begin();
1688                         scenenameit != m_addingBackgroundScenes.end();
1689                         scenenameit++)
1690                 {
1691                         STR_String scenename = *scenenameit;
1692                         KX_Scene* tmpscene = CreateScene(scenename);
1693                         m_scenes.insert(m_scenes.begin(),tmpscene);
1694                         PostProcessScene(tmpscene);
1695
1696                 }
1697                 m_addingBackgroundScenes.clear();
1698         }
1699 }
1700
1701
1702
1703 void KX_KetsjiEngine::ReplaceScene(const STR_String& oldscene,const STR_String& newscene)
1704 {
1705         m_replace_scenes.insert(std::make_pair(oldscene,newscene));
1706 }
1707
1708 // replace scene is not the same as removing and adding because the
1709 // scene must be in exact the same place (to maintain drawingorder)
1710 // (nzc) - should that not be done with a scene-display list? It seems
1711 // stupid to rely on the mem allocation order...
1712 void KX_KetsjiEngine::ReplaceScheduledScenes()
1713 {
1714         if (m_replace_scenes.size())
1715         {
1716                 set<pair<STR_String,STR_String> >::iterator scenenameit;
1717                 
1718                 for (scenenameit = m_replace_scenes.begin();
1719                         scenenameit != m_replace_scenes.end();
1720                         scenenameit++)
1721                 {
1722                         STR_String oldscenename = (*scenenameit).first;
1723                         STR_String newscenename = (*scenenameit).second;
1724                         int i=0;
1725                         /* Scenes are not supposed to be included twice... I think */
1726                         KX_SceneList::iterator sceneit;
1727                         for (sceneit = m_scenes.begin();sceneit != m_scenes.end() ; sceneit++)
1728                         {
1729                                 KX_Scene* scene = *sceneit;
1730                                 if (scene->GetName() == oldscenename)
1731                                 {
1732                                         m_sceneconverter->RemoveScene(scene);
1733                                         KX_Scene* tmpscene = CreateScene(newscenename);
1734                                         m_scenes[i]=tmpscene;
1735                                         PostProcessScene(tmpscene);
1736                                 }
1737                                 i++;
1738                         }
1739                 }
1740                 m_replace_scenes.clear();
1741         }       
1742 }
1743
1744
1745
1746 void KX_KetsjiEngine::SuspendScene(const STR_String& scenename)
1747 {
1748         KX_Scene*  scene = FindScene(scenename);
1749         if (scene) scene->Suspend();
1750 }
1751
1752
1753
1754 void KX_KetsjiEngine::ResumeScene(const STR_String& scenename)
1755 {
1756         KX_Scene*  scene = FindScene(scenename);
1757         if (scene) scene->Resume();
1758 }
1759
1760
1761
1762 void KX_KetsjiEngine::SetUseFixedTime(bool bUseFixedTime)
1763 {
1764         m_bFixedTime = bUseFixedTime;
1765 }
1766
1767
1768 void    KX_KetsjiEngine::SetAnimRecordMode(bool animation_record, int startFrame)
1769 {
1770         m_animation_record = animation_record;
1771         if (animation_record)
1772         {
1773                 //when recording physics keyframes, always run at a fixed framerate
1774                 m_bFixedTime = true;
1775         }
1776         m_currentFrame = startFrame;
1777 }
1778
1779 bool KX_KetsjiEngine::GetUseFixedTime(void) const
1780 {
1781         return m_bFixedTime;
1782 }
1783
1784 double KX_KetsjiEngine::GetSuspendedDelta()
1785 {
1786         return m_suspendeddelta;
1787 }
1788
1789 double KX_KetsjiEngine::GetTicRate()
1790 {
1791         return m_ticrate;
1792 }
1793
1794 void KX_KetsjiEngine::SetTicRate(double ticrate)
1795 {
1796         m_ticrate = ticrate;
1797 }
1798
1799 int KX_KetsjiEngine::GetMaxLogicFrame()
1800 {
1801         return m_maxLogicFrame;
1802 }
1803
1804 void KX_KetsjiEngine::SetMaxLogicFrame(int frame)
1805 {
1806         m_maxLogicFrame = frame;
1807 }
1808
1809 int KX_KetsjiEngine::GetMaxPhysicsFrame()
1810 {
1811         return m_maxPhysicsFrame;
1812 }
1813
1814 void KX_KetsjiEngine::SetMaxPhysicsFrame(int frame)
1815 {
1816         m_maxPhysicsFrame = frame;
1817 }
1818
1819 double KX_KetsjiEngine::GetAnimFrameRate()
1820 {
1821         return m_anim_framerate;
1822 }
1823
1824 double KX_KetsjiEngine::GetClockTime(void) const
1825 {
1826         return m_clockTime;
1827 }
1828
1829 double KX_KetsjiEngine::GetFrameTime(void) const
1830 {
1831         return m_frameTime;
1832 }
1833
1834 double KX_KetsjiEngine::GetRealTime(void) const
1835 {
1836         return m_kxsystem->GetTimeInSeconds();
1837 }
1838
1839 void KX_KetsjiEngine::SetAnimFrameRate(double framerate)
1840 {
1841         m_anim_framerate = framerate;
1842 }
1843
1844 double KX_KetsjiEngine::GetAverageFrameRate()
1845 {
1846         return m_average_framerate;
1847 }
1848
1849 void KX_KetsjiEngine::SetTimingDisplay(bool frameRate, bool profile, bool properties)
1850 {
1851         m_show_framerate = frameRate;
1852         m_show_profile = profile;
1853         m_show_debug_properties = properties;
1854 }
1855
1856
1857
1858 void KX_KetsjiEngine::GetTimingDisplay(bool& frameRate, bool& profile, bool& properties) const
1859 {
1860         frameRate = m_show_framerate;
1861         profile = m_show_profile;
1862         properties = m_show_debug_properties;
1863 }
1864
1865
1866
1867 void KX_KetsjiEngine::ProcessScheduledScenes(void)
1868 {
1869         // Check whether there will be changes to the list of scenes
1870         if (m_addingOverlayScenes.size() ||
1871                 m_addingBackgroundScenes.size() ||
1872                 m_replace_scenes.size() ||
1873                 m_removingScenes.size()) {
1874
1875                 // Change the scene list
1876                 ReplaceScheduledScenes();
1877                 RemoveScheduledScenes();
1878                 AddScheduledScenes();
1879
1880                 // Notify
1881                 SceneListsChanged();
1882         }
1883 }
1884
1885
1886
1887 void KX_KetsjiEngine::SceneListsChanged(void)
1888 {
1889         m_propertiesPresent = false;
1890         KX_SceneList::iterator sceneit = m_scenes.begin();
1891         while ((sceneit != m_scenes.end()) && (!m_propertiesPresent))
1892         {
1893                 KX_Scene* scene = *sceneit;
1894                 vector<SCA_DebugProp*>& debugproplist = scene->GetDebugProperties();    
1895                 m_propertiesPresent = !debugproplist.empty();
1896                 sceneit++;
1897         }
1898 }
1899
1900
1901 void KX_KetsjiEngine::SetHideCursor(bool hideCursor)
1902 {
1903         m_hideCursor = hideCursor;
1904 }
1905
1906
1907 bool KX_KetsjiEngine::GetHideCursor(void) const
1908 {
1909         return m_hideCursor;
1910 }
1911
1912
1913 void KX_KetsjiEngine::SetUseOverrideFrameColor(bool overrideFrameColor)
1914 {
1915         m_overrideFrameColor = overrideFrameColor;
1916 }
1917
1918
1919 bool KX_KetsjiEngine::GetUseOverrideFrameColor(void) const
1920 {
1921         return m_overrideFrameColor;
1922 }
1923
1924
1925 void KX_KetsjiEngine::SetOverrideFrameColor(float r, float g, float b)
1926 {
1927         m_overrideFrameColorR = r;
1928         m_overrideFrameColorG = g;
1929         m_overrideFrameColorB = b;
1930 }
1931
1932
1933 void KX_KetsjiEngine::GetOverrideFrameColor(float& r, float& g, float& b) const
1934 {
1935         r = m_overrideFrameColorR;
1936         g = m_overrideFrameColorG;
1937         b = m_overrideFrameColorB;
1938 }
1939
1940