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