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