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