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