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