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