Moving the letterbox clear for the embedded player so it only clears when it needs...
[blender.git] / source / gameengine / BlenderRoutines / BL_KetsjiEmbedStart.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  * Blender's Ketsji startpoint
29  */
30
31 /** \file gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp
32  *  \ingroup blroutines
33  */
34
35
36 #include <signal.h>
37 #include <stdlib.h>
38 #include <stdio.h>
39
40 #if defined(WIN32) && !defined(FREE_WINDOWS)
41 // don't show stl-warnings
42 #pragma warning (disable:4786)
43 #endif
44
45 #include "GL/glew.h"
46
47 #include "KX_BlenderGL.h"
48 #include "KX_BlenderCanvas.h"
49 #include "KX_BlenderKeyboardDevice.h"
50 #include "KX_BlenderMouseDevice.h"
51 #include "KX_BlenderRenderTools.h"
52 #include "KX_BlenderSystem.h"
53 #include "BL_Material.h"
54
55 #include "KX_KetsjiEngine.h"
56 #include "KX_BlenderSceneConverter.h"
57 #include "KX_PythonInit.h"
58 #include "KX_PyConstraintBinding.h"
59
60 #include "RAS_GLExtensionManager.h"
61 #include "RAS_OpenGLRasterizer.h"
62 #include "RAS_VAOpenGLRasterizer.h"
63 #include "RAS_ListRasterizer.h"
64
65 #include "NG_LoopBackNetworkDeviceInterface.h"
66
67 #include "BL_System.h"
68
69 #include "GPU_extensions.h"
70 #include "Value.h"
71
72
73
74 #ifdef __cplusplus
75 extern "C" {
76 #endif
77         /***/
78 #include "DNA_view3d_types.h"
79 #include "DNA_screen_types.h"
80 #include "DNA_userdef_types.h"
81 #include "DNA_windowmanager_types.h"
82 #include "BKE_global.h"
83 #include "BKE_report.h"
84 /* #include "BKE_screen.h" */ /* cant include this because of 'new' function name */
85 extern float BKE_screen_view3d_zoom_to_fac(float camzoom);
86
87
88 //XXX #include "BIF_screen.h"
89 //XXX #include "BIF_scrarea.h"
90
91 #include "BKE_main.h"
92 #include "BLI_blenlib.h"
93 #include "BLO_readfile.h"
94 #include "DNA_scene_types.h"
95 #include "BKE_ipo.h"
96         /***/
97
98 #include "AUD_C-API.h"
99
100 //XXX #include "BSE_headerbuttons.h"
101 #include "BKE_context.h"
102 #include "../../blender/windowmanager/WM_types.h"
103 #include "../../blender/windowmanager/wm_window.h"
104 #include "../../blender/windowmanager/wm_event_system.h"
105 #ifdef __cplusplus
106 }
107 #endif
108
109
110 static BlendFileData *load_game_data(char *filename)
111 {
112         ReportList reports;
113         BlendFileData *bfd;
114         
115         BKE_reports_init(&reports, RPT_STORE);
116         bfd= BLO_read_from_file(filename, &reports);
117
118         if (!bfd) {
119                 printf("Loading %s failed: ", filename);
120                 BKE_reports_print(&reports, RPT_ERROR);
121         }
122
123         BKE_reports_clear(&reports);
124
125         return bfd;
126 }
127
128 extern "C" void StartKetsjiShell(struct bContext *C, struct ARegion *ar, rcti *cam_frame, int always_use_expand_framing)
129 {
130         /* context values */
131         struct wmWindow *win= CTX_wm_window(C);
132         struct Scene *startscene= CTX_data_scene(C);
133         struct Main* maggie1= CTX_data_main(C);
134
135
136         RAS_Rect area_rect;
137         area_rect.SetLeft(cam_frame->xmin);
138         area_rect.SetBottom(cam_frame->ymin);
139         area_rect.SetRight(cam_frame->xmax);
140         area_rect.SetTop(cam_frame->ymax);
141
142         int exitrequested = KX_EXIT_REQUEST_NO_REQUEST;
143         Main* blenderdata = maggie1;
144
145         char* startscenename = startscene->id.name+2;
146         char pathname[FILE_MAXDIR+FILE_MAXFILE], oldsce[FILE_MAXDIR+FILE_MAXFILE];
147         STR_String exitstring = "";
148         BlendFileData *bfd= NULL;
149
150         BLI_strncpy(pathname, blenderdata->name, sizeof(pathname));
151         BLI_strncpy(oldsce, G.main->name, sizeof(oldsce));
152 #ifdef WITH_PYTHON
153         resetGamePythonPath(); // need this so running a second time wont use an old blendfiles path
154         setGamePythonPath(G.main->name);
155
156         // Acquire Python's GIL (global interpreter lock)
157         // so we can safely run Python code and API calls
158         PyGILState_STATE gilstate = PyGILState_Ensure();
159         
160         PyObject *pyGlobalDict = PyDict_New(); /* python utility storage, spans blend file loading */
161 #endif
162         
163         bgl::InitExtensions(true);
164
165         // VBO code for derived mesh is not compatible with BGE (couldn't find why), so disable
166         int disableVBO = (U.gameflags & USER_DISABLE_VBO);
167         U.gameflags |= USER_DISABLE_VBO;
168
169         do
170         {
171                 View3D *v3d= CTX_wm_view3d(C);
172                 RegionView3D *rv3d= CTX_wm_region_view3d(C);
173
174                 // get some preferences
175                 SYS_SystemHandle syshandle = SYS_GetSystem();
176                 bool properties = (SYS_GetCommandLineInt(syshandle, "show_properties", 0) != 0);
177                 bool usefixed = (SYS_GetCommandLineInt(syshandle, "fixedtime", 0) != 0);
178                 bool profile = (SYS_GetCommandLineInt(syshandle, "show_profile", 0) != 0);
179                 bool frameRate = (SYS_GetCommandLineInt(syshandle, "show_framerate", 0) != 0);
180                 bool animation_record = (SYS_GetCommandLineInt(syshandle, "animation_record", 0) != 0);
181                 bool displaylists = (SYS_GetCommandLineInt(syshandle, "displaylists", 0) != 0);
182 #ifdef WITH_PYTHON
183                 bool nodepwarnings = (SYS_GetCommandLineInt(syshandle, "ignore_deprecation_warnings", 0) != 0);
184 #endif
185                 bool novertexarrays = (SYS_GetCommandLineInt(syshandle, "novertexarrays", 0) != 0);
186                 bool mouse_state = startscene->gm.flag & GAME_SHOW_MOUSE;
187
188                 if(animation_record) usefixed= true; /* override since you's always want fixed time for sim recording */
189
190                 // create the canvas, rasterizer and rendertools
191                 RAS_ICanvas* canvas = new KX_BlenderCanvas(win, area_rect, ar);
192                 
193                 // default mouse state set on render panel
194                 if (mouse_state)
195                         canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
196                 else
197                         canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);
198                 RAS_IRenderTools* rendertools = new KX_BlenderRenderTools();
199                 RAS_IRasterizer* rasterizer = NULL;
200                 
201                 if(displaylists) {
202                         if (GLEW_VERSION_1_1 && !novertexarrays)
203                                 rasterizer = new RAS_ListRasterizer(canvas, true, true);
204                         else
205                                 rasterizer = new RAS_ListRasterizer(canvas);
206                 }
207                 else if (GLEW_VERSION_1_1 && !novertexarrays)
208                         rasterizer = new RAS_VAOpenGLRasterizer(canvas, false);
209                 else
210                         rasterizer = new RAS_OpenGLRasterizer(canvas);
211                 
212                 // create the inputdevices
213                 KX_BlenderKeyboardDevice* keyboarddevice = new KX_BlenderKeyboardDevice();
214                 KX_BlenderMouseDevice* mousedevice = new KX_BlenderMouseDevice();
215                 
216                 // create a networkdevice
217                 NG_NetworkDeviceInterface* networkdevice = new
218                         NG_LoopBackNetworkDeviceInterface();
219
220                 //
221                 // create a ketsji/blendersystem (only needed for timing and stuff)
222                 KX_BlenderSystem* kxsystem = new KX_BlenderSystem();
223                 
224                 // create the ketsjiengine
225                 KX_KetsjiEngine* ketsjiengine = new KX_KetsjiEngine(kxsystem);
226                 
227                 // set the devices
228                 ketsjiengine->SetKeyboardDevice(keyboarddevice);
229                 ketsjiengine->SetMouseDevice(mousedevice);
230                 ketsjiengine->SetNetworkDevice(networkdevice);
231                 ketsjiengine->SetCanvas(canvas);
232                 ketsjiengine->SetRenderTools(rendertools);
233                 ketsjiengine->SetRasterizer(rasterizer);
234                 ketsjiengine->SetNetworkDevice(networkdevice);
235                 ketsjiengine->SetUseFixedTime(usefixed);
236                 ketsjiengine->SetTimingDisplay(frameRate, profile, properties);
237
238 #ifdef WITH_PYTHON
239                 CValue::SetDeprecationWarnings(nodepwarnings);
240 #endif
241
242                 //lock frame and camera enabled - storing global values
243                 int tmp_lay= startscene->lay;
244                 Object *tmp_camera = startscene->camera;
245
246                 if (v3d->scenelock==0){
247                         startscene->lay= v3d->lay;
248                         startscene->camera= v3d->camera;
249                 }
250
251                 // some blender stuff
252                 float camzoom;
253                 int draw_letterbox = 0;
254                 
255                 if(rv3d->persp==RV3D_CAMOB) {
256                         if(startscene->gm.framing.type == SCE_GAMEFRAMING_BARS) { /* Letterbox */
257                                 camzoom = 1.0f;
258                                 draw_letterbox = 1;
259                         }
260                         else {
261                                 camzoom = BKE_screen_view3d_zoom_to_fac(rv3d->camzoom)*4.0f;
262                         }
263                 }
264                 else {
265                         camzoom = 2.0;
266                 }
267
268
269                 ketsjiengine->SetDrawType(v3d->drawtype);
270                 ketsjiengine->SetCameraZoom(camzoom);
271                 
272                 // if we got an exitcode 3 (KX_EXIT_REQUEST_START_OTHER_GAME) load a different file
273                 if (exitrequested == KX_EXIT_REQUEST_START_OTHER_GAME || exitrequested == KX_EXIT_REQUEST_RESTART_GAME)
274                 {
275                         exitrequested = KX_EXIT_REQUEST_NO_REQUEST;
276                         if (bfd) BLO_blendfiledata_free(bfd);
277                         
278                         char basedpath[240];
279                         // base the actuator filename with respect
280                         // to the original file working directory
281
282                         if (exitstring != "")
283                                 strcpy(basedpath, exitstring.Ptr());
284
285                         // load relative to the last loaded file, this used to be relative
286                         // to the first file but that makes no sense, relative paths in
287                         // blend files should be relative to that file, not some other file
288                         // that happened to be loaded first
289                         BLI_path_abs(basedpath, pathname);
290                         bfd = load_game_data(basedpath);
291                         
292                         // if it wasn't loaded, try it forced relative
293                         if (!bfd)
294                         {
295                                 // just add "//" in front of it
296                                 char temppath[242];
297                                 strcpy(temppath, "//");
298                                 strcat(temppath, basedpath);
299                                 
300                                 BLI_path_abs(temppath, pathname);
301                                 bfd = load_game_data(temppath);
302                         }
303                         
304                         // if we got a loaded blendfile, proceed
305                         if (bfd)
306                         {
307                                 blenderdata = bfd->main;
308                                 startscenename = bfd->curscene->id.name + 2;
309
310                                 if(blenderdata) {
311                                         BLI_strncpy(G.main->name, blenderdata->name, sizeof(G.main->name));
312                                         BLI_strncpy(pathname, blenderdata->name, sizeof(pathname));
313 #ifdef WITH_PYTHON
314                                         setGamePythonPath(G.main->name);
315 #endif
316                                 }
317                         }
318                         // else forget it, we can't find it
319                         else
320                         {
321                                 exitrequested = KX_EXIT_REQUEST_QUIT_GAME;
322                         }
323                 }
324
325                 Scene *scene= bfd ? bfd->curscene : (Scene *)BLI_findstring(&blenderdata->scene, startscenename, offsetof(ID, name) + 2);
326
327                 if (scene)
328                 {
329                         int startFrame = scene->r.cfra;
330                         ketsjiengine->SetAnimRecordMode(animation_record, startFrame);
331                         
332                         // Quad buffered needs a special window.
333                         if(scene->gm.stereoflag == STEREO_ENABLED){
334                                 if (scene->gm.stereomode != RAS_IRasterizer::RAS_STEREO_QUADBUFFERED)
335                                         rasterizer->SetStereoMode((RAS_IRasterizer::StereoMode) scene->gm.stereomode);
336
337                                 rasterizer->SetEyeSeparation(scene->gm.eyeseparation);
338                         }
339
340                         rasterizer->SetBackColor(scene->gm.framing.col[0], scene->gm.framing.col[1], scene->gm.framing.col[2], 0.0f);
341                 }
342                 
343                 if (exitrequested != KX_EXIT_REQUEST_QUIT_GAME)
344                 {
345                         if (rv3d->persp != RV3D_CAMOB)
346                         {
347                                 ketsjiengine->EnableCameraOverride(startscenename);
348                                 ketsjiengine->SetCameraOverrideUseOrtho((rv3d->persp == RV3D_ORTHO));
349                                 ketsjiengine->SetCameraOverrideProjectionMatrix(MT_CmMatrix4x4(rv3d->winmat));
350                                 ketsjiengine->SetCameraOverrideViewMatrix(MT_CmMatrix4x4(rv3d->viewmat));
351                                 ketsjiengine->SetCameraOverrideClipping(v3d->near, v3d->far);
352                                 ketsjiengine->SetCameraOverrideLens(v3d->lens);
353                         }
354                         
355                         // create a scene converter, create and convert the startingscene
356                         KX_ISceneConverter* sceneconverter = new KX_BlenderSceneConverter(blenderdata, ketsjiengine);
357                         ketsjiengine->SetSceneConverter(sceneconverter);
358                         sceneconverter->addInitFromFrame=false;
359                         if (always_use_expand_framing)
360                                 sceneconverter->SetAlwaysUseExpandFraming(true);
361
362                         bool usemat = false, useglslmat = false;
363
364                         if(GLEW_ARB_multitexture && GLEW_VERSION_1_1)
365                                 usemat = true;
366
367                         if(GPU_glsl_support())
368                                 useglslmat = true;
369                         else if(scene->gm.matmode == GAME_MAT_GLSL)
370                                 usemat = false;
371
372                         if(usemat && (scene->gm.matmode != GAME_MAT_TEXFACE))
373                                 sceneconverter->SetMaterials(true);
374                         if(useglslmat && (scene->gm.matmode == GAME_MAT_GLSL))
375                                 sceneconverter->SetGLSLMaterials(true);
376                                         
377                         KX_Scene* startscene = new KX_Scene(keyboarddevice,
378                                 mousedevice,
379                                 networkdevice,
380                                 startscenename,
381                                 scene,
382                                 canvas);
383
384 #ifdef WITH_PYTHON
385                         // some python things
386                         PyObject *gameLogic, *gameLogic_keys;
387                         setupGamePython(ketsjiengine, startscene, blenderdata, pyGlobalDict, &gameLogic, &gameLogic_keys, 0, NULL);
388 #endif // WITH_PYTHON
389
390                         //initialize Dome Settings
391                         if(scene->gm.stereoflag == STEREO_DOME)
392                                 ketsjiengine->InitDome(scene->gm.dome.res, scene->gm.dome.mode, scene->gm.dome.angle, scene->gm.dome.resbuf, scene->gm.dome.tilt, scene->gm.dome.warptext);
393
394                         // initialize 3D Audio Settings
395                         AUD_setSpeedOfSound(scene->audio.speed_of_sound);
396                         AUD_setDopplerFactor(scene->audio.doppler_factor);
397                         AUD_setDistanceModel(AUD_DistanceModel(scene->audio.distance_model));
398
399                         // from see blender.c:
400                         // FIXME: this version patching should really be part of the file-reading code,
401                         // but we still get too many unrelated data-corruption crashes otherwise...
402                         if (blenderdata->versionfile < 250)
403                                 do_versions_ipos_to_animato(blenderdata);
404
405                         if (sceneconverter)
406                         {
407                                 // convert and add scene
408                                 sceneconverter->ConvertScene(
409                                         startscene,
410                                         rendertools,
411                                         canvas);
412                                 ketsjiengine->AddScene(startscene);
413                                 
414                                 // init the rasterizer
415                                 rasterizer->Init();
416                                 
417                                 // start the engine
418                                 ketsjiengine->StartEngine(true);
419                                 
420
421                                 // Set the animation playback rate for ipo's and actions
422                                 // the framerate below should patch with FPS macro defined in blendef.h
423                                 // Could be in StartEngine set the framerate, we need the scene to do this
424                                 ketsjiengine->SetAnimFrameRate(FPS);
425                                 
426                                 // the mainloop
427                                 printf("\nBlender Game Engine Started\n");
428                                 while (!exitrequested)
429                                 {
430                                         // first check if we want to exit
431                                         exitrequested = ketsjiengine->GetExitCode();
432                                         
433                                         // kick the engine
434                                         bool render = ketsjiengine->NextFrame();
435                                         
436                                         if (render)
437                                         {
438                                                 if(draw_letterbox) {
439                                                         // Clear screen to border color
440                                                         // We do this here since we set the canvas to be within the frames. This means the engine
441                                                         // itself is unaware of the extra space, so we clear the whole region for it.
442                                                         glClearColor(scene->gm.framing.col[0], scene->gm.framing.col[1], scene->gm.framing.col[2], 1.0f);
443                                                         glViewport(ar->winrct.xmin, ar->winrct.ymin,
444                                                                 ar->winrct.xmax - ar->winrct.xmin, ar->winrct.ymax - ar->winrct.ymin);
445                                                         glClear(GL_COLOR_BUFFER_BIT);
446                                                 }
447
448                                                 // render the frame
449                                                 ketsjiengine->Render();
450                                         }
451                                         
452                                         wm_window_process_events_nosleep();
453                                         
454                                         // test for the ESC key
455                                         //XXX while (qtest())
456                                         while(wmEvent *event= (wmEvent *)win->queue.first)
457                                         {
458                                                 short val = 0;
459                                                 //unsigned short event = 0; //XXX extern_qread(&val);
460                                                 
461                                                 if (keyboarddevice->ConvertBlenderEvent(event->type,event->val))
462                                                         exitrequested = KX_EXIT_REQUEST_BLENDER_ESC;
463                                                 
464                                                         /* Coordinate conversion... where
465                                                         * should this really be?
466                                                 */
467                                                 if (event->type==MOUSEMOVE) {
468                                                         /* Note, not nice! XXX 2.5 event hack */
469                                                         val = event->x - ar->winrct.xmin;
470                                                         mousedevice->ConvertBlenderEvent(MOUSEX, val);
471                                                         
472                                                         val = ar->winy - (event->y - ar->winrct.ymin) - 1;
473                                                         mousedevice->ConvertBlenderEvent(MOUSEY, val);
474                                                 }
475                                                 else {
476                                                         mousedevice->ConvertBlenderEvent(event->type,event->val);
477                                                 }
478                                                 
479                                                 BLI_remlink(&win->queue, event);
480                                                 wm_event_free(event);
481                                         }
482                                         
483                                         if(win != CTX_wm_window(C)) {
484                                                 exitrequested= KX_EXIT_REQUEST_OUTSIDE; /* window closed while bge runs */
485                                         }
486                                 }
487                                 printf("Blender Game Engine Finished\n");
488                                 exitstring = ketsjiengine->GetExitString();
489
490
491                                 // when exiting the mainloop
492 #ifdef WITH_PYTHON
493                                 // Clears the dictionary by hand:
494                                 // This prevents, extra references to global variables
495                                 // inside the GameLogic dictionary when the python interpreter is finalized.
496                                 // which allows the scene to safely delete them :)
497                                 // see: (space.c)->start_game
498                                 
499                                 //PyDict_Clear(PyModule_GetDict(gameLogic));
500                                 
501                                 // Keep original items, means python plugins will autocomplete members
502                                 int listIndex;
503                                 PyObject *gameLogic_keys_new = PyDict_Keys(PyModule_GetDict(gameLogic));
504                                 for (listIndex=0; listIndex < PyList_Size(gameLogic_keys_new); listIndex++)  {
505                                         PyObject* item = PyList_GET_ITEM(gameLogic_keys_new, listIndex);
506                                         if (!PySequence_Contains(gameLogic_keys, item)) {
507                                                 PyDict_DelItem( PyModule_GetDict(gameLogic), item);
508                                         }
509                                 }
510                                 Py_DECREF(gameLogic_keys_new);
511                                 gameLogic_keys_new = NULL;
512 #endif
513                                 ketsjiengine->StopEngine();
514 #ifdef WITH_PYTHON
515                                 exitGamePythonScripting();
516 #endif
517                                 networkdevice->Disconnect();
518                         }
519                         if (sceneconverter)
520                         {
521                                 delete sceneconverter;
522                                 sceneconverter = NULL;
523                         }
524
525 #ifdef WITH_PYTHON
526                         Py_DECREF(gameLogic_keys);
527                         gameLogic_keys = NULL;
528 #endif
529                 }
530                 //lock frame and camera enabled - restoring global values
531                 if (v3d->scenelock==0){
532                         startscene->lay= tmp_lay;
533                         startscene->camera= tmp_camera;
534                 }
535
536                 if(exitrequested != KX_EXIT_REQUEST_OUTSIDE)
537                 {
538                         // set the cursor back to normal
539                         canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
540                 }
541                 
542                 // clean up some stuff
543                 if (ketsjiengine)
544                 {
545                         delete ketsjiengine;
546                         ketsjiengine = NULL;
547                 }
548                 if (kxsystem)
549                 {
550                         delete kxsystem;
551                         kxsystem = NULL;
552                 }
553                 if (networkdevice)
554                 {
555                         delete networkdevice;
556                         networkdevice = NULL;
557                 }
558                 if (keyboarddevice)
559                 {
560                         delete keyboarddevice;
561                         keyboarddevice = NULL;
562                 }
563                 if (mousedevice)
564                 {
565                         delete mousedevice;
566                         mousedevice = NULL;
567                 }
568                 if (rasterizer)
569                 {
570                         delete rasterizer;
571                         rasterizer = NULL;
572                 }
573                 if (rendertools)
574                 {
575                         delete rendertools;
576                         rendertools = NULL;
577                 }
578                 if (canvas)
579                 {
580                         delete canvas;
581                         canvas = NULL;
582                 }
583         
584         } while (exitrequested == KX_EXIT_REQUEST_RESTART_GAME || exitrequested == KX_EXIT_REQUEST_START_OTHER_GAME);
585         
586         if (!disableVBO)
587                 U.gameflags &= ~USER_DISABLE_VBO;
588
589         if (bfd) BLO_blendfiledata_free(bfd);
590
591         BLI_strncpy(G.main->name, oldsce, sizeof(G.main->name));
592
593 #ifdef WITH_PYTHON
594         Py_DECREF(pyGlobalDict);
595
596         // Release Python's GIL
597         PyGILState_Release(gilstate);
598 #endif
599
600 }