comparison libcore/core/game.c @ 162:629f55f3961e

core: rework states
author David Demelier <markand@malikania.fr>
date Sun, 18 Oct 2020 12:01:59 +0200
parents b386d25832c8
children eb3148c1e54d
comparison
equal deleted inserted replaced
161:31d7f23c0588 162:629f55f3961e
30 game_switch(struct state *state, bool quick) 30 game_switch(struct state *state, bool quick)
31 { 31 {
32 assert(state); 32 assert(state);
33 33
34 if (quick) { 34 if (quick) {
35 if (game.state_next)
36 state_finish(game.state_next);
37
35 game.state_next = NULL; 38 game.state_next = NULL;
36 game.state = state; 39 game.state = state;
37 game.state->enter(); 40 state_start(game.state);
38 } else 41 } else
39 game.state_next = state; 42 game.state_next = state;
40 } 43 }
41 44
42 void 45 void
43 game_handle(const union event *event) 46 game_handle(const union event *ev)
44 { 47 {
45 assert(event); 48 assert(ev);
46 49
47 if (game.state && !(game.inhibit & INHIBIT_STATE_INPUT)) 50 if (game.state && !(game.inhibit & INHIBIT_STATE_INPUT))
48 game.state->handle(event); 51 state_handle(game.state, ev);
49 } 52 }
50 53
51 void 54 void
52 game_update(unsigned int ticks) 55 game_update(unsigned int ticks)
53 { 56 {
54 if (!(game.inhibit & INHIBIT_STATE_UPDATE)) { 57 if (game.inhibit & INHIBIT_STATE_UPDATE)
55 /* Change state if any. */ 58 return;
56 if (game.state_next) {
57 /* Inform the current state we're gonna leave it. */
58 if (game.state)
59 game.state->leave();
60 59
61 game.state = game.state_next; 60 /* Change state if any. */
62 game.state->enter(); 61 if (game.state_next) {
63 game.state_next = NULL; 62 struct state *previous;
64 }
65 63
66 if (game.state) 64 /* Inform the current state we're gonna leave it. */
67 game.state->update(ticks); 65 if ((previous = game.state))
66 state_end(previous);
67
68 /* Change the state and tell we're starting it. */
69 if ((game.state = game.state_next))
70 state_start(game.state);
71
72 game.state_next = NULL;
73
74 /*
75 * Only call finish at the end of the process because
76 * the user may still use resources from it during the
77 * transition.
78 */
79 if (previous)
80 state_finish(previous);
68 } 81 }
82
83 if (game.state)
84 state_update(game.state, ticks);
69 } 85 }
70 86
71 void 87 void
72 game_draw(void) 88 game_draw(void)
73 { 89 {
74 if (game.state && !(game.inhibit & INHIBIT_STATE_DRAW)) 90 if (game.state && !(game.inhibit & INHIBIT_STATE_DRAW))
75 game.state->draw(); 91 state_draw(game.state);
76 92
77 painter_present(); 93 painter_present();
78 } 94 }
79 95
80 void 96 void
81 game_quit(void) 97 game_quit(void)
82 { 98 {
83 if (game.state && game.state->leave) 99 /* Close the next state if any. */
84 game.state->leave(); 100 if (game.state_next) {
85 101 state_finish(game.state_next);
86 game.state = NULL; 102 game.state_next = NULL;
103 }
104
105 if (game.state) {
106 state_end(game.state);
107 state_finish(game.state);
108 game.state = NULL;
109 }
87 } 110 }