Merged changes in the trunk up to revision 42116.
[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 #ifdef __APPLE__
44 // Can't use Carbon right now because of double defined type ID (In Carbon.h and DNA_ID.h, sigh)
45 //#include <Carbon/Carbon.h>
46 //#include <CFBundle.h>
47 #endif // __APPLE__
48 #include "KX_KetsjiEngine.h"
49 #include "KX_PythonInit.h"
50
51 /**********************************
52 * Begin Blender include block
53 **********************************/
54 #ifdef __cplusplus
55 extern "C"
56 {
57 #endif  // __cplusplus
58 #include "MEM_guardedalloc.h"
59 #include "BKE_blender.h"        
60 #include "BKE_global.h" 
61 #include "BKE_icons.h"  
62 #include "BKE_node.h"   
63 #include "BKE_report.h"
64 #include "BKE_library.h"
65 #include "BLI_threads.h"
66 #include "BLI_blenlib.h"
67 #include "DNA_scene_types.h"
68 #include "DNA_userdef_types.h"
69 #include "BLO_readfile.h"
70 #include "BLO_runtime.h"
71 #include "IMB_imbuf.h"
72 #include "BKE_text.h"
73 #include "BKE_sound.h"
74         
75         int GHOST_HACK_getFirstFile(char buf[]);
76         
77 // For BLF
78 #include "BLF_api.h"
79 #include "BLF_translation.h"
80 extern int datatoc_bfont_ttf_size;
81 extern char datatoc_bfont_ttf[];
82
83 #ifdef __cplusplus
84 }
85 #endif // __cplusplus
86
87 #include "GPU_draw.h"
88
89 /**********************************
90 * End Blender include block
91 **********************************/
92
93 #include "BL_System.h"
94 #include "GPG_Application.h"
95
96 #include "GHOST_ISystem.h"
97 #include "RAS_IRasterizer.h"
98
99 #include "BKE_main.h"
100 #include "BKE_utildefines.h"
101
102 #include "RNA_define.h"
103
104 #ifdef WIN32
105 #include <windows.h>
106 #if !defined(DEBUG)
107 #include <wincon.h>
108 #endif // !defined(DEBUG)
109 #endif // WIN32
110
111 const int kMinWindowWidth = 100;
112 const int kMinWindowHeight = 100;
113
114 static void mem_error_cb(const char *errorStr)
115 {
116         fprintf(stderr, "%s", errorStr);
117         fflush(stderr);
118 }
119
120 #ifdef WIN32
121 typedef enum 
122 {
123   SCREEN_SAVER_MODE_NONE = 0,
124   SCREEN_SAVER_MODE_PREVIEW,
125   SCREEN_SAVER_MODE_SAVER,
126   SCREEN_SAVER_MODE_CONFIGURATION,
127   SCREEN_SAVER_MODE_PASSWORD,
128 } ScreenSaverMode;
129
130 static ScreenSaverMode scr_saver_mode = SCREEN_SAVER_MODE_NONE;
131 static HWND scr_saver_hwnd = NULL;
132
133 static BOOL scr_saver_init(int argc, char **argv) 
134 {
135         scr_saver_mode = SCREEN_SAVER_MODE_NONE;
136         scr_saver_hwnd = NULL;
137         BOOL ret = FALSE;
138
139         int len = ::strlen(argv[0]);
140         if (len > 4 && !::stricmp(".scr", argv[0] + len - 4))
141         {
142                 scr_saver_mode = SCREEN_SAVER_MODE_CONFIGURATION;
143                 ret = TRUE;
144                 if (argc >= 2)
145                 {
146                         if (argc >= 3)
147                         {
148                                 scr_saver_hwnd = (HWND) ::atoi(argv[2]);
149                         }
150                         if (!::stricmp("/c", argv[1]))
151                         {
152                                 scr_saver_mode = SCREEN_SAVER_MODE_CONFIGURATION;
153                                 if (scr_saver_hwnd == NULL)
154                                         scr_saver_hwnd = ::GetForegroundWindow();
155                         }
156                         else if (!::stricmp("/s", argv[1]))
157                         {
158                                 scr_saver_mode = SCREEN_SAVER_MODE_SAVER;
159                         }
160                         else if (!::stricmp("/a", argv[1]))
161                         {
162                                 scr_saver_mode = SCREEN_SAVER_MODE_PASSWORD;
163                         }
164                         else if (!::stricmp("/p", argv[1])
165                                  || !::stricmp("/l", argv[1]))
166                         {
167                                 scr_saver_mode = SCREEN_SAVER_MODE_PREVIEW;
168                         }
169                 }
170         }
171         return ret;
172 }
173
174 #endif /* WIN32 */
175
176 void usage(const char* program, bool isBlenderPlayer)
177 {
178         const char * consoleoption;
179         const char * example_filename = "";
180         const char * example_pathname = "";
181
182 #ifdef _WIN32
183         consoleoption = "-c ";
184 #else
185         consoleoption = "";
186 #endif
187
188         if (isBlenderPlayer) {
189                 example_filename = "filename.blend";
190 #ifdef _WIN32
191                 example_pathname = "c:\\";
192 #else
193                 example_pathname = "/home/user/";
194 #endif
195         }
196         
197         printf("usage:   %s [-w [w h l t]] [-f [fw fh fb ff]] %s[-g gamengineoptions] "
198                 "[-s stereomode] [-m aasamples] %s\n", program, consoleoption, example_filename);
199         printf("  -h: Prints this command summary\n\n");
200         printf("  -w: display in a window\n");
201         printf("       --Optional parameters--\n"); 
202         printf("       w = window width\n");
203         printf("       h = window height\n\n");
204         printf("       l = window left coordinate\n");
205         printf("       t = window top coordinate\n");
206         printf("       Note: If w or h is defined, both must be defined.\n");
207         printf("          Also, if l or t is defined, all options must be used.\n\n");
208         printf("  -f: start game in full screen mode\n");
209         printf("       --Optional parameters--\n");
210         printf("       fw = full screen mode pixel width\n");
211         printf("       fh = full screen mode pixel height\n\n");
212         printf("       fb = full screen mode bits per pixel\n");
213         printf("       ff = full screen mode frequency\n");
214         printf("       Note: If fw or fh is defined, both must be defined.\n");
215         printf("          Also, if fb is used, fw and fh must be used. ff requires all options.\n\n");
216         printf("  -s: start player in stereo\n");
217         printf("       stereomode: hwpageflip       (Quad buffered shutter glasses)\n");
218         printf("                   syncdoubling     (Above Below)\n");
219         printf("                   sidebyside       (Left Right)\n");
220         printf("                   anaglyph         (Red-Blue glasses)\n");
221         printf("                   vinterlace       (Vertical interlace for autostereo display)\n");
222         printf("                             depending on the type of stereo you want\n\n");
223         printf("  -D: start player in dome mode\n");
224         printf("       --Optional parameters--\n");
225         printf("       angle    = field of view in degrees\n");
226         printf("       tilt     = tilt angle in degrees\n");
227         printf("       warpdata = a file to use for warping the image (absolute path)\n");      
228         printf("       mode: fisheye                (Fisheye)\n");
229         printf("             truncatedfront         (Front-Truncated)\n");
230         printf("             truncatedrear          (Rear-Truncated)\n");
231         printf("             cubemap                (Cube Map)\n");
232         printf("             sphericalpanoramic     (Spherical Panoramic)\n");
233         printf("                             depending on the type of dome you are using\n\n");
234         printf("  -m: maximum anti-aliasing (eg. 2,4,8,16)\n\n");
235         printf("  -i: parent windows ID \n\n");
236 #ifdef _WIN32
237         printf("  -c: keep console window open\n\n");
238 #endif
239         printf("  -d: turn debugging on\n\n");
240         printf("  -g: game engine options:\n\n");
241         printf("       Name                       Default      Description\n");
242         printf("       ------------------------------------------------------------------------\n");
243         printf("       fixedtime                      0         \"Enable all frames\"\n");
244         printf("       nomipmap                       0         Disable mipmaps\n");
245         printf("       show_framerate                 0         Show the frame rate\n");
246         printf("       show_properties                0         Show debug properties\n");
247         printf("       show_profile                   0         Show profiling information\n");
248         printf("       blender_material               0         Enable material settings\n");
249         printf("       ignore_deprecation_warnings    1         Ignore deprecation warnings\n");
250         printf("\n");
251         printf("  - : all arguments after this are ignored, allowing python to access them from sys.argv\n");
252         printf("\n");
253         printf("example: %s -w 320 200 10 10 -g noaudio%s%s\n", program, example_pathname, example_filename);
254         printf("example: %s -g show_framerate = 0 %s%s\n", program, example_pathname, example_filename);
255         printf("example: %s -i 232421 -m 16 %s%s\n\n", program, example_pathname, example_filename);
256 }
257
258 static void get_filename(int argc, char **argv, char *filename)
259 {
260 #ifdef __APPLE__
261 /* On Mac we park the game file (called game.blend) in the application bundle.
262 * The executable is located in the bundle as well.
263 * Therefore, we can locate the game relative to the executable.
264         */
265         int srclen = ::strlen(argv[0]);
266         int len = 0;
267         char *gamefile = NULL;
268         
269         filename[0] = '\0';
270
271         if (argc > 1) {
272                 if (BLI_exists(argv[argc-1])) {
273                         BLI_strncpy(filename, argv[argc-1], FILE_MAX);
274                 }
275                 if (::strncmp(argv[argc-1], "-psn_", 5)==0) {
276                         static char firstfilebuf[512];
277                         if (GHOST_HACK_getFirstFile(firstfilebuf)) {
278                                 BLI_strncpy(filename, firstfilebuf, FILE_MAX);
279                         }
280                 }                        
281         }
282         
283         srclen -= ::strlen("MacOS/blenderplayer");
284         if (srclen > 0) {
285                 len = srclen + ::strlen("Resources/game.blend"); 
286                 gamefile = new char [len + 1];
287                 ::strcpy(gamefile, argv[0]);
288                 ::strcpy(gamefile + srclen, "Resources/game.blend");
289                 //::printf("looking for file: %s\n", filename);
290                 
291                 if (BLI_exists(gamefile))
292                         BLI_strncpy(filename, gamefile, FILE_MAX);
293
294                 delete [] gamefile;
295         }
296         
297 #else
298         filename[0] = '\0';
299
300         if(argc > 1)
301                 BLI_strncpy(filename, argv[argc-1], FILE_MAX);
302 #endif // !_APPLE
303 }
304
305 static BlendFileData *load_game_data(const char *progname, char *filename = NULL, char *relativename = NULL)
306 {
307         ReportList reports;
308         BlendFileData *bfd = NULL;
309
310         BKE_reports_init(&reports, RPT_STORE);
311         
312         /* try to load ourself, will only work if we are a runtime */
313         if (BLO_is_a_runtime(progname)) {
314                 bfd= BLO_read_runtime(progname, &reports);
315                 if (bfd) {
316                         bfd->type= BLENFILETYPE_RUNTIME;
317                         BLI_strncpy(bfd->main->name, progname, sizeof(bfd->main->name));
318                 }
319         } else {
320                 bfd= BLO_read_from_file(progname, &reports);
321         }
322         
323         if (!bfd && filename) {
324                 bfd = load_game_data(filename);
325                 if (!bfd) {
326                         printf("Loading %s failed: ", filename);
327                         BKE_reports_print(&reports, RPT_ERROR);
328                 }
329         }
330
331         BKE_reports_clear(&reports);
332         
333         return bfd;
334 }
335
336 int main(int argc, char** argv)
337 {
338         int i;
339         int argc_py_clamped= argc; /* use this so python args can be added after ' - ' */
340         bool error = false;
341         SYS_SystemHandle syshandle = SYS_GetSystem();
342         bool fullScreen = false;
343         bool fullScreenParFound = false;
344         bool windowParFound = false;
345 #ifdef WIN32
346         bool closeConsole = true;
347 #endif
348         RAS_IRasterizer::StereoMode stereomode = RAS_IRasterizer::RAS_STEREO_NOSTEREO;
349         bool stereoWindow = false;
350         bool stereoParFound = false;
351         int stereoFlag = STEREO_NOSTEREO;
352         int domeFov = -1;
353         int domeTilt = -200;
354         int domeMode = 0;
355         char* domeWarp = NULL;
356         Text *domeText  = NULL;
357         int windowLeft = 100;
358         int windowTop = 100;
359         int windowWidth = 640;
360         int windowHeight = 480;
361         GHOST_TUns32 fullScreenWidth = 0;
362         GHOST_TUns32 fullScreenHeight= 0;
363         int fullScreenBpp = 32;
364         int fullScreenFrequency = 60;
365         GHOST_TEmbedderWindowID parentWindow = 0;
366         bool isBlenderPlayer = false;
367         int validArguments=0;
368         GHOST_TUns16 aasamples = 0;
369         
370 #ifdef __linux__
371 #ifdef __alpha__
372         signal (SIGFPE, SIG_IGN);
373 #endif /* __alpha__ */
374 #endif /* __linux__ */
375         BLI_init_program_path(argv[0]);
376         BLI_init_temporary_dir(NULL);
377 #ifdef __APPLE__
378         // Can't use Carbon right now because of double defined type ID (In Carbon.h and DNA_ID.h, sigh)
379         /*
380         IBNibRef                nibRef;
381         WindowRef               window;
382         OSStatus                err;
383
384           // Create a Nib reference passing the name of the nib file (without the .nib extension)
385           // CreateNibReference only searches into the application bundle.
386           err = ::CreateNibReference(CFSTR("main"), &nibRef);
387           if (err) return -1;
388           
389                 // Once the nib reference is created, set the menu bar. "MainMenu" is the name of the menu bar
390                 // object. This name is set in InterfaceBuilder when the nib is created.
391                 err = ::SetMenuBarFromNib(nibRef, CFSTR("MenuBar"));
392                 if (err) return -1;
393                 
394                   // We don't need the nib reference anymore.
395                   ::DisposeNibReference(nibRef);
396         */
397 #endif // __APPLE__
398         
399         // We don't use threads directly in the BGE, but we need to call this so things like
400         // freeing up GPU_Textures works correctly.
401         BLI_threadapi_init();
402
403         RNA_init();
404
405         init_nodesystem();
406         
407         initglobals();
408
409         U.gameflags |= USER_DISABLE_VBO;
410         // We load our own G.main, so free the one that initglobals() gives us
411         free_main(G.main);
412         G.main = NULL;
413
414         IMB_init();
415
416         // Setup builtin font for BLF (mostly copied from creator.c, wm_init_exit.c and interface_style.c)
417         BLF_init(11, U.dpi);
418         BLF_lang_init();
419         BLF_lang_encoding("");
420         BLF_lang_set("");
421
422         BLF_load_mem("default", (unsigned char*)datatoc_bfont_ttf, datatoc_bfont_ttf_size);
423
424         // Parse command line options
425 #if defined(DEBUG)
426         printf("argv[0] = '%s'\n", argv[0]);
427 #endif
428
429 #ifdef WIN32
430         if (scr_saver_init(argc, argv))
431         {
432                 switch (scr_saver_mode)
433                 {
434                 case SCREEN_SAVER_MODE_CONFIGURATION:
435                         MessageBox(scr_saver_hwnd, "This screen saver has no options that you can set", "Screen Saver", MB_OK);
436                         break;
437                 case SCREEN_SAVER_MODE_PASSWORD:
438                         /* This is W95 only, which we currently do not support.
439                            Fall-back to normal screen saver behaviour in that case... */
440                 case SCREEN_SAVER_MODE_SAVER:
441                         fullScreen = true;
442                         fullScreenParFound = true;
443                         break;
444
445                 case SCREEN_SAVER_MODE_PREVIEW:
446                         /* This will actually be handled somewhere below... */
447                         break;
448                 }
449         }
450 #endif
451         // XXX add the ability to change this values to the command line parsing.
452         U.mixbufsize = 2048;
453         U.audiodevice = 2;
454         U.audiorate = 44100;
455         U.audioformat = 0x24;
456         U.audiochannels = 2;
457
458         // XXX this one too
459         U.anisotropic_filter = 2;
460
461         sound_init_once();
462
463         /* if running blenderplayer the last argument can't be parsed since it has to be the filename. */
464         isBlenderPlayer = !BLO_is_a_runtime(argv[0]);
465         if (isBlenderPlayer)
466                 validArguments = argc - 1;
467         else
468                 validArguments = argc;
469
470         for (i = 1; (i < validArguments) && !error 
471 #ifdef WIN32
472                 && scr_saver_mode == SCREEN_SAVER_MODE_NONE
473 #endif
474                 ;)
475
476         {
477 #if defined(DEBUG)
478                 printf("argv[%d] = '%s'   , %i\n", i, argv[i],argc);
479 #endif
480                 if (argv[i][0] == '-')
481                 {
482                         /* ignore all args after " - ", allow python to have own args */
483                         if (argv[i][1]=='\0') {
484                                 argc_py_clamped= i;
485                                 break;
486                         }
487                         
488                         switch (argv[i][1])
489                         {
490                         case 'g':
491                                 // Parse game options
492                                 {
493                                         i++;
494                                         if (i <= validArguments)
495                                         {
496                                                 char* paramname = argv[i];
497                                                 // Check for single value versus assignment
498                                                 if (i+1 <= validArguments && (*(argv[i+1]) == '='))
499                                                 {
500                                                         i++;
501                                                         if (i + 1 <= validArguments)
502                                                         {
503                                                                 i++;
504                                                                 // Assignment
505                                                                 SYS_WriteCommandLineInt(syshandle, paramname, atoi(argv[i]));
506                                                                 SYS_WriteCommandLineFloat(syshandle, paramname, atof(argv[i]));
507                                                                 SYS_WriteCommandLineString(syshandle, paramname, argv[i]);
508 #if defined(DEBUG)
509                                                                 printf("%s = '%s'\n", paramname, argv[i]);
510 #endif
511                                                                 i++;
512                                                         }
513                                                         else
514                                                         {
515                                                                 error = true;
516                                                                 printf("error: argument assignment %s without value.\n", paramname);
517                                                         }
518                                                 }
519                                                 else
520                                                 {
521 //                                                      SYS_WriteCommandLineInt(syshandle, argv[i++], 1);
522                                                 }
523                                         }
524                                 }
525                                 break;
526
527                         case 'd':
528                                 i++;
529                                 G.f |= G_DEBUG;     /* std output printf's */
530                                 MEM_set_memory_debug();
531                                 break;
532
533                         case 'f':
534                                 i++;
535                                 fullScreen = true;
536                                 fullScreenParFound = true;
537                                 if ((i + 2) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-')
538                                 {
539                                         fullScreenWidth = atoi(argv[i++]);
540                                         fullScreenHeight = atoi(argv[i++]);
541                                         if ((i + 1) <= validArguments && argv[i][0] != '-')
542                                         {
543                                                 fullScreenBpp = atoi(argv[i++]);
544                                                 if ((i + 1) <= validArguments && argv[i][0] != '-')
545                                                         fullScreenFrequency = atoi(argv[i++]);
546                                         }
547                                 }
548                                 break;
549                         case 'w':
550                                 // Parse window position and size options
551                                 i++;
552                                 fullScreen = false;
553                                 windowParFound = true;
554
555                                 if ((i + 2) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-')
556                                 {
557                                         windowWidth = atoi(argv[i++]);
558                                         windowHeight = atoi(argv[i++]);
559                                         if ((i + 2) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-')
560                                         {
561                                                 windowLeft = atoi(argv[i++]);
562                                                 windowTop = atoi(argv[i++]);
563                                         }
564                                 }
565                                 break;
566                                         
567                         case 'h':
568                                 usage(argv[0], isBlenderPlayer);
569                                 return 0;
570                                 break;
571                         case 'i':
572                                 i++;
573                                 if ( (i + 1) <= validArguments )
574                                         parentWindow = atoi(argv[i++]); 
575                                 else {
576                                         error = true;
577                                         printf("error: too few options for parent window argument.\n");
578                                 }
579 #if defined(DEBUG)
580                                 printf("XWindows ID = %d\n", parentWindow);
581 #endif // defined(DEBUG)
582                                 break;
583                         case 'm':
584                                 i++;
585                                 if ((i+1) <= validArguments )
586                                 aasamples = atoi(argv[i++]);
587                                 break;
588                         case 'c':
589                                 i++;
590 #ifdef WIN32
591                                 closeConsole = false;
592 #endif
593                                 break;
594                         case 's':  // stereo
595                                 i++;
596                                 if ((i + 1) <= validArguments)
597                                 {
598                                         stereomode = (RAS_IRasterizer::StereoMode) atoi(argv[i]);
599                                         if (stereomode < RAS_IRasterizer::RAS_STEREO_NOSTEREO || stereomode >= RAS_IRasterizer::RAS_STEREO_MAXSTEREO)
600                                                 stereomode = RAS_IRasterizer::RAS_STEREO_NOSTEREO;
601                                         
602                                         if(!strcmp(argv[i], "nostereo"))  // ok, redundant but clear
603                                                 stereomode = RAS_IRasterizer::RAS_STEREO_NOSTEREO;
604                                         
605                                         // only the hardware pageflip method needs a stereo window
606                                         else if(!strcmp(argv[i], "hwpageflip")) {
607                                                 stereomode = RAS_IRasterizer::RAS_STEREO_QUADBUFFERED;
608                                                 stereoWindow = true;
609                                         }
610                                         else if(!strcmp(argv[i], "syncdoubling"))
611                                                 stereomode = RAS_IRasterizer::RAS_STEREO_ABOVEBELOW;
612                                         
613                                         else if(!strcmp(argv[i], "anaglyph"))
614                                                 stereomode = RAS_IRasterizer::RAS_STEREO_ANAGLYPH;
615                                         
616                                         else if(!strcmp(argv[i], "sidebyside"))
617                                                 stereomode = RAS_IRasterizer::RAS_STEREO_SIDEBYSIDE;
618                                         
619                                         else if(!strcmp(argv[i], "vinterlace"))
620                                                 stereomode = RAS_IRasterizer::RAS_STEREO_VINTERLACE;
621                                         
622 #if 0
623                                         // future stuff
624                                         else if(!strcmp(argv[i], "stencil")
625                                                 stereomode = RAS_STEREO_STENCIL;
626 #endif
627                                         
628                                         i++;
629                                         stereoParFound = true;
630                                         stereoFlag = STEREO_ENABLED;
631                                 }
632                                 else
633                                 {
634                                         error = true;
635                                         printf("error: too few options for stereo argument.\n");
636                                 }
637                                 break;
638                         case 'D':
639                                 stereoFlag = STEREO_DOME;
640                                 stereomode = RAS_IRasterizer::RAS_STEREO_DOME;
641                                 i++;
642                                 if ((i + 1) <= validArguments)
643                                 {
644                                         if(!strcmp(argv[i], "angle")){
645                                                 i++;
646                                                 domeFov = atoi(argv[i++]);
647                                         }
648                                         if(!strcmp(argv[i], "tilt")){
649                                                 i++;
650                                                 domeTilt = atoi(argv[i++]);
651                                         }
652                                         if(!strcmp(argv[i], "warpdata")){
653                                                 i++;
654                                                 domeWarp = argv[i++];
655                                         }
656                                         if(!strcmp(argv[i], "mode")){
657                                                 i++;
658                                                 if(!strcmp(argv[i], "fisheye"))
659                                                         domeMode = DOME_FISHEYE;
660                                                         
661                                                 else if(!strcmp(argv[i], "truncatedfront"))
662                                                         domeMode = DOME_TRUNCATED_FRONT;
663                                                         
664                                                 else if(!strcmp(argv[i], "truncatedrear"))
665                                                         domeMode = DOME_TRUNCATED_REAR;
666                                                         
667                                                 else if(!strcmp(argv[i], "cubemap"))
668                                                         domeMode = DOME_ENVMAP;
669                                                         
670                                                 else if(!strcmp(argv[i], "sphericalpanoramic"))
671                                                         domeMode = DOME_PANORAM_SPH;
672
673                                                 else
674                                                         printf("error: %s is not a valid dome mode.\n", argv[i]);
675                                         }
676                                         i++;
677                                 }
678                                 break;
679                         default:
680                                 printf("Unknown argument: %s\n", argv[i++]);
681                                 break;
682                         }
683                 }
684                 else
685                 {
686                         i++;
687                 }
688         }
689         
690         if ((windowWidth < kMinWindowWidth) || (windowHeight < kMinWindowHeight))
691         {
692                 error = true;
693                 printf("error: window size too small.\n");
694         }
695         
696         if (error )
697         {
698                 usage(argv[0], isBlenderPlayer);
699                 return 0;
700         }
701
702 #ifdef WIN32
703         if (scr_saver_mode != SCREEN_SAVER_MODE_CONFIGURATION)
704 #endif
705         {
706 #ifdef __APPLE__
707                 //SYS_WriteCommandLineInt(syshandle, "show_framerate", 1);
708                 //SYS_WriteCommandLineInt(syshandle, "nomipmap", 1);
709                 //fullScreen = false;           // Can't use full screen
710 #endif
711
712                 if (SYS_GetCommandLineInt(syshandle, "nomipmap", 0))
713                 {
714                         GPU_set_mipmap(0);
715                 }
716
717                 GPU_set_anisotropic(U.anisotropic_filter);
718                 
719                 // Create the system
720                 if (GHOST_ISystem::createSystem() == GHOST_kSuccess)
721                 {
722                         GHOST_ISystem* system = GHOST_ISystem::getSystem();
723                         assertd(system);
724                         
725                         if (!fullScreenWidth || !fullScreenHeight)
726                                 system->getMainDisplayDimensions(fullScreenWidth, fullScreenHeight);
727                         // process first batch of events. If the user
728                         // drops a file on top off the blenderplayer icon, we 
729                         // receive an event with the filename
730                         
731                         system->processEvents(0);
732                         
733                         // this bracket is needed for app (see below) to get out
734                         // of scope before GHOST_ISystem::disposeSystem() is called.
735                         {
736                                 int exitcode = KX_EXIT_REQUEST_NO_REQUEST;
737                                 STR_String exitstring = "";
738                                 GPG_Application app(system);
739                                 bool firstTimeRunning = true;
740                                 char filename[FILE_MAX];
741                                 char pathname[FILE_MAX];
742                                 char *titlename;
743
744                                 get_filename(argc_py_clamped, argv, filename);
745                                 if(filename[0])
746                                         BLI_path_cwd(filename);
747                                 
748
749                                 // fill the GlobalSettings with the first scene files
750                                 // those may change during the game and persist after using Game Actuator
751                                 GlobalSettings gs;
752
753                                 do
754                                 {
755                                         // Read the Blender file
756                                         BlendFileData *bfd;
757                                         
758                                         // if we got an exitcode 3 (KX_EXIT_REQUEST_START_OTHER_GAME) load a different file
759                                         if (exitcode == KX_EXIT_REQUEST_START_OTHER_GAME)
760                                         {
761                                                 char basedpath[240];
762                                                 
763                                                 // base the actuator filename relative to the last file
764                                                 BLI_strncpy(basedpath, exitstring.Ptr(), sizeof(basedpath));
765                                                 BLI_path_abs(basedpath, pathname);
766                                                 
767                                                 bfd = load_game_data(basedpath);
768
769                                                 if (!bfd)
770                                                 {
771                                                         // just add "//" in front of it
772                                                         char temppath[242];
773                                                         strcpy(temppath, "//");
774                                                         strcat(temppath, basedpath);
775                                 
776                                                         BLI_path_abs(temppath, pathname);
777                                                         bfd = load_game_data(temppath);
778                                                 }
779                                         }
780                                         else
781                                         {
782                                                 bfd = load_game_data(BLI_program_path(), filename[0]? filename: NULL);
783                                         }
784                                         
785                                         //::printf("game data loaded from %s\n", filename);
786                                         
787                                         if (!bfd) {
788                                                 usage(argv[0], isBlenderPlayer);
789                                                 error = true;
790                                                 exitcode = KX_EXIT_REQUEST_QUIT_GAME;
791                                         } 
792                                         else 
793                                         {
794 #ifdef WIN32
795 #if !defined(DEBUG)
796                                                 if (closeConsole)
797                                                 {
798                                                         //::FreeConsole();    // Close a console window
799                                                 }
800 #endif // !defined(DEBUG)
801 #endif // WIN32
802                                                 Main *maggie = bfd->main;
803                                                 Scene *scene = bfd->curscene;
804                                                 G.main = maggie;
805
806                                                 if (firstTimeRunning) {
807                                                         G.fileflags  = bfd->fileflags;
808
809                                                         gs.matmode= scene->gm.matmode;
810                                                         gs.glslflag= scene->gm.flag;
811                                                 }
812
813                                                 //Seg Fault; icon.c gIcons == 0
814                                                 BKE_icons_init(1);
815                                                 
816                                                 titlename = maggie->name;
817                                                 
818                                                 // Check whether the game should be displayed full-screen
819                                                 if ((!fullScreenParFound) && (!windowParFound))
820                                                 {
821                                                         // Only use file settings when command line did not override
822                                                         if (scene->gm.fullscreen) {
823                                                                 //printf("fullscreen option found in Blender file\n");
824                                                                 fullScreen = true;
825                                                                 fullScreenWidth= scene->gm.xplay;
826                                                                 fullScreenHeight= scene->gm.yplay;
827                                                                 fullScreenFrequency= scene->gm.freqplay;
828                                                                 fullScreenBpp = scene->gm.depth;
829                                                         }
830                                                         else
831                                                         {
832                                                                 fullScreen = false;
833                                                                 windowWidth = scene->gm.xplay;
834                                                                 windowHeight = scene->gm.yplay;
835                                                         }
836                                                 }
837                                                 
838                                                 
839                                                 // Check whether the game should be displayed in stereo
840                                                 if (!stereoParFound)
841                                                 {
842                                                         if(scene->gm.stereoflag == STEREO_ENABLED){
843                                                                 stereomode = (RAS_IRasterizer::StereoMode) scene->gm.stereomode;
844                                                                 if (stereomode != RAS_IRasterizer::RAS_STEREO_QUADBUFFERED)
845                                                                         stereoWindow = true;
846                                                         }
847                                                 }
848                                                 else
849                                                         scene->gm.stereoflag = STEREO_ENABLED;
850
851                                                 if (stereoFlag == STEREO_DOME){
852                                                         stereomode = RAS_IRasterizer::RAS_STEREO_DOME;
853                                                         scene->gm.stereoflag = STEREO_DOME;
854                                                         if (domeFov > 89)
855                                                                 scene->gm.dome.angle = domeFov;
856                                                         if (domeTilt > -180)
857                                                                 scene->gm.dome.tilt = domeTilt;
858                                                         if (domeMode > 0)
859                                                                 scene->gm.dome.mode = domeMode;
860                                                         if (domeWarp)
861                                                         {
862                                                                 //XXX to do: convert relative to absolute path
863                                                                 domeText= add_text(domeWarp, "");
864                                                                 if(!domeText)
865                                                                         printf("error: invalid warpdata text file - %s\n", domeWarp);
866                                                                 else
867                                                                         scene->gm.dome.warptext = domeText;
868                                                         }
869                                                 }
870                                                 
871                                                 //                                      GPG_Application app (system, maggie, startscenename);
872                                                 app.SetGameEngineData(maggie, scene, &gs, argc, argv); /* this argc cant be argc_py_clamped, since python uses it */
873                                                 BLI_strncpy(pathname, maggie->name, sizeof(pathname));
874                                                 if(G.main != maggie) {
875                                                         BLI_strncpy(G.main->name, maggie->name, sizeof(G.main->name));
876                                                 }
877 #ifdef WITH_PYTHON
878                                                 setGamePythonPath(G.main->name);
879 #endif
880                                                 if (firstTimeRunning)
881                                                 {
882                                                         firstTimeRunning = false;
883
884                                                         if (fullScreen)
885                                                         {
886 #ifdef WIN32
887                                                                 if (scr_saver_mode == SCREEN_SAVER_MODE_SAVER)
888                                                                 {
889                                                                         app.startScreenSaverFullScreen(fullScreenWidth, fullScreenHeight, fullScreenBpp, fullScreenFrequency,
890                                                                                 stereoWindow, stereomode, aasamples);
891                                                                 }
892                                                                 else
893 #endif
894                                                                 {
895                                                                         app.startFullScreen(fullScreenWidth, fullScreenHeight, fullScreenBpp, fullScreenFrequency,
896                                                                                 stereoWindow, stereomode, aasamples);
897                                                                 }
898                                                         }
899                                                         else
900                                                         {
901 #ifdef __APPLE__
902                                                                 // on Mac's we'll show the executable name instead of the 'game.blend' name
903                                                                 char tempname[1024], *appstring;
904                                                                 ::strcpy(tempname, titlename);
905                                                                 
906                                                                 appstring = strstr(tempname, ".app/");
907                                                                 if (appstring) {
908                                                                         appstring[2] = 0;
909                                                                         titlename = &tempname[0];
910                                                                 }
911 #endif
912                                                                 // Strip the path so that we have the name of the game file
913                                                                 STR_String path = titlename;
914 #ifndef WIN32
915                                                                 vector<STR_String> parts = path.Explode('/');
916 #else  // WIN32
917                                                                 vector<STR_String> parts = path.Explode('\\');
918 #endif // WIN32                        
919                                                                 STR_String title;
920                                                                 if (parts.size())
921                                                                 {
922                                                                         title = parts[parts.size()-1];
923                                                                         parts = title.Explode('.');
924                                                                         if (parts.size() > 1)
925                                                                         {
926                                                                                 title = parts[0];
927                                                                         }
928                                                                 }
929                                                                 else
930                                                                 {
931                                                                         title = "blenderplayer";
932                                                                 }
933 #ifdef WIN32
934                                                                 if (scr_saver_mode == SCREEN_SAVER_MODE_PREVIEW)
935                                                                 {
936                                                                         app.startScreenSaverPreview(scr_saver_hwnd, stereoWindow, stereomode, aasamples);
937                                                                 }
938                                                                 else
939 #endif
940                                                                 {
941                                                                                                                                                                                                                 if (parentWindow != 0)
942                                                                                 app.startEmbeddedWindow(title, parentWindow, stereoWindow, stereomode, aasamples);
943                                                                         else
944                                                                                 app.startWindow(title, windowLeft, windowTop, windowWidth, windowHeight,
945                                                                                 stereoWindow, stereomode, aasamples);
946                                                                 }
947                                                         }
948                                                 }
949                                                 else
950                                                 {
951                                                         app.StartGameEngine(stereomode);
952                                                         exitcode = KX_EXIT_REQUEST_NO_REQUEST;
953                                                 }
954                                                 
955                                                 // Add the application as event consumer
956                                                 system->addEventConsumer(&app);
957                                                 
958                                                 // Enter main loop
959                                                 bool run = true;
960                                                 while (run)
961                                                 {
962                                                         system->processEvents(false);
963                                                         system->dispatchEvents();
964                                                         if ((exitcode = app.getExitRequested()))
965                                                         {
966                                                                 run = false;
967                                                                 exitstring = app.getExitString();
968                                                                 gs = *app.getGlobalSettings();
969                                                         }
970                                                 }
971                                                 app.StopGameEngine();
972
973                                                 /* 'app' is freed automatic when out of scope. 
974                                                  * removal is needed else the system will free an already freed value */
975                                                 system->removeEventConsumer(&app);
976
977                                                 BLO_blendfiledata_free(bfd);
978                                         }
979                                 } while (exitcode == KX_EXIT_REQUEST_RESTART_GAME || exitcode == KX_EXIT_REQUEST_START_OTHER_GAME);
980                         }
981
982                         // Seg Fault; icon.c gIcons == 0
983                         BKE_icons_free();
984
985                         // Dispose the system
986                         GHOST_ISystem::disposeSystem();
987                 } else {
988                         error = true;
989                         printf("error: couldn't create a system.\n");
990                 }
991         }
992
993         // Cleanup
994         RNA_exit();
995         BLF_exit();
996
997 #ifdef WITH_INTERNATIONAL
998         BLF_free_unifont();
999 #endif
1000
1001         IMB_exit();
1002         free_nodesystem();
1003
1004         SYS_DeleteSystem(syshandle);
1005
1006         int totblock= MEM_get_memory_blocks_in_use();
1007         if(totblock!=0) {
1008                 printf("Error Totblock: %d\n",totblock);
1009                 MEM_set_error_callback(mem_error_cb);
1010                 MEM_printmemlist();
1011         }
1012
1013         return error ? -1 : 0;
1014 }
1015
1016