]> git.lizzy.rs Git - nothing.git/blob - src/math/triangle.c
Sort includes
[nothing.git] / src / math / triangle.c
1 #include <math.h>
2 #include <stdio.h>
3
4 #include "./math/pi.h"
5 #include "./math/rand.h"
6 #include "./triangle.h"
7
8 triangle_t triangle(point_t p1, point_t p2, point_t p3)
9 {
10     const triangle_t result = {
11         .p1 = p1,
12         .p2 = p2,
13         .p3 = p3
14     };
15
16     return result;
17 }
18
19 triangle_t equilateral_triangle(void)
20 {
21     const float d = PI_2 / 3.0f;
22
23     const triangle_t result = {
24         .p1 = vec(cosf(0.0f), sinf(0.0f)),
25         .p2 = vec(cosf(d), sinf(d)),
26         .p3 = vec(cosf(2.0f * d), sinf(2.0f * d))
27     };
28
29     return result;
30 }
31
32 /* TODO(#151): some of the random triangles are too thin */
33 triangle_t random_triangle(float radius)
34 {
35     return triangle(
36         vec_from_polar(rand_float(2 * PI), rand_float(radius)),
37         vec_from_polar(rand_float(2 * PI), rand_float(radius)),
38         vec_from_polar(rand_float(2 * PI), rand_float(radius)));
39 }
40
41 static void swap_points(point_t *p1, point_t *p2)
42 {
43     point_t t = *p1;
44     *p1 = *p2;
45     *p2 = t;
46 }
47
48 triangle_t triangle_sorted_by_y(triangle_t t)
49 {
50     if (t.p1.y > t.p2.y) { swap_points(&t.p1, &t.p2); }
51     if (t.p2.y > t.p3.y) { swap_points(&t.p2, &t.p3); }
52     if (t.p1.y > t.p2.y) { swap_points(&t.p1, &t.p2); }
53
54     return t;
55 }
56
57 void rect_as_triangles(rect_t rect, triangle_t triangles[2])
58 {
59     triangle_t t1 = {
60         .p1 = { .x = rect.x, .y = rect.y },
61         .p2 = { .x = rect.x + rect.w, .y = rect.y },
62         .p3 = { .x = rect.x, .y = rect.y + rect.h }
63     };
64
65     triangle_t t2 = {
66         .p1 = { .x = rect.x + rect.w, .y = rect.y },
67         .p2 = { .x = rect.x, .y = rect.y + rect.h },
68         .p3 = { .x = rect.x + rect.w, .y = rect.y + rect.h }
69     };
70
71     triangles[0] = t1;
72     triangles[1] = t2;
73 }
74
75 triangle_t triangle_mat3x3_product(triangle_t t, mat3x3 m)
76 {
77     triangle_t t1 = {
78         .p1 = point_mat3x3_product(t.p1, m),
79         .p2 = point_mat3x3_product(t.p2, m),
80         .p3 = point_mat3x3_product(t.p3, m)
81     };
82
83     return t1;
84 }