- turned LEFT/RIGHT defines into enum, turned BadGuyModes into enum
[supertux.git] / src / setup.cpp
1 //  $Id$
2 //
3 //  SuperTux -  A Jump'n Run
4 //  Copyright (C) 2000 Bill Kendrick <bill@newbreedsoftware.com>
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
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19
20 #include <assert.h>
21 #include <stdio.h>
22 #include <iostream>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <errno.h>
27 #include <unistd.h>
28 #include <SDL.h>
29 #include <SDL_image.h>
30 #ifndef NOOPENGL
31 #include <SDL_opengl.h>
32 #endif
33
34 #include <sys/stat.h>
35 #include <sys/types.h>
36 #include <dirent.h>
37 #ifndef WIN32
38 #include <libgen.h>
39 #endif
40 #include <ctype.h>
41
42 #include "defines.h"
43 #include "globals.h"
44 #include "setup.h"
45 #include "screen.h"
46 #include "texture.h"
47 #include "menu.h"
48 #include "gameloop.h"
49 #include "configfile.h"
50 #include "scene.h"
51 #include "worldmap.h"
52
53 #ifdef WIN32
54 #define mkdir(dir, mode)    mkdir(dir)
55 // on win32 we typically don't want LFS paths
56 #undef DATA_PREFIX
57 #define DATA_PREFIX "./data/"
58 #endif
59
60 /* Local function prototypes: */
61
62 void seticon(void);
63 void usage(char * prog, int ret);
64
65 /* Does the given file exist and is it accessible? */
66 int faccessible(const char *filename)
67 {
68   struct stat filestat;
69   if (stat(filename, &filestat) == -1)
70     {
71       return false;
72     }
73   else
74     {
75       if(S_ISREG(filestat.st_mode))
76         return true;
77       else
78         return false;
79     }
80 }
81
82 /* Can we write to this location? */
83 int fwriteable(const char *filename)
84 {
85   FILE* fi;
86   fi = fopen(filename, "wa");
87   if (fi == NULL)
88     {
89       return false;
90     }
91   return true;
92 }
93
94 /* Makes sure a directory is created in either the SuperTux home directory or the SuperTux base directory.*/
95 int fcreatedir(const char* relative_dir)
96 {
97   char path[1024];
98   snprintf(path, 1024, "%s/%s/", st_dir, relative_dir);
99   if(mkdir(path,0755) != 0)
100     {
101       snprintf(path, 1024, "%s/%s/", datadir.c_str(), relative_dir);
102       if(mkdir(path,0755) != 0)
103         {
104           return false;
105         }
106       else
107         {
108           return true;
109         }
110     }
111   else
112     {
113       return true;
114     }
115 }
116
117 FILE * opendata(const char * rel_filename, const char * mode)
118 {
119   char * filename = NULL;
120   FILE * fi;
121
122   filename = (char *) malloc(sizeof(char) * (strlen(st_dir) +
123                                              strlen(rel_filename) + 1));
124
125   strcpy(filename, st_dir);
126   /* Open the high score file: */
127
128   strcat(filename, rel_filename);
129
130   /* Try opening the file: */
131   fi = fopen(filename, mode);
132
133   if (fi == NULL)
134     {
135       fprintf(stderr, "Warning: Unable to open the file \"%s\" ", filename);
136
137       if (strcmp(mode, "r") == 0)
138         fprintf(stderr, "for read!!!\n");
139       else if (strcmp(mode, "w") == 0)
140         fprintf(stderr, "for write!!!\n");
141     }
142   free( filename );
143
144   return(fi);
145 }
146
147 /* Get all names of sub-directories in a certain directory. */
148 /* Returns the number of sub-directories found. */
149 /* Note: The user has to free the allocated space. */
150 string_list_type dsubdirs(const char *rel_path,const  char* expected_file)
151 {
152   DIR *dirStructP;
153   struct dirent *direntp;
154   string_list_type sdirs;
155   char filename[1024];
156   char path[1024];
157
158   string_list_init(&sdirs);
159   sprintf(path,"%s/%s",st_dir,rel_path);
160   if((dirStructP = opendir(path)) != NULL)
161     {
162       while((direntp = readdir(dirStructP)) != NULL)
163         {
164           char absolute_filename[1024];
165           struct stat buf;
166
167           sprintf(absolute_filename, "%s/%s", path, direntp->d_name);
168
169           if (stat(absolute_filename, &buf) == 0 && S_ISDIR(buf.st_mode))
170             {
171               if(expected_file != NULL)
172                 {
173                   sprintf(filename,"%s/%s/%s",path,direntp->d_name,expected_file);
174                   if(!faccessible(filename))
175                     continue;
176                 }
177
178               string_list_add_item(&sdirs,direntp->d_name);
179             }
180         }
181       closedir(dirStructP);
182     }
183
184   sprintf(path,"%s/%s",datadir.c_str(),rel_path);
185   if((dirStructP = opendir(path)) != NULL)
186     {
187       while((direntp = readdir(dirStructP)) != NULL)
188         {
189           char absolute_filename[1024];
190           struct stat buf;
191
192           sprintf(absolute_filename, "%s/%s", path, direntp->d_name);
193
194           if (stat(absolute_filename, &buf) == 0 && S_ISDIR(buf.st_mode))
195             {
196               if(expected_file != NULL)
197                 {
198                   sprintf(filename,"%s/%s/%s",path,direntp->d_name,expected_file);
199                   if(!faccessible(filename))
200                     {
201                       continue;
202                     }
203                   else
204                     {
205                       sprintf(filename,"%s/%s/%s/%s",st_dir,rel_path,direntp->d_name,expected_file);
206                       if(faccessible(filename))
207                         continue;
208                     }
209                 }
210
211               string_list_add_item(&sdirs,direntp->d_name);
212             }
213         }
214       closedir(dirStructP);
215     }
216
217   return sdirs;
218 }
219
220 string_list_type dfiles(const char *rel_path, const  char* glob, const  char* exception_str)
221 {
222   DIR *dirStructP;
223   struct dirent *direntp;
224   string_list_type sdirs;
225   char path[1024];
226
227   string_list_init(&sdirs);
228   sprintf(path,"%s/%s",st_dir,rel_path);
229   if((dirStructP = opendir(path)) != NULL)
230     {
231       while((direntp = readdir(dirStructP)) != NULL)
232         {
233           char absolute_filename[1024];
234           struct stat buf;
235
236           sprintf(absolute_filename, "%s/%s", path, direntp->d_name);
237
238           if (stat(absolute_filename, &buf) == 0 && S_ISREG(buf.st_mode))
239             {
240               if(exception_str != NULL)
241                 {
242                   if(strstr(direntp->d_name,exception_str) != NULL)
243                     continue;
244                 }
245               if(glob != NULL)
246                 if(strstr(direntp->d_name,glob) == NULL)
247                   continue;
248
249               string_list_add_item(&sdirs,direntp->d_name);
250             }
251         }
252       closedir(dirStructP);
253     }
254
255   sprintf(path,"%s/%s",datadir.c_str(),rel_path);
256   if((dirStructP = opendir(path)) != NULL)
257     {
258       while((direntp = readdir(dirStructP)) != NULL)
259         {
260           char absolute_filename[1024];
261           struct stat buf;
262
263           sprintf(absolute_filename, "%s/%s", path, direntp->d_name);
264
265           if (stat(absolute_filename, &buf) == 0 && S_ISREG(buf.st_mode))
266             {
267               if(exception_str != NULL)
268                 {
269                   if(strstr(direntp->d_name,exception_str) != NULL)
270                     continue;
271                 }
272               if(glob != NULL)
273                 if(strstr(direntp->d_name,glob) == NULL)
274                   continue;
275
276               string_list_add_item(&sdirs,direntp->d_name);
277             }
278         }
279       closedir(dirStructP);
280     }
281
282   return sdirs;
283 }
284
285 void free_strings(char **strings, int num)
286 {
287   int i;
288   for(i=0; i < num; ++i)
289     free(strings[i]);
290 }
291
292 /* --- SETUP --- */
293 /* Set SuperTux configuration and save directories */
294 void st_directory_setup(void)
295 {
296   char *home;
297   char str[1024];
298   /* Get home directory (from $HOME variable)... if we can't determine it,
299      use the current directory ("."): */
300   if (getenv("HOME") != NULL)
301     home = getenv("HOME");
302   else
303     home = ".";
304
305   st_dir = (char *) malloc(sizeof(char) * (strlen(home) +
306                                            strlen("/.supertux") + 1));
307   strcpy(st_dir, home);
308   strcat(st_dir, "/.supertux");
309
310   /* Remove .supertux config-file from old SuperTux versions */
311   if(faccessible(st_dir))
312     {
313       remove
314         (st_dir);
315     }
316
317   st_save_dir = (char *) malloc(sizeof(char) * (strlen(st_dir) + strlen("/save") + 1));
318
319   strcpy(st_save_dir,st_dir);
320   strcat(st_save_dir,"/save");
321
322   /* Create them. In the case they exist they won't destroy anything. */
323   mkdir(st_dir, 0755);
324   mkdir(st_save_dir, 0755);
325
326   sprintf(str, "%s/levels", st_dir);
327   mkdir(str, 0755);
328
329   // User has not that a datadir, so we try some magic
330   if (datadir.empty())
331     {
332 #ifndef WIN32
333       // Detect datadir
334       char exe_file[PATH_MAX];
335       if (readlink("/proc/self/exe", exe_file, PATH_MAX) < 0)
336         {
337           puts("Couldn't read /proc/self/exe, using default path: " DATA_PREFIX);
338           datadir = DATA_PREFIX;
339         }
340       else
341         {
342           std::string exedir = std::string(dirname(exe_file)) + "/";
343           
344           datadir = exedir + "../data/"; // SuperTux run from source dir
345           if (access(datadir.c_str(), F_OK) != 0)
346             {
347               datadir = exedir + "../share/supertux/"; // SuperTux run from PATH
348               if (access(datadir.c_str(), F_OK) != 0) 
349                 { // If all fails, fall back to compiled path
350                   datadir = DATA_PREFIX; 
351                 }
352             }
353         }
354 #else
355   datadir = DATA_PREFIX;
356 #endif
357     }
358   printf("Datadir: %s\n", datadir.c_str());
359 }
360
361 /* Create and setup menus. */
362 void st_menu(void)
363 {
364   main_menu      = new Menu();
365   options_menu   = new Menu();
366   options_controls_menu   = new Menu();
367   load_game_menu = new Menu();
368   save_game_menu = new Menu();
369   game_menu      = new Menu();
370   highscore_menu = new Menu();
371   contrib_menu   = new Menu();
372   contrib_subset_menu   = new Menu();
373   worldmap_menu  = new Menu();
374
375   main_menu->set_pos(screen->w/2, 335);
376   main_menu->additem(MN_GOTO, "Start Game",0,load_game_menu);
377   main_menu->additem(MN_GOTO, "Contrib Levels",0,contrib_menu);
378   main_menu->additem(MN_GOTO, "Options",0,options_menu);
379   main_menu->additem(MN_ACTION,"Level editor",0,0);
380   main_menu->additem(MN_ACTION,"Credits",0,0);
381   main_menu->additem(MN_ACTION,"Quit",0,0);
382
383   options_menu->additem(MN_LABEL,"Options",0,0);
384   options_menu->additem(MN_HL,"",0,0);
385 #ifndef NOOPENGL
386   options_menu->additem(MN_TOGGLE,"OpenGL",use_gl,0);
387 #else
388   options_menu->additem(MN_DEACTIVE,"OpenGL (not supported)",use_gl,0);
389 #endif
390   options_menu->additem(MN_TOGGLE,"Fullscreen",use_fullscreen,0);
391   if(audio_device)
392     {
393       options_menu->additem(MN_TOGGLE,"Sound     ",use_sound,0);
394       options_menu->additem(MN_TOGGLE,"Music     ",use_music,0);
395     }
396   else
397     {
398       options_menu->additem(MN_DEACTIVE,"Sound     ",use_sound,0);
399       options_menu->additem(MN_DEACTIVE,"Music     ",use_music,0);
400     }
401   options_menu->additem(MN_TOGGLE,"Show FPS  ",show_fps,0);
402   options_menu->additem(MN_GOTO,"Controls  ",0,options_controls_menu);
403   options_menu->additem(MN_HL,"",0,0);
404   options_menu->additem(MN_BACK,"Back",0,0);
405   
406   options_controls_menu->additem(MN_LABEL,"Controls",0,0);
407   options_controls_menu->additem(MN_HL,"",0,0);
408   //FIXME:options_controls_menu->additem(MN_CONTROLFIELD,"Move Right", tux.keymap.right,0);
409   options_controls_menu->additem(MN_HL,"",0,0);
410   options_controls_menu->additem(MN_BACK,"Back",0,0);
411
412   load_game_menu->additem(MN_LABEL,"Start Game",0,0);
413   load_game_menu->additem(MN_HL,"",0,0);
414   load_game_menu->additem(MN_DEACTIVE,"Slot 1",0,0);
415   load_game_menu->additem(MN_DEACTIVE,"Slot 2",0,0);
416   load_game_menu->additem(MN_DEACTIVE,"Slot 3",0,0);
417   load_game_menu->additem(MN_DEACTIVE,"Slot 4",0,0);
418   load_game_menu->additem(MN_DEACTIVE,"Slot 5",0,0);
419   load_game_menu->additem(MN_HL,"",0,0);
420   load_game_menu->additem(MN_BACK,"Back",0,0);
421
422   save_game_menu->additem(MN_LABEL,"Save Game",0,0);
423   save_game_menu->additem(MN_HL,"",0,0);
424   save_game_menu->additem(MN_DEACTIVE,"Slot 1",0,0);
425   save_game_menu->additem(MN_DEACTIVE,"Slot 2",0,0);
426   save_game_menu->additem(MN_DEACTIVE,"Slot 3",0,0);
427   save_game_menu->additem(MN_DEACTIVE,"Slot 4",0,0);
428   save_game_menu->additem(MN_DEACTIVE,"Slot 5",0,0);
429   save_game_menu->additem(MN_HL,"",0,0);
430   save_game_menu->additem(MN_BACK,"Back",0,0);
431
432   game_menu->additem(MN_LABEL,"Pause",0,0);
433   game_menu->additem(MN_HL,"",0,0);
434   game_menu->additem(MN_ACTION,"Continue",0,0);
435   game_menu->additem(MN_GOTO,"Options",0,options_menu);
436   game_menu->additem(MN_HL,"",0,0);
437   game_menu->additem(MN_ACTION,"Abort Level",0,0);
438
439   worldmap_menu->additem(MN_LABEL,"Pause",0,0);
440   worldmap_menu->additem(MN_HL,"",0,0);
441   worldmap_menu->additem(MN_ACTION,"Continue",0,0);
442   worldmap_menu->additem(MN_ACTION,"Save",0,0);
443   worldmap_menu->additem(MN_GOTO,"Options",0,options_menu);
444   worldmap_menu->additem(MN_HL,"",0,0);
445   worldmap_menu->additem(MN_ACTION,"Quit Game",0,0);
446
447   highscore_menu->additem(MN_TEXTFIELD,"Enter your name:",0,0);
448 }
449
450 void update_load_save_game_menu(Menu* pmenu)
451 {
452   for(int i = 2; i < 7; ++i)
453     {
454       // FIXME: Insert a real savegame struct/class here instead of
455       // doing string vodoo
456       std::string tmp = slotinfo(i - 1);
457       pmenu->item[i].kind = MN_ACTION;
458       pmenu->item[i].change_text(tmp.c_str());
459     }
460 }
461
462 bool process_load_game_menu()
463 {
464   int slot = load_game_menu->check();
465
466   if(slot != -1 && load_game_menu->get_item(slot).kind == MN_ACTION)
467     {
468       WorldMapNS::WorldMap worldmap;
469
470       char slotfile[1024];
471       snprintf(slotfile, 1024, "%s/slot%d.stsg", st_save_dir, slot-1);
472      
473       // Load the game or at least set the savegame_file variable
474       worldmap.loadgame(slotfile);
475
476       worldmap.display();
477       
478       Menu::set_current(main_menu);
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               if (SDL_JoystickNumAxes(js) < 2)
766                 {
767                   fprintf(stderr,
768                           "Warning: Joystick does not have enough axes!\n");
769
770                   use_joystick = false;
771                 }
772               else
773                 {
774                   if (SDL_JoystickNumButtons(js) < 2)
775                     {
776                       fprintf(stderr,
777                               "Warning: "
778                               "Joystick does not have enough buttons!\n");
779
780                       use_joystick = false;
781                     }
782                 }
783             }
784         }
785     }
786 }
787
788 void st_audio_setup(void)
789 {
790
791   /* Init SDL Audio silently even if --disable-sound : */
792
793   if (audio_device)
794     {
795       if (SDL_Init(SDL_INIT_AUDIO) < 0)
796         {
797           /* only print out message if sound or music
798              was not disabled at command-line
799            */
800           if (use_sound || use_music)
801             {
802               fprintf(stderr,
803                       "\nWarning: I could not initialize audio!\n"
804                       "The Simple DirectMedia error that occured was:\n"
805                       "%s\n\n", SDL_GetError());
806             }
807           /* keep the programming logic the same :-)
808              because in this case, use_sound & use_music' values are ignored
809              when there's no available audio device
810           */
811           use_sound = false;
812           use_music = false;
813           audio_device = false;
814         }
815     }
816
817
818   /* Open sound silently regarless the value of "use_sound": */
819
820   if (audio_device)
821     {
822       if (open_audio(44100, AUDIO_S16, 2, 2048) < 0)
823         {
824           /* only print out message if sound or music
825              was not disabled at command-line
826            */
827           if (use_sound || use_music)
828             {
829               fprintf(stderr,
830                       "\nWarning: I could not set up audio for 44100 Hz "
831                       "16-bit stereo.\n"
832                       "The Simple DirectMedia error that occured was:\n"
833                       "%s\n\n", SDL_GetError());
834             }
835           use_sound = false;
836           use_music = false;
837           audio_device = false;
838         }
839     }
840
841 }
842
843
844 /* --- SHUTDOWN --- */
845
846 void st_shutdown(void)
847 {
848   close_audio();
849   SDL_Quit();
850   saveconfig();
851 }
852
853 /* --- ABORT! --- */
854
855 void st_abort(const std::string& reason, const std::string& details)
856 {
857   fprintf(stderr, "\nError: %s\n%s\n\n", reason.c_str(), details.c_str());
858   st_shutdown();
859   abort();
860 }
861
862
863 /* Set Icon (private) */
864
865 void seticon(void)
866 {
867   int masklen;
868   Uint8 * mask;
869   SDL_Surface * icon;
870
871
872   /* Load icon into a surface: */
873
874   icon = IMG_Load((datadir + "/images/icon.png").c_str());
875   if (icon == NULL)
876     {
877       fprintf(stderr,
878               "\nError: I could not load the icon image: %s%s\n"
879               "The Simple DirectMedia error that occured was:\n"
880               "%s\n\n", datadir.c_str(), "/images/icon.png", SDL_GetError());
881       exit(1);
882     }
883
884
885   /* Create mask: */
886
887   masklen = (((icon -> w) + 7) / 8) * (icon -> h);
888   mask = (Uint8*) malloc(masklen * sizeof(Uint8));
889   memset(mask, 0xFF, masklen);
890
891
892   /* Set icon: */
893
894   SDL_WM_SetIcon(icon, mask);
895
896
897   /* Free icon surface & mask: */
898
899   free(mask);
900   SDL_FreeSurface(icon);
901 }
902
903
904 /* Parse command-line arguments: */
905
906 void parseargs(int argc, char * argv[])
907 {
908   int i;
909
910   loadconfig();
911
912   /* Parse arguments: */
913
914   for (i = 1; i < argc; i++)
915     {
916       if (strcmp(argv[i], "--fullscreen") == 0 ||
917           strcmp(argv[i], "-f") == 0)
918         {
919           /* Use full screen: */
920
921           use_fullscreen = true;
922         }
923       else if (strcmp(argv[i], "--joystick") == 0 || strcmp(argv[i], "-j") == 0)
924         {
925           assert(i+1 < argc);
926           joystick_num = atoi(argv[++i]);
927         }
928       else if (strcmp(argv[i], "--joymap") == 0)
929         {
930           assert(i+1 < argc);
931           if (sscanf(argv[++i],
932                      "%d:%d:%d:%d:%d", 
933                      &joystick_keymap.x_axis, 
934                      &joystick_keymap.y_axis, 
935                      &joystick_keymap.a_button, 
936                      &joystick_keymap.b_button, 
937                      &joystick_keymap.start_button) != 5)
938             {
939               puts("Warning: Invalid or incomplete joymap, should be: 'XAXIS:YAXIS:A:B:START'");
940             }
941           else
942             {
943               std::cout << "Using new joymap:\n"
944                         << "  X-Axis:       " << joystick_keymap.x_axis << "\n"
945                         << "  Y-Axis:       " << joystick_keymap.y_axis << "\n"
946                         << "  A-Button:     " << joystick_keymap.a_button << "\n"
947                         << "  B-Button:     " << joystick_keymap.b_button << "\n"
948                         << "  Start-Button: " << joystick_keymap.start_button << std::endl;
949             }
950         }
951       else if (strcmp(argv[i], "--worldmap") == 0)
952         {
953           launch_worldmap_mode = true;
954         }
955       else if (strcmp(argv[i], "--datadir") == 0 
956                || strcmp(argv[i], "-d") == 0 )
957         {
958           assert(i+1 < argc);
959           datadir = argv[++i];
960         }
961       else if (strcmp(argv[i], "--show-fps") == 0)
962         {
963           /* Use full screen: */
964
965           show_fps = true;
966         }
967       else if (strcmp(argv[i], "--opengl") == 0 ||
968                strcmp(argv[i], "-gl") == 0)
969         {
970 #ifndef NOOPENGL
971           /* Use OpengGL: */
972
973           use_gl = true;
974 #endif
975         }
976       else if (strcmp(argv[i], "--sdl") == 0)
977           {
978             use_gl = false;
979           }
980       else if (strcmp(argv[i], "--usage") == 0)
981         {
982           /* Show usage: */
983
984           usage(argv[0], 0);
985         }
986       else if (strcmp(argv[i], "--version") == 0)
987         {
988           /* Show version: */
989           printf("SuperTux " VERSION "\n");
990           exit(0);
991         }
992       else if (strcmp(argv[i], "--disable-sound") == 0)
993         {
994           /* Disable the compiled in sound feature */
995           printf("Sounds disabled \n");
996           use_sound = false;
997         }
998       else if (strcmp(argv[i], "--disable-music") == 0)
999         {
1000           /* Disable the compiled in sound feature */
1001           printf("Music disabled \n");
1002           use_music = false;
1003         }
1004       else if (strcmp(argv[i], "--debug-mode") == 0)
1005         {
1006           /* Enable the debug-mode */
1007           debug_mode = true;
1008
1009         }
1010       else if (strcmp(argv[i], "--help") == 0)
1011         {     /* Show help: */
1012           puts("Super Tux " VERSION "\n"
1013                "  Please see the file \"README.txt\" for more details.\n");
1014           printf("Usage: %s [OPTIONS] FILENAME\n\n", argv[0]);
1015           puts("Display Options:\n"
1016                "  --fullscreen        Run in fullscreen mode.\n"
1017                "  --opengl            If opengl support was compiled in, this will enable\n"
1018                "                      the EXPERIMENTAL OpenGL mode.\n"
1019                "  --sdl               Use non-opengl renderer\n"
1020                "\n"
1021                "Sound Options:\n"
1022                "  --disable-sound     If sound support was compiled in,  this will\n"
1023                "                      disable sound for this session of the game.\n"
1024                "  --disable-music     Like above, but this will disable music.\n"
1025                "\n"
1026                "Misc Options:\n"
1027                "  -j, --joystick NUM  Use joystick NUM (default: 0)\n" 
1028                "  --joymap XAXIS:YAXIS:A:B:START\n"
1029                "                      Define how joystick buttons and axis should be mapped\n"
1030                "  --worldmap          Start in worldmap-mode (EXPERIMENTAL)\n"          
1031                "  -d, --datadir DIR   Load Game data from DIR (default: automatic)\n"
1032                "  --debug-mode        Enables the debug-mode, which is useful for developers.\n"
1033                "  --help              Display a help message summarizing command-line\n"
1034                "                      options, license and game controls.\n"
1035                "  --usage             Display a brief message summarizing command-line options.\n"
1036                "  --version           Display the version of SuperTux you're running.\n\n"
1037                );
1038           exit(0);
1039         }
1040       else if (argv[i][0] != '-')
1041         {
1042           level_startup_file = argv[i];
1043         }
1044       else
1045         {
1046           /* Unknown - complain! */
1047
1048           usage(argv[0], 1);
1049         }
1050     }
1051 }
1052
1053
1054 /* Display usage: */
1055
1056 void usage(char * prog, int ret)
1057 {
1058   FILE * fi;
1059
1060
1061   /* Determine which stream to write to: */
1062
1063   if (ret == 0)
1064     fi = stdout;
1065   else
1066     fi = stderr;
1067
1068
1069   /* Display the usage message: */
1070
1071   fprintf(fi, "Usage: %s [--fullscreen] [--opengl] [--disable-sound] [--disable-music] [--debug-mode] | [--usage | --help | --version] [--worldmap] FILENAME\n",
1072           prog);
1073
1074
1075   /* Quit! */
1076
1077   exit(ret);
1078 }
1079