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