]> git.lizzy.rs Git - nothing.git/blob - src/dying_rect.c
Merge pull request #124 from tsoding/117
[nothing.git] / src / dying_rect.c
1 #include <assert.h>
2 #include <SDL2/SDL.h>
3
4 #include "./lt.h"
5 #include "./error.h"
6 #include "./dying_rect.h"
7
8 struct dying_rect_t
9 {
10     lt_t *lt;
11
12     vec_t position;
13     vec_t size;
14     color_t color;
15     Uint32 duration;
16     Uint32 time_passed;
17 };
18
19 dying_rect_t *create_dying_rect(rect_t rect,
20                                 color_t color,
21                                 Uint32 duration)
22 {
23     lt_t *lt = create_lt();
24     if (lt == NULL) {
25         return NULL;
26     }
27
28     dying_rect_t *dying_rect = PUSH_LT(lt, malloc(sizeof(dying_rect_t)), free);
29     if (dying_rect == NULL) {
30         throw_error(ERROR_TYPE_LIBC);
31         RETURN_LT(lt, NULL);
32     }
33
34     dying_rect->lt = lt;
35     dying_rect->position = vec(rect.x, rect.y);
36     dying_rect->size = vec(rect.w, rect.h);
37     dying_rect->color = color;
38     dying_rect->duration = duration;
39     dying_rect->time_passed = 0;
40
41     return dying_rect;
42 }
43
44 void destroy_dying_rect(dying_rect_t *dying_rect)
45 {
46     assert(dying_rect);
47     RETURN_LT0(dying_rect->lt);
48 }
49
50 /* TODO(#109): Dying Rect animation is too boring */
51 int dying_rect_render(const dying_rect_t *dying_rect,
52                       SDL_Renderer *renderer,
53                       const camera_t *camera)
54 {
55     assert(dying_rect);
56     assert(renderer);
57     assert(camera);
58
59     const float scale = 1.0f - (float) dying_rect->time_passed / (float) dying_rect->duration;
60     const vec_t center = vec_sum(
61         dying_rect->position,
62         vec_scala_mult(
63             dying_rect->size,
64             0.5f));
65     const vec_t scaled_size =
66         vec_scala_mult(dying_rect->size, scale);
67     const vec_t scaled_position =
68         vec_sum(center, vec_scala_mult(scaled_size, -0.5f));
69
70     return camera_fill_rect(
71         camera,
72         renderer,
73         rect_from_vecs(scaled_position, scaled_size),
74         dying_rect->color);
75 }
76
77 int dying_rect_update(dying_rect_t *dying_rect,
78                       Uint32 delta_time)
79 {
80     assert(dying_rect);
81     assert(delta_time > 0);
82
83     if (!dying_rect_is_dead(dying_rect)) {
84         dying_rect->time_passed = dying_rect->time_passed + delta_time;
85     }
86
87     return 0;
88 }
89
90 int dying_rect_is_dead(const dying_rect_t *dying_rect)
91 {
92     assert(dying_rect);
93     return dying_rect->time_passed >= dying_rect->duration;
94 }