0ea3a3e62ebd6f30276893002da8d6b536005e96
[blender.git] / source / gameengine / GamePlayer / ghost / GPG_ghost.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  * Start up of the Blender Player on GHOST.
27  */
28
29 /** \file gameengine/GamePlayer/ghost/GPG_ghost.cpp
30  *  \ingroup player
31  */
32
33
34 #include <iostream>
35 #include <math.h>
36
37 #ifdef __linux__
38 #ifdef __alpha__
39 #include <signal.h>
40 #endif /* __alpha__ */
41 #endif /* __linux__ */
42
43 #include "KX_KetsjiEngine.h"
44 #include "KX_PythonInit.h"
45 #include "KX_PythonMain.h"
46 #include "KX_PyConstraintBinding.h" // for PHY_SetActiveEnvironment
47
48 /**********************************
49 * Begin Blender include block
50 **********************************/
51 #ifdef __cplusplus
52 extern "C"
53 {
54 #endif  // __cplusplus
55 #include "MEM_guardedalloc.h"
56 #include "MEM_CacheLimiterC-Api.h"
57
58 #include "BLI_threads.h"
59 #include "BLI_mempool.h"
60 #include "BLI_blenlib.h"
61
62 #include "DNA_scene_types.h"
63 #include "DNA_userdef_types.h"
64
65 #include "BLO_readfile.h"
66 #include "BLO_runtime.h"
67
68 #include "BKE_appdir.h"
69 #include "BKE_blender.h"
70 #include "BKE_depsgraph.h"
71 #include "BKE_global.h"
72 #include "BKE_icons.h"
73 #include "BKE_image.h"
74 #include "BKE_node.h"
75 #include "BKE_report.h"
76 #include "BKE_library.h"
77 #include "BKE_library_remap.h"
78 #include "BKE_modifier.h"
79 #include "BKE_material.h"
80 #include "BKE_text.h"
81 #include "BKE_sound.h"
82
83 #include "IMB_imbuf.h"
84 #include "IMB_moviecache.h"
85         
86 #ifdef __APPLE__
87         int GHOST_HACK_getFirstFile(char buf[]);
88 #endif
89         
90 // For BLF
91 #include "BLF_api.h"
92 #include "BLT_translation.h"
93 #include "BLT_lang.h"
94 extern int datatoc_bfont_ttf_size;
95 extern char datatoc_bfont_ttf[];
96 extern int datatoc_bmonofont_ttf_size;
97 extern char datatoc_bmonofont_ttf[];
98
99 #ifdef __cplusplus
100 }
101 #endif // __cplusplus
102
103 #include "GPU_draw.h"
104
105 /**********************************
106 * End Blender include block
107 **********************************/
108
109 #include "BL_System.h"
110 #include "GPG_Application.h"
111
112 #include "GHOST_ISystem.h"
113 #include "RAS_IRasterizer.h"
114
115 #include "BKE_main.h"
116
117 #include "RNA_define.h"
118
119 #ifdef WIN32
120 #  include <windows.h>
121 #  if !defined(DEBUG)
122 #    include <wincon.h>
123 #  endif // !defined(DEBUG)
124 #  if defined(_MSC_VER) && defined(_M_X64)
125 #    include <math.h> /* needed for _set_FMA3_enable */
126 #  endif
127 #  include "utfconv.h"
128 #endif // WIN32
129
130 #ifdef WITH_SDL_DYNLOAD
131 #  include "sdlew.h"
132 #endif
133
134 const int kMinWindowWidth = 100;
135 const int kMinWindowHeight = 100;
136
137 static void mem_error_cb(const char *errorStr)
138 {
139         fprintf(stderr, "%s", errorStr);
140         fflush(stderr);
141 }
142
143 // library.c will only free window managers with a callback function.
144 // We don't actually use a wmWindowManager, but loading a blendfile
145 // loads wmWindows, so we need to free those.
146 static void wm_free(bContext *C, wmWindowManager *wm)
147 {
148         BLI_freelistN(&wm->windows);
149 }
150
151 #ifdef WIN32
152 typedef enum {
153         SCREEN_SAVER_MODE_NONE = 0,
154         SCREEN_SAVER_MODE_PREVIEW,
155         SCREEN_SAVER_MODE_SAVER,
156         SCREEN_SAVER_MODE_CONFIGURATION,
157         SCREEN_SAVER_MODE_PASSWORD,
158 } ScreenSaverMode;
159
160 static ScreenSaverMode scr_saver_mode = SCREEN_SAVER_MODE_NONE;
161 static HWND scr_saver_hwnd = NULL;
162
163 static BOOL scr_saver_init(int argc, char **argv) 
164 {
165         scr_saver_mode = SCREEN_SAVER_MODE_NONE;
166         scr_saver_hwnd = NULL;
167         BOOL ret = false;
168
169         int len = ::strlen(argv[0]);
170         if (len > 4 && !::stricmp(".scr", argv[0] + len - 4))
171         {
172                 scr_saver_mode = SCREEN_SAVER_MODE_CONFIGURATION;
173                 ret = true;
174                 if (argc >= 2)
175                 {
176                         if (argc >= 3)
177                         {
178                                 scr_saver_hwnd = (HWND) ::atoi(argv[2]);
179                         }
180                         if (!::stricmp("/c", argv[1]))
181                         {
182                                 scr_saver_mode = SCREEN_SAVER_MODE_CONFIGURATION;
183                                 if (scr_saver_hwnd == NULL)
184                                         scr_saver_hwnd = ::GetForegroundWindow();
185                         }
186                         else if (!::stricmp("/s", argv[1]))
187                         {
188                                 scr_saver_mode = SCREEN_SAVER_MODE_SAVER;
189                         }
190                         else if (!::stricmp("/a", argv[1]))
191                         {
192                                 scr_saver_mode = SCREEN_SAVER_MODE_PASSWORD;
193                         }
194                         else if (!::stricmp("/p", argv[1])
195                                  || !::stricmp("/l", argv[1]))
196                         {
197                                 scr_saver_mode = SCREEN_SAVER_MODE_PREVIEW;
198                         }
199                 }
200         }
201         return ret;
202 }
203
204 #endif /* WIN32 */
205
206 static void usage(const char* program, bool isBlenderPlayer)
207 {
208         const char * consoleoption;
209         const char * example_filename = "";
210         const char * example_pathname = "";
211
212 #ifdef _WIN32
213         consoleoption = "[-c] ";
214 #else
215         consoleoption = "";
216 #endif
217
218         if (isBlenderPlayer) {
219                 example_filename = "filename.blend";
220 #ifdef _WIN32
221                 example_pathname = "c:\\";
222 #else
223                 example_pathname = "/home/user/";
224 #endif
225         }
226         printf("\n");
227         printf("usage:   %s [--options] %s\n\n", program, example_filename);
228         printf("Available options are: [-w [w h l t]] [-f [fw fh fb ff]] %s[-g gamengineoptions] ", consoleoption);
229         printf("[-s stereomode] [-m aasamples]\n");
230         printf("Optional parameters must be passed in order.\n");
231         printf("Default values are set in the blend file.\n\n");
232         printf("  -h: Prints this command summary\n\n");
233         printf("  -w: display in a window\n");
234         printf("       --Optional parameters--\n"); 
235         printf("       w = window width\n");
236         printf("       h = window height\n");
237         printf("       l = window left coordinate\n");
238         printf("       t = window top coordinate\n");
239         printf("       Note: To define 'w' or 'h', both must be used.");
240         printf("Also, to define 'l' or 't', all four parameters must be used.\n");
241         printf("       Example: -w   or  -w 500 300  or  -w 500 300 0 0\n\n");
242         printf("  -f: start game in fullscreen mode\n");
243         printf("       --Optional parameters--\n");
244         printf("       fw = fullscreen mode pixel width    (use 0 to detect automatically)\n");
245         printf("       fh = fullscreen mode pixel height   (use 0 to detect automatically)\n");
246         printf("       fb = fullscreen mode bits per pixel (default unless set in the blend file: 32)\n");
247         printf("       ff = fullscreen mode frequency      (default unless set in the blend file: 60)\n");
248         printf("       Note: To define 'fw'' or 'fh'', both must be used.\n");
249         printf("       Example: -f  or  -f 1024 768  or  -f 0 0 16  or  -f 1024 728 16 30\n\n");
250         printf("  -s: start player in stereoscopy mode (requires 3D capable hardware)\n");
251         printf("       stereomode: nostereo         (default unless stereo is set in the blend file)\n");
252         printf("                   anaglyph         (Red-Blue glasses)\n");
253         printf("                   sidebyside       (Left Right)\n");
254         printf("                   syncdoubling     (Above Below)\n");
255         printf("                   3dtvtopbottom    (Squashed Top-Bottom for passive glasses)\n");
256         printf("                   interlace        (Interlace horizontally)\n");
257         printf("                   vinterlace       (Vertical interlace for autostereo display)\n");
258         printf("                   hwpageflip       (Quad buffered shutter glasses)\n");
259         printf("       Example: -s sidebyside  or  -s vinterlace\n\n");
260         printf("  -D: start player in dome mode\n");
261         printf("       --Optional parameters--\n");
262         printf("       angle    = field of view in degrees\n");
263         printf("       tilt     = tilt angle in degrees\n");
264         printf("       warpdata = a file to use for warping the image (absolute path)\n");
265         printf("       mode: fisheye                (Fisheye)\n");
266         printf("             truncatedfront         (Front-Truncated)\n");
267         printf("             truncatedrear          (Rear-Truncated)\n");
268         printf("             cubemap                (Cube Map)\n");
269         printf("             sphericalpanoramic     (Spherical Panoramic)\n");
270         printf("       Example: -D  or  -D mode cubemap\n\n");
271         printf("  -m: maximum anti-aliasing (eg. 2,4,8,16)\n\n");
272         printf("  -i: parent window's ID\n\n");
273 #ifdef _WIN32
274         printf("  -c: keep console window open\n\n");
275 #endif
276         printf("  -d: turn debugging on\n\n");
277         printf("  -g: game engine options:\n\n");
278         printf("       Name                       Default      Description\n");
279         printf("       ------------------------------------------------------------------------\n");
280         printf("       fixedtime                      0         \"Enable all frames\"\n");
281         printf("       nomipmap                       0         Disable mipmaps\n");
282         printf("       show_framerate                 0         Show the frame rate\n");
283         printf("       show_properties                0         Show debug properties\n");
284         printf("       show_profile                   0         Show profiling information\n");
285         printf("       blender_material               0         Enable material settings\n");
286         printf("       ignore_deprecation_warnings    1         Ignore deprecation warnings\n");
287         printf("\n");
288         printf("  - : all arguments after this are ignored, allowing python to access them from sys.argv\n");
289         printf("\n");
290         printf("example: %s -w 320 200 10 10 -g noaudio %s%s\n", program, example_pathname, example_filename);
291         printf("example: %s -g show_framerate = 0 %s%s\n", program, example_pathname, example_filename);
292         printf("example: %s -i 232421 -m 16 %s%s\n\n", program, example_pathname, example_filename);
293 }
294
295 static void get_filename(int argc, char **argv, char *filename)
296 {
297 #ifdef __APPLE__
298         /* On Mac we park the game file (called game.blend) in the application bundle.
299          * The executable is located in the bundle as well.
300          * Therefore, we can locate the game relative to the executable.
301          */
302         int srclen = ::strlen(argv[0]);
303         int len = 0;
304         char *gamefile = NULL;
305         
306         filename[0] = '\0';
307
308         if (argc > 1) {
309                 if (BLI_exists(argv[argc-1])) {
310                         BLI_strncpy(filename, argv[argc-1], FILE_MAX);
311                 }
312                 if (::strncmp(argv[argc-1], "-psn_", 5)==0) {
313                         static char firstfilebuf[512];
314                         if (GHOST_HACK_getFirstFile(firstfilebuf)) {
315                                 BLI_strncpy(filename, firstfilebuf, FILE_MAX);
316                         }
317                 }
318         }
319         
320         srclen -= ::strlen("MacOS/blenderplayer");
321         if (srclen > 0) {
322                 len = srclen + ::strlen("Resources/game.blend"); 
323                 gamefile = new char [len + 1];
324                 ::strcpy(gamefile, argv[0]);
325                 ::strcpy(gamefile + srclen, "Resources/game.blend");
326                 //::printf("looking for file: %s\n", filename);
327                 
328                 if (BLI_exists(gamefile))
329                         BLI_strncpy(filename, gamefile, FILE_MAX);
330
331                 delete [] gamefile;
332         }
333         
334 #else
335         filename[0] = '\0';
336
337         if (argc > 1)
338                 BLI_strncpy(filename, argv[argc-1], FILE_MAX);
339 #endif // !_APPLE
340 }
341
342 static BlendFileData *load_game_data(const char *progname, char *filename = NULL, char *relativename = NULL)
343 {
344         ReportList reports;
345         BlendFileData *bfd = NULL;
346
347         BKE_reports_init(&reports, RPT_STORE);
348         
349         /* try to load ourself, will only work if we are a runtime */
350         if (BLO_is_a_runtime(progname)) {
351                 bfd= BLO_read_runtime(progname, &reports);
352                 if (bfd) {
353                         bfd->type= BLENFILETYPE_RUNTIME;
354                         BLI_strncpy(bfd->main->name, progname, sizeof(bfd->main->name));
355                 }
356         } else {
357                 bfd= BLO_read_from_file(progname, &reports);
358         }
359         
360         if (!bfd && filename) {
361                 bfd = load_game_data(filename);
362                 if (!bfd) {
363                         printf("Loading %s failed: ", filename);
364                         BKE_reports_print(&reports, RPT_ERROR);
365                 }
366         }
367
368         BKE_reports_clear(&reports);
369         
370         return bfd;
371 }
372
373 static bool GPG_NextFrame(GHOST_ISystem* system, GPG_Application *app, int &exitcode, STR_String &exitstring, GlobalSettings *gs)
374 {
375         bool run = true;
376         system->processEvents(false);
377         system->dispatchEvents();
378         app->EngineNextFrame();
379         if ((exitcode = app->getExitRequested())) {
380                 run = false;
381                 exitstring = app->getExitString();
382                 *gs = *app->getGlobalSettings();
383         }
384         return run;
385 }
386
387 struct GPG_NextFrameState {
388         GHOST_ISystem* system;
389         GPG_Application *app;
390         GlobalSettings *gs;
391 } gpg_nextframestate;
392
393 static int GPG_PyNextFrame(void *state0)
394 {
395         GPG_NextFrameState *state = (GPG_NextFrameState *) state0;
396         int exitcode;
397         STR_String exitstring;
398         bool run = GPG_NextFrame(state->system, state->app, exitcode, exitstring, state->gs);
399         if (run) return 0;  
400         else {
401                 if (exitcode) 
402                         fprintf(stderr, "Exit code %d: %s\n", exitcode, exitstring.ReadPtr());
403                 return 1;
404         }
405 }
406
407 int main(
408         int argc,
409 #ifdef WIN32
410         char **UNUSED(argv_c)
411 #else
412         char **argv
413 #endif
414         )
415 {
416         int i;
417         int argc_py_clamped= argc; /* use this so python args can be added after ' - ' */
418         bool error = false;
419         SYS_SystemHandle syshandle = SYS_GetSystem();
420         bool fullScreen = false;
421         bool fullScreenParFound = false;
422         bool windowParFound = false;
423 #ifdef WIN32
424         bool closeConsole = true;
425 #endif
426         RAS_IRasterizer::StereoMode stereomode = RAS_IRasterizer::RAS_STEREO_NOSTEREO;
427         bool stereoWindow = false;
428         bool stereoParFound = false;
429         int stereoFlag = STEREO_NOSTEREO;
430         int domeFov = -1;
431         int domeTilt = -200;
432         int domeMode = 0;
433         char* domeWarp = NULL;
434         Text *domeText  = NULL;
435         int windowLeft = 100;
436         int windowTop = 100;
437         int windowWidth = 640;
438         int windowHeight = 480;
439         GHOST_TUns32 fullScreenWidth = 0;
440         GHOST_TUns32 fullScreenHeight= 0;
441         int fullScreenBpp = 32;
442         int fullScreenFrequency = 60;
443         GHOST_TEmbedderWindowID parentWindow = 0;
444         bool isBlenderPlayer = false; //true when lauching from blender or command line. false for bundled player
445         int validArguments=0;
446         bool samplesParFound = false;
447         GHOST_TUns16 aasamples = 0;
448         int alphaBackground = 0;
449         
450 #ifdef WIN32
451         char **argv;
452         int argv_num;
453
454         /* We delay loading of openmp so we can set the policy here. */
455 # if defined(_MSC_VER)
456         _putenv_s("OMP_WAIT_POLICY", "PASSIVE");
457 # endif
458
459         /* FMA3 support in the 2013 CRT is broken on Vista and Windows 7 RTM (fixed in SP1). Just disable it. */
460 #  if defined(_MSC_VER) && defined(_M_X64)
461         _set_FMA3_enable(0);
462 #  endif
463
464         /* Win32 Unicode Args */
465         /* NOTE: cannot use guardedalloc malloc here, as it's not yet initialized
466         *       (it depends on the args passed in, which is what we're getting here!)
467         */
468         {
469                 wchar_t **argv_16 = CommandLineToArgvW(GetCommandLineW(), &argc);
470                 argv = (char**)malloc(argc * sizeof(char *));
471                 for (argv_num = 0; argv_num < argc; argv_num++) {
472                         argv[argv_num] = alloc_utf_8_from_16(argv_16[argv_num], 0);
473                 }
474                 LocalFree(argv_16);
475         }
476 #endif  /* WIN32 */
477
478 #ifdef __linux__
479 #ifdef __alpha__
480         signal (SIGFPE, SIG_IGN);
481 #endif /* __alpha__ */
482 #endif /* __linux__ */
483
484 #ifdef WITH_SDL_DYNLOAD
485         sdlewInit();
486 #endif
487
488         BKE_appdir_program_path_init(argv[0]);
489         BKE_tempdir_init(NULL);
490         
491         // We don't use threads directly in the BGE, but we need to call this so things like
492         // freeing up GPU_Textures works correctly.
493         BLI_threadapi_init();
494
495         RNA_init();
496
497         init_nodesystem();
498         
499         BKE_blender_globals_init();
500
501         // We load our own G.main, so free the one that BKE_blender_globals_init() gives us
502         BKE_main_free(G.main);
503         G.main = NULL;
504
505         MEM_CacheLimiter_set_disabled(true);
506         IMB_init();
507         BKE_images_init();
508         BKE_modifier_init();
509         DAG_init();
510
511 #ifdef WITH_FFMPEG
512         IMB_ffmpeg_init();
513 #endif
514
515         // Setup builtin font for BLF (mostly copied from creator.c, wm_init_exit.c and interface_style.c)
516         BLF_init(11, U.dpi);
517         BLT_lang_init();
518         BLT_lang_set("");
519
520         BLF_load_mem("default", (unsigned char*)datatoc_bfont_ttf, datatoc_bfont_ttf_size);
521         if (blf_mono_font == -1)
522                 blf_mono_font = BLF_load_mem_unique("monospace", (unsigned char*)datatoc_bmonofont_ttf, datatoc_bmonofont_ttf_size);
523
524         // Parse command line options
525 #if defined(DEBUG)
526         printf("argv[0] = '%s'\n", argv[0]);
527 #endif
528
529 #ifdef WIN32
530         if (scr_saver_init(argc, argv))
531         {
532                 switch (scr_saver_mode)
533                 {
534                 case SCREEN_SAVER_MODE_CONFIGURATION:
535                         MessageBox(scr_saver_hwnd, "This screen saver has no options that you can set", "Screen Saver", MB_OK);
536                         break;
537                 case SCREEN_SAVER_MODE_PASSWORD:
538                         /* This is W95 only, which we currently do not support.
539                          * Fall-back to normal screen saver behavior in that case... */
540                 case SCREEN_SAVER_MODE_SAVER:
541                         fullScreen = true;
542                         fullScreenParFound = true;
543                         break;
544
545                 case SCREEN_SAVER_MODE_PREVIEW:
546                         /* This will actually be handled somewhere below... */
547                         break;
548                 }
549         }
550 #endif
551         // XXX add the ability to change this values to the command line parsing.
552         U.mixbufsize = 2048;
553         U.audiodevice = 2;
554         U.audiorate = 44100;
555         U.audioformat = 0x24;
556         U.audiochannels = 2;
557
558         // XXX this one too
559         U.anisotropic_filter = 2;
560         // enable fast mipmap generation
561         U.use_gpu_mipmap = 1;
562
563         BKE_sound_init_once();
564
565         // Initialize a default material for meshes without materials.
566         init_def_material();
567
568         BKE_library_callback_free_window_manager_set(wm_free);
569
570         /* if running blenderplayer the last argument can't be parsed since it has to be the filename. else it is bundled */
571         isBlenderPlayer = !BLO_is_a_runtime(argv[0]);
572         if (isBlenderPlayer)
573                 validArguments = argc - 1;
574         else
575                 validArguments = argc;
576
577
578         /* Parsing command line arguments (can be set from WM_OT_blenderplayer_start) */
579 #if defined(DEBUG)
580                 printf("Parsing command line arguments...\n");
581                 printf("Num of arguments is: %i\n", validArguments-1); //-1 because i starts at 1
582 #endif
583
584         for (i = 1; (i < validArguments) && !error 
585 #ifdef WIN32
586                 && scr_saver_mode == SCREEN_SAVER_MODE_NONE
587 #endif
588                 ;)
589
590         {
591 #if defined(DEBUG)
592                 printf("argv[%d] = '%s'\n", i, argv[i]);
593 #endif
594                 if (argv[i][0] == '-')
595                 {
596                         /* ignore all args after " - ", allow python to have own args */
597                         if (argv[i][1]=='\0') {
598                                 argc_py_clamped= i;
599                                 break;
600                         }
601                         
602                         switch (argv[i][1])
603                         {
604                         case 'g': //game engine options (show_framerate, fixedtime, etc)
605                         {
606                                 i++;
607                                 if (i <= validArguments)
608                                 {
609                                         char* paramname = argv[i];
610                                         // Check for single value versus assignment
611                                         if (i+1 <= validArguments && (*(argv[i+1]) == '='))
612                                         {
613                                                 i++;
614                                                 if (i + 1 <= validArguments)
615                                                 {
616                                                         i++;
617                                                         // Assignment
618                                                         SYS_WriteCommandLineInt(syshandle, paramname, atoi(argv[i]));
619                                                         SYS_WriteCommandLineFloat(syshandle, paramname, atof(argv[i]));
620                                                         SYS_WriteCommandLineString(syshandle, paramname, argv[i]);
621 #if defined(DEBUG)
622                                                         printf("%s = '%s'\n", paramname, argv[i]);
623 #endif
624                                                         i++;
625                                                 }
626                                                 else
627                                                 {
628                                                         error = true;
629                                                         printf("error: argument assignment %s without value.\n", paramname);
630                                                 }
631                                         }
632                                         else
633                                         {
634 //                                              SYS_WriteCommandLineInt(syshandle, argv[i++], 1);
635                                         }
636                                 }
637                                 break;
638                         }
639                         case 'd': //debug on
640                         {
641                                 i++;
642                                 G.debug |= G_DEBUG;
643                                 MEM_set_memory_debug();
644 #ifndef NDEBUG
645                                 BLI_mempool_set_memory_debug();
646 #endif
647                                 break;
648                         }
649                         case 'f': //fullscreen mode
650                         {
651                                 i++;
652                                 fullScreen = true;
653                                 fullScreenParFound = true;
654                                 if ((i + 2) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-')
655                                 {
656                                         fullScreenWidth = atoi(argv[i++]);
657                                         fullScreenHeight = atoi(argv[i++]);
658                                         if ((i + 1) <= validArguments && argv[i][0] != '-')
659                                         {
660                                                 fullScreenBpp = atoi(argv[i++]);
661                                                 if ((i + 1) <= validArguments && argv[i][0] != '-')
662                                                         fullScreenFrequency = atoi(argv[i++]);
663                                         }
664                                 }
665                                 else if ((i + 1) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-')
666                                 {
667                                         error = true;
668                                         printf("error: to define fullscreen width or height, both options must be used.\n");
669                                 }
670                                 break;
671                         }
672                         case 'w': //display in a window
673                         {
674                                 i++;
675                                 fullScreen = false;
676                                 windowParFound = true;
677
678                                 // Parse window position and size options
679                                 if ((i + 2) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-')
680                                 {
681                                         windowWidth = atoi(argv[i++]);
682                                         windowHeight = atoi(argv[i++]);
683
684                                         if ((i + 2) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-')
685                                         {
686                                                 windowLeft = atoi(argv[i++]);
687                                                 windowTop = atoi(argv[i++]);
688                                         }
689                                         else if ((i + 1) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-')
690                                         {
691                                                 error = true;
692                                                 printf("error: to define the window left or right coordinates, both options must be used.\n");
693                                         }
694                                 }
695                                 else if ((i + 1) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-')
696                                 {
697                                         error = true;
698                                         printf("error: to define the window's width or height, both options must be used.\n");
699                                 }
700                                 break;
701                         }
702                         case 'h': //display help
703                         {
704                                 usage(argv[0], isBlenderPlayer);
705                                 return 0;
706                                 break;
707                         }
708                         case 'i': //parent window ID
709                         {
710                                 i++;
711                                 if ( (i + 1) <= validArguments )
712                                         parentWindow = atoi(argv[i++]);
713                                 else {
714                                         error = true;
715                                         printf("error: too few options for parent window argument.\n");
716                                 }
717 #if defined(DEBUG)
718                                 printf("XWindows ID = %d\n", parentWindow);
719 #endif // defined(DEBUG)
720                                 break;
721                         }
722                         case 'm': //maximum anti-aliasing (eg. 2,4,8,16)
723                         {
724                                 i++;
725                                 samplesParFound = true;
726                                 if ((i+1) <= validArguments )
727                                         aasamples = atoi(argv[i++]);
728                                 else
729                                 {
730                                         error = true;
731                                         printf("error: No argument supplied for -m");
732                                 }
733                                 break;
734                         }
735                         case 'c': //keep console (windows only)
736                         {
737                                 i++;
738 #ifdef WIN32
739                                 closeConsole = false;
740 #endif
741                                 break;
742                         }
743                         case 's': //stereo mode
744                         {
745                                 i++;
746                                 if ((i + 1) <= validArguments)
747                                 {
748                                         stereoParFound = true;
749                                         stereoFlag = STEREO_ENABLED;
750
751                                         if (!strcmp(argv[i], "nostereo"))  // may not be redundant if the file has different setting
752                                         {
753                                                 stereomode = RAS_IRasterizer::RAS_STEREO_NOSTEREO;
754                                                 stereoFlag = STEREO_NOSTEREO;
755                                         }
756
757                                         // only the hardware pageflip method needs a stereo window
758                                         else if (!strcmp(argv[i], "hwpageflip")) {
759                                                 stereomode = RAS_IRasterizer::RAS_STEREO_QUADBUFFERED;
760                                                 stereoWindow = true;
761                                         }
762                                         else if (!strcmp(argv[i], "syncdoubling"))
763                                                 stereomode = RAS_IRasterizer::RAS_STEREO_ABOVEBELOW;
764
765                                         else if (!strcmp(argv[i], "3dtvtopbottom"))
766                                                 stereomode = RAS_IRasterizer::RAS_STEREO_3DTVTOPBOTTOM;
767
768                                         else if (!strcmp(argv[i], "anaglyph"))
769                                                 stereomode = RAS_IRasterizer::RAS_STEREO_ANAGLYPH;
770
771                                         else if (!strcmp(argv[i], "sidebyside"))
772                                                 stereomode = RAS_IRasterizer::RAS_STEREO_SIDEBYSIDE;
773
774                                         else if (!strcmp(argv[i], "interlace"))
775                                                 stereomode = RAS_IRasterizer::RAS_STEREO_INTERLACED;
776
777                                         else if (!strcmp(argv[i], "vinterlace"))
778                                                 stereomode = RAS_IRasterizer::RAS_STEREO_VINTERLACE;
779
780 #if 0
781 //                                      // future stuff
782 //                                      else if (!strcmp(argv[i], "stencil")
783 //                                              stereomode = RAS_STEREO_STENCIL;
784 #endif
785                                         else
786                                         {
787                                                 error = true;
788                                                 printf("error: stereomode '%s' unrecognized.\n", argv[i]);
789                                         }
790
791                                         i++;
792                                 }
793                                 else
794                                 {
795                                         error = true;
796                                         printf("error: too few options for stereo argument.\n");
797                                 }
798                                 break;
799                         }
800                         case 'D': //dome mode
801                         {
802                                 stereoFlag = STEREO_DOME;
803                                 stereomode = RAS_IRasterizer::RAS_STEREO_DOME;
804                                 i++;
805                                 if ((i + 1) <= validArguments)
806                                 {
807                                         if (!strcmp(argv[i], "angle")) {
808                                                 i++;
809                                                 domeFov = atoi(argv[i++]);
810                                         }
811                                         if (!strcmp(argv[i], "tilt")) {
812                                                 i++;
813                                                 domeTilt = atoi(argv[i++]);
814                                         }
815                                         if (!strcmp(argv[i], "warpdata")) {
816                                                 i++;
817                                                 domeWarp = argv[i++];
818                                         }
819                                         if (!strcmp(argv[i], "mode")) {
820                                                 i++;
821                                                 if (!strcmp(argv[i], "fisheye"))
822                                                         domeMode = DOME_FISHEYE;
823                                                         
824                                                 else if (!strcmp(argv[i], "truncatedfront"))
825                                                         domeMode = DOME_TRUNCATED_FRONT;
826                                                         
827                                                 else if (!strcmp(argv[i], "truncatedrear"))
828                                                         domeMode = DOME_TRUNCATED_REAR;
829                                                         
830                                                 else if (!strcmp(argv[i], "cubemap"))
831                                                         domeMode = DOME_ENVMAP;
832                                                         
833                                                 else if (!strcmp(argv[i], "sphericalpanoramic"))
834                                                         domeMode = DOME_PANORAM_SPH;
835
836                                                 else
837                                                         printf("error: %s is not a valid dome mode.\n", argv[i]);
838                                         }
839                                         i++;
840                                 }
841                                 break;
842                         }
843                         case 'a':   // allow window to blend with display background
844                         {
845                                 i++;
846                                 alphaBackground = 1;
847                                 break;
848                         }
849                         default:  //not recognized
850                         {
851                                 printf("Unknown argument: %s\n", argv[i++]);
852                                 break;
853                         }
854                         }
855                 }
856                 else
857                 {
858                         i++;
859                 }
860         }
861
862         if ((windowWidth < kMinWindowWidth) || (windowHeight < kMinWindowHeight))
863         {
864                 error = true;
865                 printf("error: window size too small.\n");
866         }
867         
868         if (error )
869         {
870                 usage(argv[0], isBlenderPlayer);
871                 return 0;
872         }
873
874 #ifdef WIN32
875         if (scr_saver_mode != SCREEN_SAVER_MODE_CONFIGURATION)
876 #endif
877         {
878                 // Create the system
879                 if (GHOST_ISystem::createSystem() == GHOST_kSuccess) {
880                         GHOST_ISystem* system = GHOST_ISystem::getSystem();
881                         assertd(system);
882                         
883                         if (!fullScreenWidth || !fullScreenHeight)
884                                 system->getMainDisplayDimensions(fullScreenWidth, fullScreenHeight);
885                         // process first batch of events. If the user
886                         // drops a file on top off the blenderplayer icon, we
887                         // receive an event with the filename
888                         
889                         system->processEvents(0);
890                         
891                         // this bracket is needed for app (see below) to get out
892                         // of scope before GHOST_ISystem::disposeSystem() is called.
893                         {
894                                 int exitcode = KX_EXIT_REQUEST_NO_REQUEST;
895                                 STR_String exitstring = "";
896                                 GPG_Application app(system);
897                                 bool firstTimeRunning = true;
898                                 char filename[FILE_MAX];
899                                 char pathname[FILE_MAX];
900                                 char *titlename;
901
902                                 get_filename(argc_py_clamped, argv, filename);
903                                 if (filename[0])
904                                         BLI_path_cwd(filename, sizeof(filename));
905                                 
906
907                                 // fill the GlobalSettings with the first scene files
908                                 // those may change during the game and persist after using Game Actuator
909                                 GlobalSettings gs;
910
911                                 do {
912                                         // Read the Blender file
913                                         BlendFileData *bfd;
914                                         
915                                         // if we got an exitcode 3 (KX_EXIT_REQUEST_START_OTHER_GAME) load a different file
916                                         if (exitcode == KX_EXIT_REQUEST_START_OTHER_GAME)
917                                         {
918                                                 char basedpath[FILE_MAX];
919                                                 
920                                                 // base the actuator filename relative to the last file
921                                                 BLI_strncpy(basedpath, exitstring.Ptr(), sizeof(basedpath));
922                                                 BLI_path_abs(basedpath, pathname);
923                                                 
924                                                 bfd = load_game_data(basedpath);
925
926                                                 if (!bfd) {
927                                                         // just add "//" in front of it
928                                                         char temppath[FILE_MAX] = "//";
929                                                         BLI_strncpy(temppath + 2, basedpath, FILE_MAX - 2);
930
931                                                         BLI_path_abs(temppath, pathname);
932                                                         bfd = load_game_data(temppath);
933                                                 }
934                                         }
935                                         else {
936                                                 bfd = load_game_data(BKE_appdir_program_path(), filename[0]? filename: NULL);
937                                         }
938
939 #if defined(DEBUG)
940                                         printf("Game data loaded from %s\n", filename);
941 #endif
942                                         
943                                         if (!bfd) {
944                                                 usage(argv[0], isBlenderPlayer);
945                                                 error = true;
946                                                 exitcode = KX_EXIT_REQUEST_QUIT_GAME;
947                                         }
948                                         else {
949                                                 /* Setting options according to the blend file if not overriden in the command line */
950 #ifdef WIN32
951 #if !defined(DEBUG)
952                                                 if (closeConsole) {
953                                                         system->toggleConsole(0); // Close a console window
954                                                 }
955 #endif // !defined(DEBUG)
956 #endif // WIN32
957                                                 Main *maggie = bfd->main;
958                                                 Scene *scene = bfd->curscene;
959                                                 G.main = maggie;
960
961                                                 if (firstTimeRunning) {
962                                                         G.fileflags  = bfd->fileflags;
963
964                                                         gs.matmode= scene->gm.matmode;
965                                                         gs.glslflag= scene->gm.flag;
966                                                 }
967
968                                                 //Seg Fault; icon.c gIcons == 0
969                                                 BKE_icons_init(1);
970                                                 
971                                                 titlename = maggie->name;
972                                                 
973                                                 // Check whether the game should be displayed full-screen
974                                                 if ((!fullScreenParFound) && (!windowParFound)) {
975                                                         // Only use file settings when command line did not override
976                                                         if ((scene->gm.playerflag & GAME_PLAYER_FULLSCREEN)) {
977                                                                 //printf("fullscreen option found in Blender file\n");
978                                                                 fullScreen = true;
979                                                                 fullScreenWidth= scene->gm.xplay;
980                                                                 fullScreenHeight= scene->gm.yplay;
981                                                                 fullScreenFrequency= scene->gm.freqplay;
982                                                                 fullScreenBpp = scene->gm.depth;
983                                                         }
984                                                         else
985                                                         {
986                                                                 fullScreen = false;
987                                                                 windowWidth = scene->gm.xplay;
988                                                                 windowHeight = scene->gm.yplay;
989                                                         }
990                                                 }
991                                                 
992                                                 
993                                                 // Check whether the game should be displayed in stereo (dome included)
994                                                 if (!stereoParFound) {
995                                                         // Only use file settings when command line did not override
996                                                         if (scene->gm.stereoflag == STEREO_ENABLED) {
997                                                                 stereomode = (RAS_IRasterizer::StereoMode) scene->gm.stereomode;
998                                                                 if (stereomode == RAS_IRasterizer::RAS_STEREO_QUADBUFFERED)
999                                                                         stereoWindow = true;
1000                                                         }
1001                                                 }
1002                                                 else {
1003                                                         scene->gm.stereoflag = STEREO_ENABLED;
1004                                                 }
1005
1006                                                 if (!samplesParFound)
1007                                                         aasamples = scene->gm.aasamples;
1008
1009                                                 // Dome specific settings
1010                                                 if (stereoFlag == STEREO_DOME) {
1011                                                         stereomode = RAS_IRasterizer::RAS_STEREO_DOME;
1012                                                         scene->gm.stereoflag = STEREO_DOME;
1013                                                         if (domeFov > 89)
1014                                                                 scene->gm.dome.angle = domeFov;
1015                                                         if (domeTilt > -180)
1016                                                                 scene->gm.dome.tilt = domeTilt;
1017                                                         if (domeMode > 0)
1018                                                                 scene->gm.dome.mode = domeMode;
1019                                                         if (domeWarp) {
1020                                                                 //XXX to do: convert relative to absolute path
1021                                                                 domeText= BKE_text_load(G.main, domeWarp, "");
1022                                                                 if (!domeText)
1023                                                                         printf("error: invalid warpdata text file - %s\n", domeWarp);
1024                                                                 else
1025                                                                         scene->gm.dome.warptext = domeText;
1026                                                         }
1027                                                 }
1028                                                 
1029                                                 //                                      GPG_Application app (system, maggie, startscenename);
1030                                                 app.SetGameEngineData(maggie, scene, &gs, argc, argv); /* this argc cant be argc_py_clamped, since python uses it */
1031                                                 BLI_strncpy(pathname, maggie->name, sizeof(pathname));
1032                                                 if (G.main != maggie) {
1033                                                         BLI_strncpy(G.main->name, maggie->name, sizeof(G.main->name));
1034                                                 }
1035 #ifdef WITH_PYTHON
1036                                                 setGamePythonPath(G.main->name);
1037 #endif
1038                                                 if (firstTimeRunning) {
1039                                                         firstTimeRunning = false;
1040
1041                                                         if (fullScreen) {
1042 #ifdef WIN32
1043                                                                 if (scr_saver_mode == SCREEN_SAVER_MODE_SAVER)
1044                                                                 {
1045                                                                         app.startScreenSaverFullScreen(fullScreenWidth, fullScreenHeight, fullScreenBpp, fullScreenFrequency,
1046                                                                                                        stereoWindow, stereomode, aasamples);
1047                                                                 }
1048                                                                 else
1049 #endif
1050                                                                 {
1051                                                                         app.startFullScreen(fullScreenWidth, fullScreenHeight, fullScreenBpp, fullScreenFrequency,
1052                                                                                             stereoWindow, stereomode, alphaBackground, aasamples, (scene->gm.playerflag & GAME_PLAYER_DESKTOP_RESOLUTION));
1053                                                                 }
1054                                                         }
1055                                                         else
1056                                                         {
1057 #ifdef __APPLE__
1058                                                                 // on Mac's we'll show the executable name instead of the 'game.blend' name
1059                                                                 char tempname[1024], *appstring;
1060                                                                 ::strcpy(tempname, titlename);
1061                                                                 
1062                                                                 appstring = strstr(tempname, ".app/");
1063                                                                 if (appstring) {
1064                                                                         appstring[2] = 0;
1065                                                                         titlename = &tempname[0];
1066                                                                 }
1067 #endif
1068                                                                 // Strip the path so that we have the name of the game file
1069                                                                 STR_String path = titlename;
1070 #ifndef WIN32
1071                                                                 vector<STR_String> parts = path.Explode('/');
1072 #else  // WIN32
1073                                                                 vector<STR_String> parts = path.Explode('\\');
1074 #endif // WIN32                        
1075                                                                 STR_String title;
1076                                                                 if (parts.size()) {
1077                                                                         title = parts[parts.size()-1];
1078                                                                         parts = title.Explode('.');
1079                                                                         if (parts.size() > 1)
1080                                                                         {
1081                                                                                 title = parts[0];
1082                                                                         }
1083                                                                 }
1084                                                                 else {
1085                                                                         title = "blenderplayer";
1086                                                                 }
1087 #ifdef WIN32
1088                                                                 if (scr_saver_mode == SCREEN_SAVER_MODE_PREVIEW)
1089                                                                 {
1090                                                                         app.startScreenSaverPreview(scr_saver_hwnd, stereoWindow, stereomode, aasamples);
1091                                                                 }
1092                                                                 else
1093 #endif
1094                                                                 {
1095                                                                         if (parentWindow != 0)
1096                                                                                 app.startEmbeddedWindow(title, parentWindow, stereoWindow, stereomode, aasamples);
1097                                                                         else
1098                                                                                 app.startWindow(title, windowLeft, windowTop, windowWidth, windowHeight,
1099                                                                                                 stereoWindow, stereomode, alphaBackground, aasamples);
1100
1101                                                                         if (SYS_GetCommandLineInt(syshandle, "nomipmap", 0)) {
1102                                                                                 GPU_set_mipmap(0);
1103                                                                         }
1104
1105                                                                         GPU_set_anisotropic(U.anisotropic_filter);
1106                                                                         GPU_set_gpu_mipmapping(U.use_gpu_mipmap);
1107                                                                 }
1108                                                         }
1109                                                 }
1110                                                 else {
1111                                                         app.StartGameEngine(stereomode);
1112                                                         exitcode = KX_EXIT_REQUEST_NO_REQUEST;
1113                                                 }
1114                                                 
1115                                                 // Add the application as event consumer
1116                                                 system->addEventConsumer(&app);
1117                                                 
1118                                                 // Enter main loop
1119                                                 bool run = true;
1120                                                 char *python_main = NULL;
1121                                                 pynextframestate.state = NULL;
1122                                                 pynextframestate.func = NULL;
1123 #ifdef WITH_PYTHON
1124                                                 python_main = KX_GetPythonMain(scene);
1125 #endif // WITH_PYTHON
1126                                                 if (python_main) {
1127                                                         char *python_code = KX_GetPythonCode(maggie, python_main);
1128                                                         if (python_code) {
1129 #ifdef WITH_PYTHON
1130                                                                 // Set python environement variable.
1131                                                                 KX_Scene *startscene = app.GetStartScene();
1132                                                                 KX_SetActiveScene(startscene);
1133                                                                 PHY_SetActiveEnvironment(startscene->GetPhysicsEnvironment());
1134
1135                                                                 gpg_nextframestate.system = system;
1136                                                                 gpg_nextframestate.app = &app;
1137                                                                 gpg_nextframestate.gs = &gs;
1138                                                                 pynextframestate.state = &gpg_nextframestate;
1139                                                                 pynextframestate.func = &GPG_PyNextFrame;
1140
1141                                                                 printf("Yielding control to Python script '%s'...\n", python_main);
1142                                                                 PyRun_SimpleString(python_code);
1143                                                                 printf("Exit Python script '%s'\n", python_main);
1144 #endif // WITH_PYTHON
1145                                                                 MEM_freeN(python_code);
1146                                                         }
1147                                                         else {
1148                                                                 fprintf(stderr, "ERROR: cannot yield control to Python: no Python text data block named '%s'\n", python_main);
1149                                                         }
1150                                                 }
1151                                                 else {
1152                                                         while (run) {
1153                                                                 run = GPG_NextFrame(system, &app, exitcode, exitstring, &gs);
1154                                                         }
1155                                                 }
1156                                                 app.StopGameEngine();
1157
1158                                                 /* 'app' is freed automatic when out of scope.
1159                                                  * removal is needed else the system will free an already freed value */
1160                                                 system->removeEventConsumer(&app);
1161
1162                                                 BLO_blendfiledata_free(bfd);
1163                                                 /* G.main == bfd->main, it gets referenced in free_nodesystem so we can't have a dangling pointer */
1164                                                 G.main = NULL;
1165                                                 if (python_main) MEM_freeN(python_main);
1166                                         }
1167                                 } while (exitcode == KX_EXIT_REQUEST_RESTART_GAME || exitcode == KX_EXIT_REQUEST_START_OTHER_GAME);
1168                         }
1169
1170                         // Seg Fault; icon.c gIcons == 0
1171                         BKE_icons_free();
1172
1173                         // Dispose the system
1174                         GHOST_ISystem::disposeSystem();
1175                 }
1176                 else {
1177                         error = true;
1178                         printf("error: couldn't create a system.\n");
1179                 }
1180         }
1181
1182         /* refer to WM_exit_ext() and BKE_blender_free(),
1183          * these are not called in the player but we need to match some of there behavior here,
1184          * if the order of function calls or blenders state isn't matching that of blender proper,
1185          * we may get troubles later on */
1186
1187         free_nodesystem();
1188
1189         // Cleanup
1190         RNA_exit();
1191         BLF_exit();
1192
1193 #ifdef WITH_INTERNATIONAL
1194         BLF_free_unifont();
1195         BLF_free_unifont_mono();
1196         BLT_lang_free();
1197 #endif
1198
1199         IMB_exit();
1200         BKE_images_exit();
1201         DAG_exit();
1202         IMB_moviecache_destruct();
1203
1204         SYS_DeleteSystem(syshandle);
1205
1206         int totblock= MEM_get_memory_blocks_in_use();
1207         if (totblock!=0) {
1208                 printf("Error Totblock: %d\n",totblock);
1209                 MEM_set_error_callback(mem_error_cb);
1210                 MEM_printmemlist();
1211         }
1212
1213         BKE_tempdir_session_purge();
1214
1215 #ifdef WIN32
1216         while (argv_num) {
1217                 free(argv[--argv_num]);
1218         }
1219         free(argv);
1220         argv = NULL;
1221 #endif
1222
1223         return error ? -1 : 0;
1224 }