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