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