]> git.draconx.ca Git - rrace.git/blob - src/curses.c
Pack/unpack the tile planes arithmetically.
[rrace.git] / src / curses.c
1 /*
2  * Curses UI for slide puzzle game
3  * Copyright © 2022 Nick Bowler
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17  */
18
19 #include <config.h>
20 #include <stdlib.h>
21 #include <locale.h>
22 #include <assert.h>
23 #include <getopt.h>
24 #include <curses.h>
25
26 #include "help.h"
27 #include "version.h"
28
29 #include "cursesui.h"
30 #include "cursesopt.h"
31
32 enum {
33         GAME_YPOS = 1 // top row of game and goal areas.
34 };
35
36 static const char *progname = "rrace";
37 static const struct option lopts[] = { LOPTS_INITIALIZER, {0} };
38
39 static struct app_state state;
40
41 static void print_version(void)
42 {
43         version_print_head("rrace-curses", stdout);
44         puts("License GPLv3+: GNU GPL version 3 or any later version");
45         puts("This is free software: you are free to change and redistribute it.");
46         puts("There is NO WARRANTY, to the extent permitted by law.");
47 }
48
49 static void print_usage(FILE *f)
50 {
51         fprintf(f, "Usage: %s [options]\n", progname);
52         if (f != stdout)
53                 fprintf(f, "Try %s --help for more information.\n", progname);
54 }
55
56 static void print_help(void)
57 {
58         struct lopt_help help = {0};
59         const struct option *opt;
60
61         print_usage(stdout);
62
63         putchar('\n');
64         puts("Options:");
65         for (opt = lopts; opt->name; opt++) {
66                 if (!lopt_get_help(opt, &help))
67                         continue;
68                 help_print_option(opt, help.arg, help.desc, 20);
69         }
70         putchar('\n');
71
72         printf("Report bugs to <%s>.\n", PACKAGE_BUGREPORT);
73 }
74
75 static void draw_tile(WINDOW **win, unsigned colour, unsigned selected,
76                       unsigned x, unsigned y, unsigned start_column)
77 {
78         WINDOW *border = win[PLAYWIN_TILEBORDER], *fill = win[PLAYWIN_TILEFILL];
79         int w, h, attr, ch, bc = selected ? '#' : 0;
80
81         assert(colour < TILE_MAX);
82         attr = COLOR_PAIR(colour);
83         switch (colour) {
84         case TILE_RED:    ch = 'X'; break;
85         case TILE_ORANGE: ch = '|'; break;
86         case TILE_GREEN:  ch = '+'; break;
87         case TILE_YELLOW: ch = '~'; attr |= A_BOLD; break;
88         case TILE_BLUE:   ch = 'o'; attr |= A_BOLD; break;
89         case TILE_WHITE:  ch = '.'; attr |= A_BOLD; break;
90
91         case TILE_EMPTY: attr = A_BOLD|COLOR_PAIR(RR_COLOUR_SHADOW);
92         }
93
94         getmaxyx(border, h, w);
95         w = 2*(w+1)/2;
96
97         if (mvwin(border, 1+GAME_YPOS+h*y, start_column+w*x) == ERR)
98                 return;
99
100         if (colour != TILE_EMPTY) {
101                 mvderwin(fill, 1, 1);
102                 wbkgdset(fill, A_REVERSE|attr|ch);
103                 werase(fill);
104         } else {
105                 werase(border);
106         }
107
108         if (bc || colour) {
109                 wattrset(border, attr);
110                 wborder(border, bc, bc, bc, bc, bc, bc, bc, bc);
111         }
112
113         wnoutrefresh(border);
114 }
115
116 static int
117 redraw_tile(WINDOW **win, unsigned x, unsigned y, unsigned start_column,
118             uint_least32_t *gp, unsigned selected)
119 {
120         unsigned tile = board_tile(gp, 5*y+x);
121
122         assert(tile < TILE_MAX);
123         draw_tile(win, tile, selected, x, y, start_column);
124         return tile;
125 }
126
127 static void redraw_area_border(WINDOW **win, unsigned x, unsigned sz)
128 {
129         int w, h, tr = 0, rs = 0, br = 0, bs = 0, bl = 0;
130         WINDOW *area = win[PLAYWIN_AREA];
131
132         getmaxyx(stdscr, h, w);
133
134         if (h <= GAME_YPOS+1) {
135                 bl = ACS_ULCORNER, br = ACS_URCORNER;
136         } else if (h <= 3*sz+GAME_YPOS+1) {
137                 bl = br = ACS_VLINE, bs = ' ';
138         }
139
140         if (w <= x+1) {
141                 tr = ACS_ULCORNER, br = ACS_LLCORNER;
142         } else if (w <= 6*sz+x+2) {
143                 tr = ACS_HLINE, rs = ' ';
144                 br = br ? ' ' : ACS_HLINE;
145         }
146
147         wborder(area, 0, rs, 0, bs, 0, tr, bl, br);
148         wnoutrefresh(area);
149 }
150
151 static void curs_redraw_game(struct app_state *state, uint_fast32_t mask)
152 {
153         uint_least32_t buf[3], *gp = state->board.game;
154         int i;
155
156         if (mask == -1)
157                 redraw_area_border(state->gamewin, 2, 5);
158
159         if (state->view_goal_on_game) {
160                 for (i = 0; i < 3; i++) {
161                         buf[i] = state->board.goal[i];
162                         buf[i] = (gp[i] & ~GOAL_MASK) | (buf[i] << GOAL_SHIFT);
163                 }
164                 gp = buf;
165         }
166
167         for (i = 0; i < 25; i++) {
168                 if (mask & 1) {
169                         redraw_tile(state->gamewin, i%5, i/5,
170                                     4, gp, i == state->cursor);
171                 }
172                 mask >>= 1;
173         }
174 }
175
176 static void curs_redraw_goal(struct app_state *state, uint_fast32_t mask)
177 {
178         uint_least32_t gp[3] = {
179                 state->board.goal[0],
180                 state->board.goal[1],
181                 state->board.goal[2]
182         };
183         int i, x, y;
184
185         if (!state->goalwin[PLAYWIN_AREA])
186                 return;
187
188         getbegyx(state->goalwin[PLAYWIN_AREA], y, x);
189         if (mask == -1)
190                 redraw_area_border(state->goalwin, x, 3);
191
192         for (i = 0; i < 9; i++) {
193                 if (mask & 1) {
194                         redraw_tile(state->goalwin, i%3, i/3, x+2, gp, 0);
195                 }
196                 mask >>= 1;
197         }
198 }
199
200 /* Thin wrapper around wresize which returns ERR if support is unavailable. */
201 static int do_wresize(WINDOW *window, int h, int w)
202 {
203 #if HAVE_CURSES_WRESIZE
204         return wresize(window, h, w);
205 #endif
206         return ERR;
207 }
208
209 static WINDOW *realloc_area(WINDOW **orig, int h, int w, int y, int x)
210 {
211         WINDOW *win = *orig;
212
213         if (win) {
214                 if (do_wresize(win, h, w) != ERR) {
215                         mvwin(win, y, x);
216                         return win;
217                 }
218
219                 delwin(win);
220         }
221
222         if (w > 0 && h > 0)
223                 return *orig = subwin(stdscr, h, w, y, x);
224         return *orig = NULL;
225 }
226
227 static void realloc_tiles(WINDOW **win, int h)
228 {
229         WINDOW *border = win[PLAYWIN_TILEBORDER], *fill = win[PLAYWIN_TILEFILL];
230         int w = 2*h - 1;
231
232         if (fill && border) {
233                 int old_w, old_h;
234
235                 if (do_wresize(fill, h-2, w-2) != ERR
236                     && do_wresize(border, h, w) != ERR)
237                         return;
238
239                 getmaxyx(border, old_h, old_w);
240                 if (old_h == h)
241                         return;
242         }
243
244         if (fill)
245                 delwin(fill);
246         if (border)
247                 delwin(border);
248
249         win[PLAYWIN_TILEBORDER] = border = newwin(h, w, 0, 0);
250         win[PLAYWIN_TILEFILL] = derwin(border, h-2, w-2, 1, 1);
251 }
252
253 static void setup_mainwin(struct app_state *state)
254 {
255         int w, h, gamesz, goalsz, scr_w, scr_h, split;
256
257         getmaxyx(stdscr, scr_h, scr_w);
258
259         /* First try to fit the game tiles based on window height. */
260         gamesz = MAX(3, (scr_h - 4) / 5);
261
262         /* Adjust downward until we can fit smallest possible goal area. */
263         for (; split = 5+10*gamesz, gamesz > 3; gamesz--) {
264                 if (split + 20 < scr_w)
265                         break;
266         }
267
268         /* Pick a goal size that will fit in the remaining area */
269         goalsz = MAX(3, (scr_w - split - 4) / 6);
270         if (goalsz >= gamesz)
271                 goalsz = MAX(3, gamesz - 1);
272
273         realloc_tiles(state->gamewin, gamesz);
274         realloc_tiles(state->goalwin, goalsz);
275
276         /* Frame for game area */
277         w = MIN(scr_w-2, 3+10*gamesz);
278         h = MIN(scr_h-GAME_YPOS, 2+5*gamesz);
279         realloc_area(&state->gamewin[PLAYWIN_AREA], h, w, GAME_YPOS, 2);
280
281         /* Frame for goal area */
282         w = MIN(scr_w-split, 3+6*goalsz);
283         h = MIN(scr_h-GAME_YPOS, 2+3*goalsz);
284         realloc_area(&state->goalwin[PLAYWIN_AREA], h, w, GAME_YPOS, split);
285
286         /* Status area */
287         w = MAX(0, scr_w-split-1);
288         realloc_area(&state->timer, 1, w, GAME_YPOS+h, split+1);
289
290         /* Toolbar */
291         realloc_area(&state->toolbar, 1, scr_w, scr_h-1, 0);
292         curs_draw_toolbar(state);
293 }
294
295 static void app_initialize(int argc, char **argv)
296 {
297         int enable_mouse = 1;
298         int opt;
299
300         if (argc > 0)
301                 progname = argv[0];
302
303         while ((opt = getopt_long(argc, argv, SOPT_STRING, lopts, 0)) != -1) {
304                 switch (opt) {
305                 case LOPT_MOUSE:
306                         enable_mouse = 2;
307                         break;
308                 case LOPT_NO_MOUSE:
309                         enable_mouse = 0;
310                         break;
311                 case LOPT_VERSION:
312                         print_version();
313                         exit(EXIT_SUCCESS);
314                 case LOPT_HELP:
315                         print_help();
316                         exit(EXIT_SUCCESS);
317                 default:
318                         print_usage(stderr);
319                         exit(EXIT_FAILURE);
320                 }
321         }
322
323         game_reset(&state.board);
324         state.cursor = -1;
325
326         initscr();
327         start_color();
328         curs_set(0);
329
330         cbreak();
331         keypad(stdscr, TRUE);
332         if (enable_mouse) {
333                 /*
334                  * While we only care about a subset of these events, for
335                  * some reason with ncurses failing to enable all of them
336                  * causes timeout to stop working when disabled buttons are
337                  * pressed (or released).
338                  *
339                  * It is not known if other curses have this problem; at least
340                  * pdcurses does not, but the extra events should be harmless
341                  * in any case.
342                  */
343 #if HAVE_CURSES_MOUSE_SUPPORT
344                 unsigned long mask = BUTTON1_PRESSED | BUTTON1_RELEASED
345                                    | BUTTON2_PRESSED | BUTTON2_RELEASED
346                                    | BUTTON3_PRESSED | BUTTON3_RELEASED
347 #ifdef BUTTON4_PRESSED
348                                    | BUTTON4_PRESSED | BUTTON4_RELEASED
349 #endif
350 #ifdef BUTTON5_PRESSED
351                                    | BUTTON5_PRESSED | BUTTON5_RELEASED
352 #endif
353                                    ;
354 #if HAVE_CURSES_MOUSE_SET
355                 mouse_set(mask);
356 #elif HAVE_CURSES_MOUSEMASK
357                 mousemask(mask, NULL);
358 #endif
359 #if HAVE_CURSES_MOUSEINTERVAL
360                 mouseinterval(0);
361 #endif
362 #endif /* HAVE_CURSES_MOUSE_SUPPORT */
363         }
364
365         noecho();
366
367         init_pair(TILE_RED, COLOR_RED, COLOR_BLACK);
368         init_pair(TILE_ORANGE, COLOR_YELLOW, COLOR_BLACK);
369         init_pair(TILE_YELLOW, COLOR_YELLOW, COLOR_BLACK);
370         init_pair(TILE_GREEN, COLOR_GREEN, COLOR_BLACK);
371         init_pair(TILE_BLUE, COLOR_BLUE, COLOR_BLACK);
372         init_pair(TILE_WHITE, COLOR_WHITE, COLOR_BLACK);
373         init_pair(RR_COLOUR_SHADOW, COLOR_BLACK, COLOR_BLACK);
374         init_pair(RR_COLOUR_TOOLBAR, COLOR_CYAN, COLOR_BLACK);
375
376         setup_mainwin(&state);
377         refresh();
378 }
379
380 static void update_timer(struct app_state *state, uint_fast32_t ms)
381 {
382         unsigned sec, min;
383
384         state->timer_ms = ms;
385         sec = ms / 1000; ms %= 1000;
386         min = sec / 60; sec %= 60;
387         mvwprintw(state->timer, 0, 0, "Time: %u:%.2u.%.3u",
388                   min, sec, (unsigned)ms);
389         wclrtoeol(state->timer);
390         wnoutrefresh(state->timer);
391 }
392
393 static uint_fast32_t do_move(struct app_state *state, int x, int y)
394 {
395         uint_fast32_t mask;
396
397         if ((mask = game_do_move(&state->board, x, y)) != 0) {
398                 uint_fast32_t goal = game_check_goal(&state->board);
399
400                 if (state->view_goal_on_game) {
401                         state->view_goal_on_game = 0;
402                         mask |= goal;
403                 }
404
405                 if (goal == 0) {
406                         /* Solved! */
407                         update_timer(state, game_finish(&state->board));
408                         mask |= ~GOAL_MASK;
409                         state->cursor = -1;
410                         timeout(-1);
411                 }
412
413                 curs_redraw_game(state, mask);
414                 doupdate();
415         }
416
417         return mask;
418 }
419
420 static void do_reset_cursor(struct app_state *state)
421 {
422         state->cursor = 5*state->board.y + state->board.x;
423 }
424
425 void curs_new_game(struct app_state *state)
426 {
427         game_reset(&state->board);
428
429         do_reset_cursor(state);
430         curs_redraw_game(state, -1);
431         curs_redraw_goal(state, -1);
432         update_timer(state, 0);
433         doupdate();
434
435         timeout(33);
436         game_begin(&state->board);
437 }
438
439 #if HAVE_CURSES_MOUSE_SUPPORT
440 /*
441  * Given x, y as screen coordinates, record which (if any) toolbar function
442  * label is at that position, to be performed later.
443  *
444  * If no function is indicated, returns zero.  Otherwise, returns non-zero.
445  */
446 static int press_toolbar(struct app_state *state, int x, int y)
447 {
448         return state->toolbar_click = curs_toolbar_mouse_func(state, x, y);
449 }
450
451 /*
452  * Given x, y as screen coordinates, perform the toolbar action.
453  *
454  * Perform the action previously recorded by press_toolbar, if and only if
455  * the x, y screen coordinates correspond to the same function.
456  */
457 static void release_toolbar(struct app_state *state, int x, int y)
458 {
459         int func = curs_toolbar_mouse_func(state, x, y);
460
461         if (func && state->toolbar_click == func) {
462                 curs_execute_function(state, func);
463         }
464
465         state->toolbar_click = 0;
466 }
467
468 /*
469  * Given x, y as screen coordinates, determine which (if any) game tile is
470  * at that position.
471  *
472  * If there is no such tile, performs no action and returns 0.
473  *
474  * Otherwise, attempts to move that tile and returns non-zero.
475  */
476 static int press_tile(struct app_state *state, int x, int y)
477 {
478         int game_x, game_y, tile_w, tile_h;
479         uint_fast32_t cursor_mask, move_mask;
480
481         getbegyx(state->gamewin[PLAYWIN_AREA], game_y, game_x);
482         getmaxyx(state->gamewin[PLAYWIN_TILEBORDER], tile_h, tile_w);
483         tile_w += tile_w & 1;
484
485         /* special case the left spacer column */
486         if (x == game_x+1)
487                 x++;
488
489         if (x < game_x+2 || (x -= game_x+2)/5 >= tile_w)
490                 return 0;
491         if (y < game_y+1 || (y -= game_y+1)/5 >= tile_h)
492                 return 0;
493
494         /* OK, selected a tile. */
495         x /= tile_w;
496         y /= tile_h;
497
498         /* Disable the keyboard cursor due to mouse action */
499         cursor_mask = state->cursor < 0 ? -1 : 1ul << state->cursor;
500         state->cursor = -1;
501
502         move_mask = do_move(state, x, y);
503         if ((cursor_mask & move_mask) == 0) {
504                 curs_redraw_game(state, cursor_mask);
505                 doupdate();
506         }
507
508         return 1;
509 }
510
511 static void do_mouse(struct app_state *state)
512 {
513         unsigned long bstate;
514         int x, y;
515
516 #if HAVE_CURSES_GETMOUSE_NCURSES
517         MEVENT mev;
518
519         if (getmouse(&mev) == ERR)
520                 return;
521
522         x = mev.x, y = mev.y;
523         bstate = mev.bstate;
524 #elif HAVE_CURSES_REQUEST_MOUSE_POS
525         request_mouse_pos();
526         x = MOUSE_X_POS;
527         y = MOUSE_Y_POS;
528
529         bstate = 0;
530
531 #define set_bstate_helper(button) do { if (BUTTON_CHANGED(button)) \
532         switch (BUTTON_STATUS(button)) { \
533         case BUTTON_RELEASED: bstate |= BUTTON ## button ##  _RELEASED; break; \
534         case BUTTON_PRESSED:  bstate |= BUTTON ## button ##  _PRESSED; break; \
535         } \
536 } while (0);
537
538         set_bstate_helper(1);
539         set_bstate_helper(3);
540 #endif
541         if (bstate & BUTTON3_PRESSED) {
542                 state->view_goal_on_game = 1;
543                 curs_redraw_game(state, game_check_goal(&state->board));
544                 doupdate();
545         }
546
547         if (bstate & BUTTON3_RELEASED) {
548                 state->view_goal_on_game = 0;
549                 curs_redraw_game(state, game_check_goal(&state->board));
550                 doupdate();
551         }
552
553         /* Ignore button1 if holding button3 to view goal */
554         if (state->view_goal_on_game & 1)
555                 return;
556
557         if (bstate & BUTTON1_PRESSED) {
558                 if (press_toolbar(state, x, y));
559                 else if (press_tile(state, x, y));
560         }
561
562         if (bstate & BUTTON1_RELEASED) {
563                 release_toolbar(state, x, y);
564         }
565 }
566 #endif /* HAVE_CURSES_MOUSE_SUPPORT */
567
568 static void do_move_cursor(struct app_state *state, int c)
569 {
570         uint_fast32_t mask = 0;
571
572         if (state->cursor < 0) {
573                 /* Cursor was hidden; reset it */
574                 do_reset_cursor(state);
575         } else {
576                 mask = 1ul << state->cursor;
577         }
578
579         if (state->view_goal_on_game) {
580                 state->view_goal_on_game = 0;
581                 mask |= game_check_goal(&state->board);
582         }
583
584         switch (c) {
585         case KEY_UP:
586                 if ((state->cursor -= 5) < 0)
587                         state->cursor += 25;
588                 break;
589         case KEY_DOWN:
590                 if ((state->cursor += 5) >= 25)
591                         state->cursor -= 25;
592                 break;
593         case KEY_LEFT:
594                 if ((state->cursor -= 1) % 5 == 4 || state->cursor < 0)
595                         state->cursor += 5;
596                 break;
597         case KEY_RIGHT:
598                 if ((state->cursor += 1) % 5 == 0)
599                         state->cursor -= 5;
600                 break;
601         }
602
603         curs_redraw_game(state, mask | 1ul << state->cursor);
604         doupdate();
605 }
606
607 static void do_keystroke(struct app_state *state, int c)
608 {
609         int last_input = state->last_input;
610         state->last_input = c;
611
612         switch (c) {
613         case KEY_DOWN: case KEY_UP: case KEY_LEFT: case KEY_RIGHT:
614                 do_move_cursor(state, c);
615                 break;
616         case '\t':
617                 state->view_goal_on_game ^= 2u;
618                 curs_redraw_game(state, game_check_goal(&state->board));
619                 doupdate();
620                 break;
621         case ' ':
622                 if (!(state->view_goal_on_game & 1) && state->cursor >= 0)
623                         do_move(state, state->cursor%5, state->cursor/5);
624                 break;
625         }
626
627         /* ESC+# keys */
628         if (last_input == '\33' && c >= '0' && c <= '9') {
629                 curs_execute_function(state, (c -= '0') == 0 ? 10 : c);
630         }
631
632         /* F# keys */
633         if (c >= KEY_F(1) && c <= KEY_F(10)) {
634                 curs_execute_function(state, c - KEY_F0);
635         }
636 }
637
638 /* One iteration of main input loop */
639 void do_mainloop(struct app_state *state)
640 {
641         int c = getch();
642
643         switch (c) {
644 #ifdef KEY_RESIZE
645         case KEY_RESIZE:
646                 setup_mainwin(state);
647                 clear();
648                 refresh();
649                 curs_redraw_game(state, -1);
650                 curs_redraw_goal(state, -1);
651                 curs_draw_toolbar(state);
652                 update_timer(state, state->timer_ms);
653                 doupdate();
654                 break;
655 #endif
656 #if HAVE_CURSES_MOUSE_SUPPORT
657         case KEY_MOUSE:
658                 do_mouse(state);
659                 break;
660 #endif
661         default:
662                 do_keystroke(state, c);
663         case ERR:;
664         }
665
666         if (state->board.x <= 4) {
667                 update_timer(state, game_elapsed(&state->board));
668                 doupdate();
669         }
670 }
671
672 int main(int argc, char **argv)
673 {
674         setlocale(LC_ALL, "");
675         app_initialize(argc, argv);
676
677         curs_new_game(&state);
678         while (1)
679                 do_mainloop(&state);
680         abort();
681 }