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