aboutsummaryrefslogtreecommitdiff
path: root/menu.c
blob: e4e82f56614deb3398d39f5a8e81e1f5390752ae (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include "asset.h"
#include "input.h"
#include "menu.h"

#ifdef DEBUG
#include "error.h"
#include "platform.h"
#endif

void init_menu(Menu* menu, void* ptr) {
	menu->el_count = 0;
	menu->selected = 0;
	menu->y = renderer_h / 2;
	menu->h = 0;
	menu->ptr = ptr;
}

void menu_add(
	Menu* menu,
	const char* text,
	Menu_Event on_select,
	const BM_Font* font
) {
	Menu_Item* it;
	int i;

#ifdef DEBUG
	if (menu->el_count >= menu_max_elements) {
		platform_err("Too many menu elements.\n");
		platform_abort(error_gameplay_error);
	}
#endif

	it = &menu->els[menu->el_count++];
	it->on_select = on_select;
	it->text_len = 0;
	for (i = 0; text[i]; i++) {
		it->text[i] = text[i];
		it->text_len++;
	} it->text[i] = 0;

	menu->h = font->char_h * menu->el_count;
	menu->y = renderer_h / 2 - (menu->h) / 2;
}

void update_menu(Menu* menu) {
	if (button_just_pressed(btn_dpad_down)) {
		menu->selected++;
		if (menu->selected >= menu->el_count) {
			menu->selected = 0;
		}
	}

	if (button_just_pressed(btn_dpad_up)) {
		menu->selected--;
		if (menu->selected < 0) {
			menu->selected = menu->el_count - 1;
		}
	}

	if (
		button_just_pressed(btn_jump) ||
		button_just_pressed(btn_shoot)
	) {
		menu->els[menu->selected].on_select(menu);
	}
}

void render_menu(Menu* menu, const BM_Font* font) {
	int i, x, y, cw, ch;
	const Menu_Item* el;

	y = menu->y;
	cw = font->char_w;
	ch = font->char_h;

	for (i = 0; i < menu->el_count; i++) {
		el = &menu->els[i];
		x = renderer_w / 2 - (cw * el->text_len) / 2;
		rfont_text(font, x, y, el->text);
		if (i == menu->selected) {
			rfont_char(font, x - cw, y, '>');
		}
		y += ch;
	}
}