blob: 932b7a5d552795aa6998a9403bdffce45a3ac8df (
plain)
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
|
#include <SDL3/SDL.h>
#include <stdio.h>
#include <stdlib.h>
#include <saffron.h>
SaffronWidget* saffron_widget_new(void) {
/* This function is a generic primitive for creating widgets. You wouldn't want to do this manually unless you're a lunatic. It is meant to be wrapped around by other functions that change the default parameters, for example, what sane person makes a widget 0x0x0x0? you LUNATIC! */
SaffronWidget* widget = malloc(sizeof(SaffronWidget));
widget->x = 0;
widget->y = 0;
widget->w = 0;
widget->h = 0;
widget->draw = NULL;
widget->on_click = NULL;
widget->parent = NULL;
widget->children = NULL;
widget->child_count = 0;
return widget;
}
void saffron_widget_free(SaffronWidget *widget) {
/* follow-up to my previous comment:
* yeah it is the caller's responsibility to check
* for undefined behaviour but this one line will save
* so much time down the line */
if (!widget) return;
for (int i = 0; i < widget->child_count; i++) {
saffron_widget_free(widget->children[i]);
}
free(widget->children);
free(widget);
}
void saffron_widget_draw(SaffronWidget* widget, SDL_Renderer *renderer) {
if (!widget) return;
if (widget->draw) {
widget->draw(widget, renderer);
}
for (int i = 0; i < widget->child_count; i++) {
saffron_widget_draw(widget->children[i], renderer);
}
}
void saffron_widget_add_child(SaffronWidget *parent, SaffronWidget *child) {
child->parent = parent;
parent->children = realloc(parent->children, sizeof(SaffronWidget*) * (parent->child_count + 1));
parent->children[parent->child_count] = child;
parent->child_count++;
}
SaffronWidget* saffron_widget_hit_test(SaffronWidget* widget, int x, int y) {
if (!widget) {
printf("[saffron] hit test: widget is NULL!\n");
return NULL;
}
if (x < widget->x || x > widget->x + widget->w) {
printf("[saffron] hit test: widget failed X bounds check!\n");
return NULL;
}
if (y < widget->y || y > widget->y + widget->h) {
printf("[saffron] hit test: widget failed Y bounds check!\n");
return NULL;
}
// check children front to back
for (int i = widget->child_count - 1; i >= 0; i--) {
printf("[saffron] recursing to child (%i)\n", i);
SaffronWidget* hit = saffron_widget_hit_test(widget->children[i], x, y);
if (hit) return hit;
}
return widget;
}
|