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