59c5888ff35bc903d8ab028019b088c126e302b5
[blender-staging.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                 
254                 if(rv3d->persp==RV3D_CAMOB) {
255                         if(startscene->gm.framing.type == SCE_GAMEFRAMING_BARS) { /* Letterbox */
256                                 camzoom = 1.0f;
257                         }
258                         else {
259                                 camzoom = BKE_screen_view3d_zoom_to_fac(rv3d->camzoom);
260                         }
261                 }
262                 else {
263                         camzoom = 2.0;
264                 }
265
266
267                 ketsjiengine->SetDrawType(v3d->drawtype);
268                 ketsjiengine->SetCameraZoom(camzoom);
269                 
270                 // if we got an exitcode 3 (KX_EXIT_REQUEST_START_OTHER_GAME) load a different file
271                 if (exitrequested == KX_EXIT_REQUEST_START_OTHER_GAME || exitrequested == KX_EXIT_REQUEST_RESTART_GAME)
272                 {
273                         exitrequested = KX_EXIT_REQUEST_NO_REQUEST;
274                         if (bfd) BLO_blendfiledata_free(bfd);
275                         
276                         char basedpath[240];
277                         // base the actuator filename with respect
278                         // to the original file working directory
279
280                         if (exitstring != "")
281                                 strcpy(basedpath, exitstring.Ptr());
282
283                         // load relative to the last loaded file, this used to be relative
284                         // to the first file but that makes no sense, relative paths in
285                         // blend files should be relative to that file, not some other file
286                         // that happened to be loaded first
287                         BLI_path_abs(basedpath, pathname);
288                         bfd = load_game_data(basedpath);
289                         
290                         // if it wasn't loaded, try it forced relative
291                         if (!bfd)
292                         {
293                                 // just add "//" in front of it
294                                 char temppath[242];
295                                 strcpy(temppath, "//");
296                                 strcat(temppath, basedpath);
297                                 
298                                 BLI_path_abs(temppath, pathname);
299                                 bfd = load_game_data(temppath);
300                         }
301                         
302                         // if we got a loaded blendfile, proceed
303                         if (bfd)
304                         {
305                                 blenderdata = bfd->main;
306                                 startscenename = bfd->curscene->id.name + 2;
307
308                                 if(blenderdata) {
309                                         BLI_strncpy(G.main->name, blenderdata->name, sizeof(G.main->name));
310                                         BLI_strncpy(pathname, blenderdata->name, sizeof(pathname));
311 #ifdef WITH_PYTHON
312                                         setGamePythonPath(G.main->name);
313 #endif
314                                 }
315                         }
316                         // else forget it, we can't find it
317                         else
318                         {
319                                 exitrequested = KX_EXIT_REQUEST_QUIT_GAME;
320                         }
321                 }
322
323                 Scene *scene= bfd ? bfd->curscene : (Scene *)BLI_findstring(&blenderdata->scene, startscenename, offsetof(ID, name) + 2);
324
325                 if (scene)
326                 {
327                         int startFrame = scene->r.cfra;
328                         ketsjiengine->SetAnimRecordMode(animation_record, startFrame);
329                         
330                         // Quad buffered needs a special window.
331                         if(scene->gm.stereoflag == STEREO_ENABLED){
332                                 if (scene->gm.stereomode != RAS_IRasterizer::RAS_STEREO_QUADBUFFERED)
333                                         rasterizer->SetStereoMode((RAS_IRasterizer::StereoMode) scene->gm.stereomode);
334
335                                 rasterizer->SetEyeSeparation(scene->gm.eyeseparation);
336                         }
337
338                         rasterizer->SetBackColor(scene->gm.framing.col[0], scene->gm.framing.col[1], scene->gm.framing.col[2], 0.0f);
339                 }
340                 
341                 if (exitrequested != KX_EXIT_REQUEST_QUIT_GAME)
342                 {
343                         if (rv3d->persp != RV3D_CAMOB)
344                         {
345                                 ketsjiengine->EnableCameraOverride(startscenename);
346                                 ketsjiengine->SetCameraOverrideUseOrtho((rv3d->persp == RV3D_ORTHO));
347                                 ketsjiengine->SetCameraOverrideProjectionMatrix(MT_CmMatrix4x4(rv3d->winmat));
348                                 ketsjiengine->SetCameraOverrideViewMatrix(MT_CmMatrix4x4(rv3d->viewmat));
349                                 ketsjiengine->SetCameraOverrideClipping(v3d->near, v3d->far);
350                                 ketsjiengine->SetCameraOverrideLens(v3d->lens);
351                         }
352                         
353                         // create a scene converter, create and convert the startingscene
354                         KX_ISceneConverter* sceneconverter = new KX_BlenderSceneConverter(blenderdata, ketsjiengine);
355                         ketsjiengine->SetSceneConverter(sceneconverter);
356                         sceneconverter->addInitFromFrame=false;
357                         if (always_use_expand_framing)
358                                 sceneconverter->SetAlwaysUseExpandFraming(true);
359
360                         bool usemat = false, useglslmat = false;
361
362                         if(GLEW_ARB_multitexture && GLEW_VERSION_1_1)
363                                 usemat = true;
364
365                         if(GPU_glsl_support())
366                                 useglslmat = true;
367                         else if(scene->gm.matmode == GAME_MAT_GLSL)
368                                 usemat = false;
369
370                         if(usemat && (scene->gm.matmode != GAME_MAT_TEXFACE))
371                                 sceneconverter->SetMaterials(true);
372                         if(useglslmat && (scene->gm.matmode == GAME_MAT_GLSL))
373                                 sceneconverter->SetGLSLMaterials(true);
374                                         
375                         KX_Scene* startscene = new KX_Scene(keyboarddevice,
376                                 mousedevice,
377                                 networkdevice,
378                                 startscenename,
379                                 scene,
380                                 canvas);
381
382 #ifdef WITH_PYTHON
383                         // some python things
384                         PyObject *gameLogic, *gameLogic_keys;
385                         setupGamePython(ketsjiengine, startscene, blenderdata, pyGlobalDict, &gameLogic, &gameLogic_keys, 0, NULL);
386 #endif // WITH_PYTHON
387
388                         //initialize Dome Settings
389                         if(scene->gm.stereoflag == STEREO_DOME)
390                                 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);
391
392                         // initialize 3D Audio Settings
393                         AUD_setSpeedOfSound(scene->audio.speed_of_sound);
394                         AUD_setDopplerFactor(scene->audio.doppler_factor);
395                         AUD_setDistanceModel(AUD_DistanceModel(scene->audio.distance_model));
396
397                         // from see blender.c:
398                         // FIXME: this version patching should really be part of the file-reading code,
399                         // but we still get too many unrelated data-corruption crashes otherwise...
400                         if (blenderdata->versionfile < 250)
401                                 do_versions_ipos_to_animato(blenderdata);
402
403                         if (sceneconverter)
404                         {
405                                 // convert and add scene
406                                 sceneconverter->ConvertScene(
407                                         startscene,
408                                         rendertools,
409                                         canvas);
410                                 ketsjiengine->AddScene(startscene);
411                                 
412                                 // init the rasterizer
413                                 rasterizer->Init();
414                                 
415                                 // start the engine
416                                 ketsjiengine->StartEngine(true);
417                                 
418
419                                 // Set the animation playback rate for ipo's and actions
420                                 // the framerate below should patch with FPS macro defined in blendef.h
421                                 // Could be in StartEngine set the framerate, we need the scene to do this
422                                 ketsjiengine->SetAnimFrameRate(FPS);
423                                 
424                                 // the mainloop
425                                 printf("\nBlender Game Engine Started\n");
426                                 while (!exitrequested)
427                                 {
428                                         // first check if we want to exit
429                                         exitrequested = ketsjiengine->GetExitCode();
430
431                                         // Clear screen to border color
432                                         // We do this here since we set the canvas to be within the frames. This means the engine
433                                         // itself is unaware of the extra space, so we clear the whole region for it.
434                                         glClearColor(scene->gm.framing.col[0], scene->gm.framing.col[1], scene->gm.framing.col[2], 1.0f);
435                                         glViewport(ar->winrct.xmin, ar->winrct.ymin, ar->winrct.xmax, ar->winrct.ymax);
436                                         glClear(GL_COLOR_BUFFER_BIT);
437                                         
438                                         // kick the engine
439                                         bool render = ketsjiengine->NextFrame();
440                                         
441                                         if (render)
442                                         {
443                                                 // render the frame
444                                                 ketsjiengine->Render();
445                                         }
446                                         
447                                         wm_window_process_events_nosleep();
448                                         
449                                         // test for the ESC key
450                                         //XXX while (qtest())
451                                         while(wmEvent *event= (wmEvent *)win->queue.first)
452                                         {
453                                                 short val = 0;
454                                                 //unsigned short event = 0; //XXX extern_qread(&val);
455                                                 
456                                                 if (keyboarddevice->ConvertBlenderEvent(event->type,event->val))
457                                                         exitrequested = KX_EXIT_REQUEST_BLENDER_ESC;
458                                                 
459                                                         /* Coordinate conversion... where
460                                                         * should this really be?
461                                                 */
462                                                 if (event->type==MOUSEMOVE) {
463                                                         /* Note, not nice! XXX 2.5 event hack */
464                                                         val = event->x - ar->winrct.xmin;
465                                                         mousedevice->ConvertBlenderEvent(MOUSEX, val);
466                                                         
467                                                         val = ar->winy - (event->y - ar->winrct.ymin) - 1;
468                                                         mousedevice->ConvertBlenderEvent(MOUSEY, val);
469                                                 }
470                                                 else {
471                                                         mousedevice->ConvertBlenderEvent(event->type,event->val);
472                                                 }
473                                                 
474                                                 BLI_remlink(&win->queue, event);
475                                                 wm_event_free(event);
476                                         }
477                                         
478                                         if(win != CTX_wm_window(C)) {
479                                                 exitrequested= KX_EXIT_REQUEST_OUTSIDE; /* window closed while bge runs */
480                                         }
481                                 }
482                                 printf("Blender Game Engine Finished\n");
483                                 exitstring = ketsjiengine->GetExitString();
484
485
486                                 // when exiting the mainloop
487 #ifdef WITH_PYTHON
488                                 // Clears the dictionary by hand:
489                                 // This prevents, extra references to global variables
490                                 // inside the GameLogic dictionary when the python interpreter is finalized.
491                                 // which allows the scene to safely delete them :)
492                                 // see: (space.c)->start_game
493                                 
494                                 //PyDict_Clear(PyModule_GetDict(gameLogic));
495                                 
496                                 // Keep original items, means python plugins will autocomplete members
497                                 int listIndex;
498                                 PyObject *gameLogic_keys_new = PyDict_Keys(PyModule_GetDict(gameLogic));
499                                 for (listIndex=0; listIndex < PyList_Size(gameLogic_keys_new); listIndex++)  {
500                                         PyObject* item = PyList_GET_ITEM(gameLogic_keys_new, listIndex);
501                                         if (!PySequence_Contains(gameLogic_keys, item)) {
502                                                 PyDict_DelItem( PyModule_GetDict(gameLogic), item);
503                                         }
504                                 }
505                                 Py_DECREF(gameLogic_keys_new);
506                                 gameLogic_keys_new = NULL;
507 #endif
508                                 ketsjiengine->StopEngine();
509 #ifdef WITH_PYTHON
510                                 exitGamePythonScripting();
511 #endif
512                                 networkdevice->Disconnect();
513                         }
514                         if (sceneconverter)
515                         {
516                                 delete sceneconverter;
517                                 sceneconverter = NULL;
518                         }
519
520 #ifdef WITH_PYTHON
521                         Py_DECREF(gameLogic_keys);
522                         gameLogic_keys = NULL;
523 #endif
524                 }
525                 //lock frame and camera enabled - restoring global values
526                 if (v3d->scenelock==0){
527                         startscene->lay= tmp_lay;
528                         startscene->camera= tmp_camera;
529                 }
530
531                 if(exitrequested != KX_EXIT_REQUEST_OUTSIDE)
532                 {
533                         // set the cursor back to normal
534                         canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
535                 }
536                 
537                 // clean up some stuff
538                 if (ketsjiengine)
539                 {
540                         delete ketsjiengine;
541                         ketsjiengine = NULL;
542                 }
543                 if (kxsystem)
544                 {
545                         delete kxsystem;
546                         kxsystem = NULL;
547                 }
548                 if (networkdevice)
549                 {
550                         delete networkdevice;
551                         networkdevice = NULL;
552                 }
553                 if (keyboarddevice)
554                 {
555                         delete keyboarddevice;
556                         keyboarddevice = NULL;
557                 }
558                 if (mousedevice)
559                 {
560                         delete mousedevice;
561                         mousedevice = NULL;
562                 }
563                 if (rasterizer)
564                 {
565                         delete rasterizer;
566                         rasterizer = NULL;
567                 }
568                 if (rendertools)
569                 {
570                         delete rendertools;
571                         rendertools = NULL;
572                 }
573                 if (canvas)
574                 {
575                         delete canvas;
576                         canvas = NULL;
577                 }
578         
579         } while (exitrequested == KX_EXIT_REQUEST_RESTART_GAME || exitrequested == KX_EXIT_REQUEST_START_OTHER_GAME);
580         
581         if (!disableVBO)
582                 U.gameflags &= ~USER_DISABLE_VBO;
583
584         if (bfd) BLO_blendfiledata_free(bfd);
585
586         BLI_strncpy(G.main->name, oldsce, sizeof(G.main->name));
587
588 #ifdef WITH_PYTHON
589         Py_DECREF(pyGlobalDict);
590
591         // Release Python's GIL
592         PyGILState_Release(gilstate);
593 #endif
594
595 }