- some more savegame stuff
[supertux.git] / src / setup.cpp
1 /*
2   setup.c
3   
4   Super Tux - Setup
5   
6   by Bill Kendrick
7   bill@newbreedsoftware.com
8   http://www.newbreedsoftware.com/supertux/
9   
10   April 11, 2000 - March 15, 2004
11 */
12
13 #include <assert.h>
14 #include <iostream>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <errno.h>
19 #include <unistd.h>
20 #include <SDL.h>
21 #include <SDL_image.h>
22 #ifndef NOOPENGL
23 #include <SDL_opengl.h>
24 #endif
25
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 #include <dirent.h>
29 #ifndef WIN32
30 #include <libgen.h>
31 #endif
32 #include <ctype.h>
33
34 #include "defines.h"
35 #include "globals.h"
36 #include "setup.h"
37 #include "screen.h"
38 #include "texture.h"
39 #include "menu.h"
40 #include "gameloop.h"
41 #include "configfile.h"
42 #include "scene.h"
43 #include "worldmap.h"
44
45 #ifdef WIN32
46 #define mkdir(dir, mode)    mkdir(dir)
47 // on win32 we typically don't want LFS paths
48 #undef DATA_PREFIX
49 #define DATA_PREFIX "./data/"
50 #endif
51
52 /* Local function prototypes: */
53
54 void seticon(void);
55 void usage(char * prog, int ret);
56
57 /* Does the given file exist and is it accessible? */
58 int faccessible(const char *filename)
59 {
60   struct stat filestat;
61   if (stat(filename, &filestat) == -1)
62     {
63       return false;
64     }
65   else
66     {
67       if(S_ISREG(filestat.st_mode))
68         return true;
69       else
70         return false;
71     }
72 }
73
74 /* Can we write to this location? */
75 int fwriteable(const char *filename)
76 {
77   FILE* fi;
78   fi = fopen(filename, "wa");
79   if (fi == NULL)
80     {
81       return false;
82     }
83   return true;
84 }
85
86 /* Makes sure a directory is created in either the SuperTux home directory or the SuperTux base directory.*/
87 int fcreatedir(const char* relative_dir)
88 {
89   char path[1024];
90   snprintf(path, 1024, "%s/%s/", st_dir, relative_dir);
91   if(mkdir(path,0755) != 0)
92     {
93       snprintf(path, 1024, "%s/%s/", datadir.c_str(), relative_dir);
94       if(mkdir(path,0755) != 0)
95         {
96           return false;
97         }
98       else
99         {
100           return true;
101         }
102     }
103   else
104     {
105       return true;
106     }
107 }
108
109 FILE * opendata(const char * rel_filename, const char * mode)
110 {
111   char * filename = NULL;
112   FILE * fi;
113
114   filename = (char *) malloc(sizeof(char) * (strlen(st_dir) +
115                                              strlen(rel_filename) + 1));
116
117   strcpy(filename, st_dir);
118   /* Open the high score file: */
119
120   strcat(filename, rel_filename);
121
122   /* Try opening the file: */
123   fi = fopen(filename, mode);
124
125   if (fi == NULL)
126     {
127       fprintf(stderr, "Warning: Unable to open the file \"%s\" ", filename);
128
129       if (strcmp(mode, "r") == 0)
130         fprintf(stderr, "for read!!!\n");
131       else if (strcmp(mode, "w") == 0)
132         fprintf(stderr, "for write!!!\n");
133     }
134   free( filename );
135
136   return(fi);
137 }
138
139 /* Get all names of sub-directories in a certain directory. */
140 /* Returns the number of sub-directories found. */
141 /* Note: The user has to free the allocated space. */
142 string_list_type dsubdirs(const char *rel_path,const  char* expected_file)
143 {
144   DIR *dirStructP;
145   struct dirent *direntp;
146   string_list_type sdirs;
147   char filename[1024];
148   char path[1024];
149
150   string_list_init(&sdirs);
151   sprintf(path,"%s/%s",st_dir,rel_path);
152   if((dirStructP = opendir(path)) != NULL)
153     {
154       while((direntp = readdir(dirStructP)) != NULL)
155         {
156           char absolute_filename[1024];
157           struct stat buf;
158
159           sprintf(absolute_filename, "%s/%s", path, direntp->d_name);
160
161           if (stat(absolute_filename, &buf) == 0 && S_ISDIR(buf.st_mode))
162             {
163               if(expected_file != NULL)
164                 {
165                   sprintf(filename,"%s/%s/%s",path,direntp->d_name,expected_file);
166                   if(!faccessible(filename))
167                     continue;
168                 }
169
170               string_list_add_item(&sdirs,direntp->d_name);
171             }
172         }
173       closedir(dirStructP);
174     }
175
176   sprintf(path,"%s/%s",datadir.c_str(),rel_path);
177   if((dirStructP = opendir(path)) != NULL)
178     {
179       while((direntp = readdir(dirStructP)) != NULL)
180         {
181           char absolute_filename[1024];
182           struct stat buf;
183
184           sprintf(absolute_filename, "%s/%s", path, direntp->d_name);
185
186           if (stat(absolute_filename, &buf) == 0 && S_ISDIR(buf.st_mode))
187             {
188               if(expected_file != NULL)
189                 {
190                   sprintf(filename,"%s/%s/%s",path,direntp->d_name,expected_file);
191                   if(!faccessible(filename))
192                     {
193                       continue;
194                     }
195                   else
196                     {
197                       sprintf(filename,"%s/%s/%s/%s",st_dir,rel_path,direntp->d_name,expected_file);
198                       if(faccessible(filename))
199                         continue;
200                     }
201                 }
202
203               string_list_add_item(&sdirs,direntp->d_name);
204             }
205         }
206       closedir(dirStructP);
207     }
208
209   return sdirs;
210 }
211
212 string_list_type dfiles(const char *rel_path, const  char* glob, const  char* exception_str)
213 {
214   DIR *dirStructP;
215   struct dirent *direntp;
216   string_list_type sdirs;
217   char path[1024];
218
219   string_list_init(&sdirs);
220   sprintf(path,"%s/%s",st_dir,rel_path);
221   if((dirStructP = opendir(path)) != NULL)
222     {
223       while((direntp = readdir(dirStructP)) != NULL)
224         {
225           char absolute_filename[1024];
226           struct stat buf;
227
228           sprintf(absolute_filename, "%s/%s", path, direntp->d_name);
229
230           if (stat(absolute_filename, &buf) == 0 && S_ISREG(buf.st_mode))
231             {
232               if(exception_str != NULL)
233                 {
234                   if(strstr(direntp->d_name,exception_str) != NULL)
235                     continue;
236                 }
237               if(glob != NULL)
238                 if(strstr(direntp->d_name,glob) == NULL)
239                   continue;
240
241               string_list_add_item(&sdirs,direntp->d_name);
242             }
243         }
244       closedir(dirStructP);
245     }
246
247   sprintf(path,"%s/%s",datadir.c_str(),rel_path);
248   if((dirStructP = opendir(path)) != NULL)
249     {
250       while((direntp = readdir(dirStructP)) != NULL)
251         {
252           char absolute_filename[1024];
253           struct stat buf;
254
255           sprintf(absolute_filename, "%s/%s", path, direntp->d_name);
256
257           if (stat(absolute_filename, &buf) == 0 && S_ISREG(buf.st_mode))
258             {
259               if(exception_str != NULL)
260                 {
261                   if(strstr(direntp->d_name,exception_str) != NULL)
262                     continue;
263                 }
264               if(glob != NULL)
265                 if(strstr(direntp->d_name,glob) == NULL)
266                   continue;
267
268               string_list_add_item(&sdirs,direntp->d_name);
269             }
270         }
271       closedir(dirStructP);
272     }
273
274   return sdirs;
275 }
276
277 void free_strings(char **strings, int num)
278 {
279   int i;
280   for(i=0; i < num; ++i)
281     free(strings[i]);
282 }
283
284 /* --- SETUP --- */
285 /* Set SuperTux configuration and save directories */
286 void st_directory_setup(void)
287 {
288   char *home;
289   char str[1024];
290   /* Get home directory (from $HOME variable)... if we can't determine it,
291      use the current directory ("."): */
292   if (getenv("HOME") != NULL)
293     home = getenv("HOME");
294   else
295     home = ".";
296
297   st_dir = (char *) malloc(sizeof(char) * (strlen(home) +
298                                            strlen("/.supertux") + 1));
299   strcpy(st_dir, home);
300   strcat(st_dir, "/.supertux");
301
302   /* Remove .supertux config-file from old SuperTux versions */
303   if(faccessible(st_dir))
304     {
305       remove
306         (st_dir);
307     }
308
309   st_save_dir = (char *) malloc(sizeof(char) * (strlen(st_dir) + strlen("/save") + 1));
310
311   strcpy(st_save_dir,st_dir);
312   strcat(st_save_dir,"/save");
313
314   /* Create them. In the case they exist they won't destroy anything. */
315   mkdir(st_dir, 0755);
316   mkdir(st_save_dir, 0755);
317
318   sprintf(str, "%s/levels", st_dir);
319   mkdir(str, 0755);
320
321   // User has not that a datadir, so we try some magic
322   if (datadir.empty())
323     {
324 #ifndef WIN32
325       // Detect datadir
326       char exe_file[PATH_MAX];
327       if (readlink("/proc/self/exe", exe_file, PATH_MAX) < 0)
328         {
329           puts("Couldn't read /proc/self/exe, using default path: " DATA_PREFIX);
330           datadir = DATA_PREFIX;
331         }
332       else
333         {
334           std::string exedir = std::string(dirname(exe_file)) + "/";
335           
336           datadir = exedir + "../data/"; // SuperTux run from source dir
337           if (access(datadir.c_str(), F_OK) != 0)
338             {
339               datadir = exedir + "../share/supertux/"; // SuperTux run from PATH
340               if (access(datadir.c_str(), F_OK) != 0) 
341                 { // If all fails, fall back to compiled path
342                   datadir = DATA_PREFIX; 
343                 }
344             }
345         }
346 #else
347   datadir = DATA_PREFIX;
348 #endif
349     }
350   printf("Datadir: %s\n", datadir.c_str());
351 }
352
353 /* Create and setup menus. */
354 void st_menu(void)
355 {
356   main_menu      = new Menu();
357   options_menu   = new Menu();
358   options_controls_menu   = new Menu();
359   load_game_menu = new Menu();
360   save_game_menu = new Menu();
361   game_menu      = new Menu();
362   highscore_menu = new Menu();
363   contrib_menu   = new Menu();
364   contrib_subset_menu   = new Menu();
365   worldmap_menu  = new Menu();
366
367   main_menu->set_pos(screen->w/2, 335);
368   main_menu->additem(MN_GOTO, "Start Game",0,load_game_menu);
369   main_menu->additem(MN_GOTO, "Contrib Levels",0,contrib_menu);
370   main_menu->additem(MN_GOTO, "Options",0,options_menu);
371   main_menu->additem(MN_ACTION,"Level editor",0,0);
372   main_menu->additem(MN_ACTION,"Credits",0,0);
373   main_menu->additem(MN_ACTION,"Quit",0,0);
374
375   options_menu->additem(MN_LABEL,"Options",0,0);
376   options_menu->additem(MN_HL,"",0,0);
377 #ifndef NOOPENGL
378   options_menu->additem(MN_TOGGLE,"OpenGL",use_gl,0);
379 #else
380   options_menu->additem(MN_DEACTIVE,"OpenGL (not supported)",use_gl,0);
381 #endif
382   options_menu->additem(MN_TOGGLE,"Fullscreen",use_fullscreen,0);
383   if(audio_device)
384     {
385       options_menu->additem(MN_TOGGLE,"Sound     ",use_sound,0);
386       options_menu->additem(MN_TOGGLE,"Music     ",use_music,0);
387     }
388   else
389     {
390       options_menu->additem(MN_DEACTIVE,"Sound     ",use_sound,0);
391       options_menu->additem(MN_DEACTIVE,"Music     ",use_music,0);
392     }
393   options_menu->additem(MN_TOGGLE,"Show FPS  ",show_fps,0);
394   options_menu->additem(MN_GOTO,"Controls  ",0,options_controls_menu);
395   options_menu->additem(MN_HL,"",0,0);
396   options_menu->additem(MN_BACK,"Back",0,0);
397   
398   options_controls_menu->additem(MN_LABEL,"Controls",0,0);
399   options_controls_menu->additem(MN_HL,"",0,0);
400   //FIXME:options_controls_menu->additem(MN_CONTROLFIELD,"Move Right", tux.keymap.right,0);
401   options_controls_menu->additem(MN_HL,"",0,0);
402   options_controls_menu->additem(MN_BACK,"Back",0,0);
403
404   load_game_menu->additem(MN_LABEL,"Start Game",0,0);
405   load_game_menu->additem(MN_HL,"",0,0);
406   load_game_menu->additem(MN_DEACTIVE,"Slot 1",0,0);
407   load_game_menu->additem(MN_DEACTIVE,"Slot 2",0,0);
408   load_game_menu->additem(MN_DEACTIVE,"Slot 3",0,0);
409   load_game_menu->additem(MN_DEACTIVE,"Slot 4",0,0);
410   load_game_menu->additem(MN_DEACTIVE,"Slot 5",0,0);
411   load_game_menu->additem(MN_HL,"",0,0);
412   load_game_menu->additem(MN_BACK,"Back",0,0);
413
414   save_game_menu->additem(MN_LABEL,"Save Game",0,0);
415   save_game_menu->additem(MN_HL,"",0,0);
416   save_game_menu->additem(MN_DEACTIVE,"Slot 1",0,0);
417   save_game_menu->additem(MN_DEACTIVE,"Slot 2",0,0);
418   save_game_menu->additem(MN_DEACTIVE,"Slot 3",0,0);
419   save_game_menu->additem(MN_DEACTIVE,"Slot 4",0,0);
420   save_game_menu->additem(MN_DEACTIVE,"Slot 5",0,0);
421   save_game_menu->additem(MN_HL,"",0,0);
422   save_game_menu->additem(MN_BACK,"Back",0,0);
423
424   game_menu->additem(MN_LABEL,"InGame Menu",0,0);
425   game_menu->additem(MN_HL,"",0,0);
426   game_menu->additem(MN_ACTION,"Return To Game",0,0);
427   game_menu->additem(MN_GOTO,"Save Game",0,save_game_menu);
428   game_menu->additem(MN_GOTO,"Load Game",0,load_game_menu);
429   game_menu->additem(MN_GOTO,"Options",0,options_menu);
430   game_menu->additem(MN_HL,"",0,0);
431   game_menu->additem(MN_ACTION,"Quit Game",0,0);
432
433   worldmap_menu->additem(MN_LABEL,"Worldmap Menu",0,0);
434   worldmap_menu->additem(MN_HL,"",0,0);
435   worldmap_menu->additem(MN_ACTION,"Return To Game",0,0);
436   worldmap_menu->additem(MN_GOTO,"Options",0,options_menu);
437   worldmap_menu->additem(MN_HL,"",0,0);
438   worldmap_menu->additem(MN_ACTION,"Quit Game",0,0);
439
440   highscore_menu->additem(MN_TEXTFIELD,"Enter your name:",0,0);
441 }
442
443 void update_load_save_game_menu(Menu* pmenu, int load)
444 {
445   for(int i = 2; i < 7; ++i)
446     {
447       // FIXME: Insert a real savegame struct/class here instead of
448       // doing string vodoo
449       std::string tmp = slotinfo(i-1);
450
451       if(load && tmp.length() == strlen("Slot X - Free"))
452         pmenu->item[i].kind = MN_ACTION;
453       else
454         pmenu->item[i].kind = MN_ACTION;
455       pmenu->item[i].change_text(tmp.c_str());
456     }
457 }
458
459 bool process_load_game_menu()
460 {
461   int slot = load_game_menu->check();
462
463   if(slot != -1)
464     {
465       // FIXME: Insert a real savegame struct/class here instead of
466       // doing string vodoo
467       std::string tmp = slotinfo(slot-1);
468
469       if (tmp.length() == strlen("Slot X - Free"))
470         { // Slot is free, so start a new game
471           worldmap_run();
472           
473           show_menu = true;
474           Menu::set_current(main_menu);
475         }
476       else
477         { 
478           puts("Warning: Loading games isn't supported at the moment");
479         }
480       st_pause_ticks_stop();
481       return true;
482     }
483   else
484     {
485       return false;
486     }
487 }
488
489 /* Handle changes made to global settings in the options menu. */
490 void process_options_menu(void)
491 {
492   switch (options_menu->check())
493     {
494     case 2:
495 #ifndef NOOPENGL
496       if(use_gl != options_menu->item[2].toggled)
497         {
498           use_gl = !use_gl;
499           st_video_setup();
500         }
501 #endif
502       break;
503     case 3:
504       if(use_fullscreen != options_menu->item[3].toggled)
505         {
506           use_fullscreen = !use_fullscreen;
507           st_video_setup();
508         }
509       break;
510     case 4:
511       if(use_sound != options_menu->item[4].toggled)
512         use_sound = !use_sound;
513       break;
514     case 5:
515       if(use_music != options_menu->item[5].toggled)
516         {
517           if(use_music)
518             {
519               if(playing_music())
520                 {
521                   halt_music();
522                 }
523               use_music = false;
524             }
525           else
526             {
527               use_music = true;
528               if (!playing_music())
529                 {
530                   play_current_music();
531                 }
532             }
533         }
534       break;
535     case 6:
536       if(show_fps != options_menu->item[6].toggled)
537         show_fps = !show_fps;
538       break;
539     }
540 }
541
542 void st_general_setup(void)
543 {
544   /* Seed random number generator: */
545
546   srand(SDL_GetTicks());
547
548   /* Set icon image: */
549
550   seticon();
551
552   /* Unicode needed for input handling: */
553
554   SDL_EnableUNICODE(1);
555
556   /* Load global images: */
557
558   black_text  = new Text(datadir + "/images/status/letters-black.png", TEXT_TEXT, 16,18);
559   gold_text   = new Text(datadir + "/images/status/letters-gold.png", TEXT_TEXT, 16,18);
560   blue_text   = new Text(datadir + "/images/status/letters-blue.png", TEXT_TEXT, 16,18);
561   red_text    = new Text(datadir + "/images/status/letters-red.png", TEXT_TEXT, 16,18);
562   white_text  = new Text(datadir + "/images/status/letters-white.png", TEXT_TEXT, 16,18);
563   white_small_text = new Text(datadir + "/images/status/letters-white-small.png", TEXT_TEXT, 8,9);
564   white_big_text   = new Text(datadir + "/images/status/letters-white-big.png", TEXT_TEXT, 20,23);
565   yellow_nums = new Text(datadir + "/images/status/numbers.png", TEXT_NUM, 32,32);
566
567   /* Load GUI/menu images: */
568   checkbox = new Surface(datadir + "/images/status/checkbox.png", USE_ALPHA);
569   checkbox_checked = new Surface(datadir + "/images/status/checkbox-checked.png", USE_ALPHA);
570   back = new Surface(datadir + "/images/status/back.png", USE_ALPHA);
571   arrow_left = new Surface(datadir + "/images/icons/left.png", USE_ALPHA);
572   arrow_right = new Surface(datadir + "/images/icons/right.png", USE_ALPHA);
573
574   /* Load the mouse-cursor */
575   mouse_cursor = new MouseCursor( datadir + "/images/status/mousecursor.png",1);
576   
577 }
578
579 void st_general_free(void)
580 {
581
582   /* Free global images: */
583
584   delete black_text;
585   delete gold_text;
586   delete white_text;
587   delete blue_text;
588   delete red_text;
589   delete white_small_text;
590   delete white_big_text;
591
592   /* Free GUI/menu images: */
593   delete checkbox;
594   delete checkbox_checked;
595   delete back;
596   delete arrow_left;
597   delete arrow_right;
598
599   /* Free mouse-cursor */
600   delete mouse_cursor;
601   
602   /* Free menus */
603   delete main_menu;
604   delete game_menu;
605   delete options_menu;
606   delete highscore_menu;
607   delete save_game_menu;
608   delete load_game_menu;
609 }
610
611 void st_video_setup(void)
612 {
613   if(screen != NULL)
614     SDL_FreeSurface(screen);
615
616   /* Init SDL Video: */
617
618   if (SDL_Init(SDL_INIT_VIDEO) < 0)
619     {
620       fprintf(stderr,
621               "\nError: I could not initialize video!\n"
622               "The Simple DirectMedia error that occured was:\n"
623               "%s\n\n", SDL_GetError());
624       exit(1);
625     }
626
627   /* Open display: */
628   if(use_gl)
629     st_video_setup_gl();
630   else
631     st_video_setup_sdl();
632
633   Surface::reload_all();
634
635   /* Set window manager stuff: */
636   SDL_WM_SetCaption("SuperTux " VERSION, "SuperTux");
637 }
638
639 void st_video_setup_sdl(void)
640 {
641   SDL_FreeSurface(screen);
642
643   if (use_fullscreen)
644     {
645       screen = SDL_SetVideoMode(640, 480, 0, SDL_FULLSCREEN ) ; /* | SDL_HWSURFACE); */
646       if (screen == NULL)
647         {
648           fprintf(stderr,
649                   "\nWarning: I could not set up fullscreen video for "
650                   "640x480 mode.\n"
651                   "The Simple DirectMedia error that occured was:\n"
652                   "%s\n\n", SDL_GetError());
653           use_fullscreen = false;
654         }
655     }
656   else
657     {
658       screen = SDL_SetVideoMode(640, 480, 0, SDL_HWSURFACE | SDL_DOUBLEBUF );
659
660       if (screen == NULL)
661         {
662           fprintf(stderr,
663                   "\nError: I could not set up video for 640x480 mode.\n"
664                   "The Simple DirectMedia error that occured was:\n"
665                   "%s\n\n", SDL_GetError());
666           exit(1);
667         }
668     }
669 }
670
671 void st_video_setup_gl(void)
672 {
673 #ifndef NOOPENGL
674
675   SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
676   SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
677   SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
678   SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
679   SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
680
681   if (use_fullscreen)
682     {
683       screen = SDL_SetVideoMode(640, 480, 0, SDL_FULLSCREEN | SDL_OPENGL) ; /* | SDL_HWSURFACE); */
684       if (screen == NULL)
685         {
686           fprintf(stderr,
687                   "\nWarning: I could not set up fullscreen video for "
688                   "640x480 mode.\n"
689                   "The Simple DirectMedia error that occured was:\n"
690                   "%s\n\n", SDL_GetError());
691           use_fullscreen = false;
692         }
693     }
694   else
695     {
696       screen = SDL_SetVideoMode(640, 480, 0, SDL_OPENGL);
697
698       if (screen == NULL)
699         {
700           fprintf(stderr,
701                   "\nError: I could not set up video for 640x480 mode.\n"
702                   "The Simple DirectMedia error that occured was:\n"
703                   "%s\n\n", SDL_GetError());
704           exit(1);
705         }
706     }
707
708   /*
709    * Set up OpenGL for 2D rendering.
710    */
711   glDisable(GL_DEPTH_TEST);
712   glDisable(GL_CULL_FACE);
713
714   glViewport(0, 0, screen->w, screen->h);
715   glMatrixMode(GL_PROJECTION);
716   glLoadIdentity();
717   glOrtho(0, screen->w, screen->h, 0, -1.0, 1.0);
718
719   glMatrixMode(GL_MODELVIEW);
720   glLoadIdentity();
721   glTranslatef(0.0f, 0.0f, 0.0f);
722
723 #endif
724
725 }
726
727 void st_joystick_setup(void)
728 {
729
730   /* Init Joystick: */
731
732   use_joystick = true;
733
734   if (SDL_Init(SDL_INIT_JOYSTICK) < 0)
735     {
736       fprintf(stderr, "Warning: I could not initialize joystick!\n"
737               "The Simple DirectMedia error that occured was:\n"
738               "%s\n\n", SDL_GetError());
739
740       use_joystick = false;
741     }
742   else
743     {
744       /* Open joystick: */
745       if (SDL_NumJoysticks() <= 0)
746         {
747           fprintf(stderr, "Warning: No joysticks are available.\n");
748
749           use_joystick = false;
750         }
751       else
752         {
753           js = SDL_JoystickOpen(joystick_num);
754
755           if (js == NULL)
756             {
757               fprintf(stderr, "Warning: Could not open joystick %d.\n"
758                       "The Simple DirectMedia error that occured was:\n"
759                       "%s\n\n", joystick_num, SDL_GetError());
760
761               use_joystick = false;
762             }
763           else
764             {
765               /* Check for proper joystick configuration: */
766
767               if (SDL_JoystickNumAxes(js) < 2)
768                 {
769                   fprintf(stderr,
770                           "Warning: Joystick does not have enough axes!\n");
771
772                   use_joystick = false;
773                 }
774               else
775                 {
776                   if (SDL_JoystickNumButtons(js) < 2)
777                     {
778                       fprintf(stderr,
779                               "Warning: "
780                               "Joystick does not have enough buttons!\n");
781
782                       use_joystick = false;
783                     }
784                 }
785             }
786         }
787     }
788 }
789
790 void st_audio_setup(void)
791 {
792
793   /* Init SDL Audio silently even if --disable-sound : */
794
795   if (audio_device)
796     {
797       if (SDL_Init(SDL_INIT_AUDIO) < 0)
798         {
799           /* only print out message if sound or music
800              was not disabled at command-line
801            */
802           if (use_sound || use_music)
803             {
804               fprintf(stderr,
805                       "\nWarning: I could not initialize audio!\n"
806                       "The Simple DirectMedia error that occured was:\n"
807                       "%s\n\n", SDL_GetError());
808             }
809           /* keep the programming logic the same :-)
810              because in this case, use_sound & use_music' values are ignored
811              when there's no available audio device
812           */
813           use_sound = false;
814           use_music = false;
815           audio_device = false;
816         }
817     }
818
819
820   /* Open sound silently regarless the value of "use_sound": */
821
822   if (audio_device)
823     {
824       if (open_audio(44100, AUDIO_S16, 2, 2048) < 0)
825         {
826           /* only print out message if sound or music
827              was not disabled at command-line
828            */
829           if (use_sound || use_music)
830             {
831               fprintf(stderr,
832                       "\nWarning: I could not set up audio for 44100 Hz "
833                       "16-bit stereo.\n"
834                       "The Simple DirectMedia error that occured was:\n"
835                       "%s\n\n", SDL_GetError());
836             }
837           use_sound = false;
838           use_music = false;
839           audio_device = false;
840         }
841     }
842
843 }
844
845
846 /* --- SHUTDOWN --- */
847
848 void st_shutdown(void)
849 {
850   close_audio();
851   SDL_Quit();
852   saveconfig();
853 }
854
855 /* --- ABORT! --- */
856
857 void st_abort(const std::string& reason, const std::string& details)
858 {
859   fprintf(stderr, "\nError: %s\n%s\n\n", reason.c_str(), details.c_str());
860   st_shutdown();
861   abort();
862 }
863
864
865 /* Set Icon (private) */
866
867 void seticon(void)
868 {
869   int masklen;
870   Uint8 * mask;
871   SDL_Surface * icon;
872
873
874   /* Load icon into a surface: */
875
876   icon = IMG_Load((datadir + "/images/icon.png").c_str());
877   if (icon == NULL)
878     {
879       fprintf(stderr,
880               "\nError: I could not load the icon image: %s%s\n"
881               "The Simple DirectMedia error that occured was:\n"
882               "%s\n\n", datadir.c_str(), "/images/icon.png", SDL_GetError());
883       exit(1);
884     }
885
886
887   /* Create mask: */
888
889   masklen = (((icon -> w) + 7) / 8) * (icon -> h);
890   mask = (Uint8*) malloc(masklen * sizeof(Uint8));
891   memset(mask, 0xFF, masklen);
892
893
894   /* Set icon: */
895
896   SDL_WM_SetIcon(icon, mask);
897
898
899   /* Free icon surface & mask: */
900
901   free(mask);
902   SDL_FreeSurface(icon);
903 }
904
905
906 /* Parse command-line arguments: */
907
908 void parseargs(int argc, char * argv[])
909 {
910   int i;
911
912   loadconfig();
913
914   /* Parse arguments: */
915
916   for (i = 1; i < argc; i++)
917     {
918       if (strcmp(argv[i], "--fullscreen") == 0 ||
919           strcmp(argv[i], "-f") == 0)
920         {
921           /* Use full screen: */
922
923           use_fullscreen = true;
924         }
925       else if (strcmp(argv[i], "--joystick") == 0 || strcmp(argv[i], "-j") == 0)
926         {
927           assert(i+1 < argc);
928           joystick_num = atoi(argv[++i]);
929         }
930       else if (strcmp(argv[i], "--worldmap") == 0)
931         {
932           launch_worldmap_mode = true;
933         }
934       else if (strcmp(argv[i], "--datadir") == 0 
935                || strcmp(argv[i], "-d") == 0 )
936         {
937           assert(i+1 < argc);
938           datadir = argv[++i];
939         }
940       else if (strcmp(argv[i], "--show-fps") == 0)
941         {
942           /* Use full screen: */
943
944           show_fps = true;
945         }
946       else if (strcmp(argv[i], "--opengl") == 0 ||
947                strcmp(argv[i], "-gl") == 0)
948         {
949 #ifndef NOOPENGL
950           /* Use OpengGL: */
951
952           use_gl = true;
953 #endif
954         }
955       else if (strcmp(argv[i], "--sdl") == 0)
956           {
957             use_gl = false;
958           }
959       else if (strcmp(argv[i], "--usage") == 0)
960         {
961           /* Show usage: */
962
963           usage(argv[0], 0);
964         }
965       else if (strcmp(argv[i], "--version") == 0)
966         {
967           /* Show version: */
968           printf("SuperTux " VERSION "\n");
969           exit(0);
970         }
971       else if (strcmp(argv[i], "--disable-sound") == 0)
972         {
973           /* Disable the compiled in sound feature */
974           printf("Sounds disabled \n");
975           use_sound = false;
976         }
977       else if (strcmp(argv[i], "--disable-music") == 0)
978         {
979           /* Disable the compiled in sound feature */
980           printf("Music disabled \n");
981           use_music = false;
982         }
983       else if (strcmp(argv[i], "--debug-mode") == 0)
984         {
985           /* Enable the debug-mode */
986           debug_mode = true;
987
988         }
989       else if (strcmp(argv[i], "--help") == 0)
990         {     /* Show help: */
991           puts("Super Tux " VERSION "\n"
992                "  Please see the file \"README.txt\" for more details.\n");
993           printf("Usage: %s [OPTIONS] FILENAME\n\n", argv[0]);
994           puts("Display Options:\n"
995                "  --fullscreen        Run in fullscreen mode.\n"
996                "  --opengl            If opengl support was compiled in, this will enable\n"
997                "                      the EXPERIMENTAL OpenGL mode.\n"
998                "  --sdl               Use non-opengl renderer\n"
999                "\n"
1000                "Sound Options:\n"
1001                "  --disable-sound     If sound support was compiled in,  this will\n"
1002                "                      disable sound for this session of the game.\n"
1003                "  --disable-music     Like above, but this will disable music.\n"
1004                "\n"
1005                "Misc Options:\n"
1006                "  -j, --joystick NUM  Use joystick NUM (default: 0)\n" 
1007                "  --worldmap          Start in worldmap-mode (EXPERIMENTAL)\n"          
1008                "  -d, --datadir DIR   Load Game data from DIR (default: automatic)\n"
1009                "  --debug-mode        Enables the debug-mode, which is useful for developers.\n"
1010                "  --help              Display a help message summarizing command-line\n"
1011                "                      options, license and game controls.\n"
1012                "  --usage             Display a brief message summarizing command-line options.\n"
1013                "  --version           Display the version of SuperTux you're running.\n\n"
1014                );
1015           exit(0);
1016         }
1017       else if (argv[i][0] != '-')
1018         {
1019           level_startup_file = argv[i];
1020         }
1021       else
1022         {
1023           /* Unknown - complain! */
1024
1025           usage(argv[0], 1);
1026         }
1027     }
1028 }
1029
1030
1031 /* Display usage: */
1032
1033 void usage(char * prog, int ret)
1034 {
1035   FILE * fi;
1036
1037
1038   /* Determine which stream to write to: */
1039
1040   if (ret == 0)
1041     fi = stdout;
1042   else
1043     fi = stderr;
1044
1045
1046   /* Display the usage message: */
1047
1048   fprintf(fi, "Usage: %s [--fullscreen] [--opengl] [--disable-sound] [--disable-music] [--debug-mode] | [--usage | --help | --version] [--worldmap] FILENAME\n",
1049           prog);
1050
1051
1052   /* Quit! */
1053
1054   exit(ret);
1055 }
1056