Fix awkward requirement for non-zero joystick axis value in gui_stick
[neverball] / ball / main.c
1 /*
2  * Copyright (C) 2003 Robert Kooima
3  *
4  * NEVERBALL is  free software; you can redistribute  it and/or modify
5  * it under the  terms of the GNU General  Public License as published
6  * by the Free  Software Foundation; either version 2  of the License,
7  * or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT  ANY  WARRANTY;  without   even  the  implied  warranty  of
11  * MERCHANTABILITY or  FITNESS FOR A PARTICULAR PURPOSE.   See the GNU
12  * General Public License for more details.
13  */
14
15 /*---------------------------------------------------------------------------*/
16
17 #include <SDL.h>
18 #include <stdio.h>
19 #include <string.h>
20
21 #include "glext.h"
22 #include "config.h"
23 #include "video.h"
24 #include "image.h"
25 #include "audio.h"
26 #include "demo.h"
27 #include "progress.h"
28 #include "gui.h"
29 #include "set.h"
30 #include "tilt.h"
31 #include "fs.h"
32 #include "common.h"
33
34 #include "st_conf.h"
35 #include "st_title.h"
36 #include "st_demo.h"
37 #include "st_level.h"
38 #include "st_pause.h"
39
40 const char TITLE[] = "Neverball " VERSION;
41 const char ICON[] = "icon/neverball.png";
42
43 /*---------------------------------------------------------------------------*/
44
45 static void shot(void)
46 {
47     static char filename[MAXSTR];
48
49     sprintf(filename, "Screenshots/screen%05d.png", config_screenshot());
50     image_snap(filename);
51 }
52
53 /*---------------------------------------------------------------------------*/
54
55 static void toggle_wire(void)
56 {
57     static int wire = 0;
58
59     if (wire)
60     {
61         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
62         glEnable(GL_TEXTURE_2D);
63         glEnable(GL_LIGHTING);
64         wire = 0;
65     }
66     else
67     {
68         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
69         glDisable(GL_TEXTURE_2D);
70         glDisable(GL_LIGHTING);
71         wire = 1;
72     }
73 }
74
75 /*---------------------------------------------------------------------------*/
76
77 static int loop(void)
78 {
79     SDL_Event e;
80     int d = 1;
81     int c;
82
83     /* Process SDL events. */
84
85     while (d && SDL_PollEvent(&e))
86     {
87         switch (e.type)
88         {
89         case SDL_QUIT:
90             return 0;
91
92         case SDL_MOUSEMOTION:
93             st_point(+e.motion.x,
94                      -e.motion.y + config_get_d(CONFIG_HEIGHT),
95                      +e.motion.xrel,
96                      config_get_d(CONFIG_MOUSE_INVERT)
97                      ? +e.motion.yrel : -e.motion.yrel);
98             break;
99
100         case SDL_MOUSEBUTTONDOWN:
101             d = st_click(e.button.button, 1);
102             break;
103
104         case SDL_MOUSEBUTTONUP:
105             d = st_click(e.button.button, 0);
106             break;
107
108         case SDL_KEYDOWN:
109
110             c = e.key.keysym.sym;
111
112             if (config_tst_d(CONFIG_KEY_FORWARD, c))
113                 st_stick(config_get_d(CONFIG_JOYSTICK_AXIS_Y), -JOY_MAX);
114
115             else if (config_tst_d(CONFIG_KEY_BACKWARD, c))
116                 st_stick(config_get_d(CONFIG_JOYSTICK_AXIS_Y), +JOY_MAX);
117
118             else if (config_tst_d(CONFIG_KEY_LEFT, c))
119                 st_stick(config_get_d(CONFIG_JOYSTICK_AXIS_X), -JOY_MAX);
120
121             else if (config_tst_d(CONFIG_KEY_RIGHT, c))
122                 st_stick(config_get_d(CONFIG_JOYSTICK_AXIS_X), +JOY_MAX);
123
124             else switch (c)
125             {
126             case SDLK_F10:   shot();                    break;
127             case SDLK_F9:    config_tgl_d(CONFIG_FPS);  break;
128             case SDLK_F8:    config_tgl_d(CONFIG_NICE); break;
129
130             case SDLK_F7:
131                 if (config_cheat())
132                     toggle_wire();
133                 break;
134
135             case SDLK_RETURN:
136                 d = st_buttn(config_get_d(CONFIG_JOYSTICK_BUTTON_A), 1);
137                 break;
138             case SDLK_ESCAPE:
139                 d = st_buttn(config_get_d(CONFIG_JOYSTICK_BUTTON_EXIT), 1);
140                 break;
141
142             default:
143                 if (SDL_EnableUNICODE(-1))
144                     d = st_keybd(e.key.keysym.unicode, 1);
145                 else
146                     d = st_keybd(e.key.keysym.sym, 1);
147             }
148
149             break;
150
151         case SDL_KEYUP:
152
153             c = e.key.keysym.sym;
154
155             if      (config_tst_d(CONFIG_KEY_FORWARD, c))
156                 st_stick(config_get_d(CONFIG_JOYSTICK_AXIS_Y), 0);
157
158             else if (config_tst_d(CONFIG_KEY_BACKWARD, c))
159                 st_stick(config_get_d(CONFIG_JOYSTICK_AXIS_Y), 0);
160
161             else if (config_tst_d(CONFIG_KEY_LEFT, c))
162                 st_stick(config_get_d(CONFIG_JOYSTICK_AXIS_X), 0);
163
164             else if (config_tst_d(CONFIG_KEY_RIGHT, c))
165                 st_stick(config_get_d(CONFIG_JOYSTICK_AXIS_X), 0);
166
167             else switch (c)
168             {
169             case SDLK_RETURN:
170                 d = st_buttn(config_get_d(CONFIG_JOYSTICK_BUTTON_A), 0);
171                 break;
172             case SDLK_ESCAPE:
173                 d = st_buttn(config_get_d(CONFIG_JOYSTICK_BUTTON_EXIT), 0);
174                 break;
175
176             default:
177                 d = st_keybd(e.key.keysym.sym, 0);
178             }
179
180         case SDL_ACTIVEEVENT:
181             if (e.active.state == SDL_APPINPUTFOCUS)
182                 if (e.active.gain == 0 && video_get_grab())
183                     goto_state(&st_pause);
184             break;
185
186         case SDL_JOYAXISMOTION:
187             st_stick(e.jaxis.axis, e.jaxis.value);
188             break;
189
190         case SDL_JOYBUTTONDOWN:
191             d = st_buttn(e.jbutton.button, 1);
192             break;
193
194         case SDL_JOYBUTTONUP:
195             d = st_buttn(e.jbutton.button, 0);
196             break;
197         }
198     }
199
200     /* Process events via the tilt sensor API. */
201
202     if (tilt_stat())
203     {
204         int b;
205         int s;
206
207         st_angle((int) tilt_get_x(),
208                  (int) tilt_get_z());
209
210         while (tilt_get_button(&b, &s))
211         {
212             const int X = config_get_d(CONFIG_JOYSTICK_AXIS_X);
213             const int Y = config_get_d(CONFIG_JOYSTICK_AXIS_Y);
214             const int L = config_get_d(CONFIG_JOYSTICK_DPAD_L);
215             const int R = config_get_d(CONFIG_JOYSTICK_DPAD_R);
216             const int U = config_get_d(CONFIG_JOYSTICK_DPAD_U);
217             const int D = config_get_d(CONFIG_JOYSTICK_DPAD_D);
218
219             if (b == L || b == R || b == U || b == D)
220             {
221                 static int pad[4] = { 0, 0, 0, 0 };
222
223                 /* Track the state of the D-pad buttons. */
224
225                 if      (b == L) pad[0] = s;
226                 else if (b == R) pad[1] = s;
227                 else if (b == U) pad[2] = s;
228                 else if (b == D) pad[3] = s;
229
230                 /* Convert D-pad button events into joystick axis motion. */
231
232                 if      (pad[0] && !pad[1]) st_stick(X, -JOY_MAX);
233                 else if (pad[1] && !pad[0]) st_stick(X, +JOY_MAX);
234                 else                        st_stick(X,        0);
235
236                 if      (pad[2] && !pad[3]) st_stick(Y, -JOY_MAX);
237                 else if (pad[3] && !pad[2]) st_stick(Y, +JOY_MAX);
238                 else                        st_stick(Y,        0);
239             }
240             else d = st_buttn(b, s);
241         }
242     }
243
244     return d;
245 }
246
247 /*---------------------------------------------------------------------------*/
248
249 static char *opt_data;
250 static char *opt_replay;
251
252 #define opt_usage \
253     L_(                                                                   \
254         "Usage: %s [options ...]\n"                                       \
255         "Options:\n"                                                      \
256         "  -h, --help                show this usage message.\n"          \
257         "  -v, --version             show version.\n"                     \
258         "  -d, --data <dir>          use 'dir' as game data directory.\n" \
259         "  -r, --replay <file>       play the replay 'file'.\n"           \
260     )
261
262 #define opt_error(option) \
263     fprintf(stderr, L_("Option '%s' requires an argument.\n"), option)
264
265 static void opt_parse(int argc, char **argv)
266 {
267     int i;
268
269     /* Scan argument list. */
270
271     for (i = 1; i < argc; i++)
272     {
273         if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help")    == 0)
274         {
275             printf(opt_usage, argv[0]);
276             exit(EXIT_SUCCESS);
277         }
278
279         if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--version") == 0)
280         {
281             printf("%s\n", VERSION);
282             exit(EXIT_SUCCESS);
283         }
284
285         if (strcmp(argv[i], "-d") == 0 || strcmp(argv[i], "--data")    == 0)
286         {
287             if (i + 1 == argc)
288             {
289                 opt_error(argv[i]);
290                 exit(EXIT_FAILURE);
291             }
292             opt_data = argv[++i];
293             continue;
294         }
295
296         if (strcmp(argv[i], "-r") == 0 || strcmp(argv[i], "--replay")  == 0)
297         {
298             if (i + 1 == argc)
299             {
300                 opt_error(argv[i]);
301                 exit(EXIT_FAILURE);
302             }
303             opt_replay = argv[++i];
304             continue;
305         }
306
307         /* Assume a single unrecognized argument is a replay name. */
308
309         if (argc == 2)
310         {
311             opt_replay = argv[i];
312             break;
313         }
314     }
315 }
316
317 #undef opt_usage
318 #undef opt_error
319
320 /*---------------------------------------------------------------------------*/
321
322 static int is_replay(struct dir_item *item)
323 {
324     return str_ends_with(item->path, ".nbr");
325 }
326
327 static int is_score_file(struct dir_item *item)
328 {
329     return str_starts_with(item->path, "neverballhs-");
330 }
331
332 static void make_dirs_and_migrate(void)
333 {
334     Array items;
335     int i;
336
337     const char *src;
338     char *dst;
339
340     if (fs_mkdir("Replays"))
341     {
342         if ((items = fs_dir_scan("", is_replay)))
343         {
344             for (i = 0; i < array_len(items); i++)
345             {
346                 src = DIR_ITEM_GET(items, i)->path;
347                 dst = concat_string("Replays/", src, NULL);
348                 fs_rename(src, dst);
349                 free(dst);
350             }
351
352             fs_dir_free(items);
353         }
354     }
355
356     if (fs_mkdir("Scores"))
357     {
358         if ((items = fs_dir_scan("", is_score_file)))
359         {
360             for (i = 0; i < array_len(items); i++)
361             {
362                 src = DIR_ITEM_GET(items, i)->path;
363                 dst = concat_string("Scores/",
364                                     src + sizeof ("neverballhs-") - 1,
365                                     ".txt",
366                                     NULL);
367                 fs_rename(src, dst);
368                 free(dst);
369             }
370
371             fs_dir_free(items);
372         }
373     }
374
375     fs_mkdir("Screenshots");
376 }
377
378 /*---------------------------------------------------------------------------*/
379
380 int main(int argc, char *argv[])
381 {
382     SDL_Joystick *joy = NULL;
383     int t1, t0;
384
385     if (!fs_init(argv[0]))
386     {
387         fprintf(stderr, "Failure to initialize virtual file system: %s\n",
388                 fs_error());
389         return 1;
390     }
391
392     lang_init("neverball");
393
394     opt_parse(argc, argv);
395
396     config_paths(opt_data);
397     make_dirs_and_migrate();
398
399     /* Initialize SDL. */
400
401     if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK) == -1)
402     {
403         fprintf(stderr, "%s\n", SDL_GetError());
404         return 1;
405     }
406
407     /* Intitialize configuration. */
408
409     config_init();
410     config_load();
411
412     /* Initialize joystick. */
413
414     if (config_get_d(CONFIG_JOYSTICK) && SDL_NumJoysticks() > 0)
415     {
416         joy = SDL_JoystickOpen(config_get_d(CONFIG_JOYSTICK_DEVICE));
417         if (joy)
418             SDL_JoystickEventState(SDL_ENABLE);
419     }
420
421     /* Initialize audio. */
422
423     audio_init();
424     tilt_init();
425
426     /* Initialize video. */
427
428     if (!video_init(TITLE, ICON))
429         return 1;
430
431     init_state(&st_null);
432
433     /* Initialize demo playback. */
434
435     if (opt_replay &&
436         fs_add_path(dir_name(opt_replay)) &&
437         progress_replay(base_name(opt_replay)))
438     {
439         demo_play_goto(1);
440         goto_state(&st_demo_play);
441     }
442     else
443         goto_state(&st_title);
444
445     /* Run the main game loop. */
446
447     t0 = SDL_GetTicks();
448
449     while (loop())
450     {
451         if ((t1 = SDL_GetTicks()) > t0)
452         {
453             /* Step the game state. */
454
455             st_timer(0.001f * (t1 - t0));
456
457             t0 = t1;
458
459             /* Render. */
460
461             st_paint(0.001f * t0);
462             video_swap();
463
464             if (config_get_d(CONFIG_NICE))
465                 SDL_Delay(1);
466         }
467     }
468
469     config_save();
470
471     if (joy)
472         SDL_JoystickClose(joy);
473
474     tilt_free();
475     SDL_Quit();
476
477     return 0;
478 }
479
480 /*---------------------------------------------------------------------------*/
481