Subastra
Loading...
Searching...
No Matches
sat.h
Go to the documentation of this file.
1#ifndef __H__SAT__
2#define __H__SAT__
3
4#include "../vec2.h"
5#include <alloca.h>
6
7typedef vec2 float2;
8
10 return a.y > b.x && b.y > a.x;
11}
12
13static float2 sat_vec2_project(vec2 *vs, sz n, vec2 axis) {
14 float2 ret;
15
16 ret.x = FLOAT32_INFTY;
17 ret.y = FLOAT32_NEG_INFTY;
18
19 for (sz i = 0; i < n; i++) {
20 float proj = vec2_dot(vs[i], axis);
21 if (proj < ret.x)
22 ret.x = proj;
23 if (proj > ret.y)
24 ret.y = proj;
25 }
26
27 return ret;
28}
29
30static bool sat_intersect(vec2 *vs1, sz n1, vec2 *vs2, sz n2, vec2 *minimal) {
31 float minimal_depth = FLOAT32_INFTY;
32
33 if (minimal) {
34 minimal->x = 0.;
35 minimal->y = 0.;
36 }
37
38 // NOTE(Artur): There is a preferred direction of collision resolution for
39 // any two shapes. Is this a concern?
40
41 norm2 *axes = (norm2 *)alloca(sizeof(vec2) * (n1 + n2));
42
43 for (int i = 0; i < n1; i++) {
44 vec2 s = vec2_sub(vs1[(i + 1) % n1], vs1[i]);
45 vec2 p = vec2_perpendicular(s);
46 norm2 pn = vec2_normalize(p);
47 axes[i] = pn;
48 }
49
50 for (int i = 0; i < n2; i++) {
51 vec2 s = vec2_sub(vs2[(i + 1) % n2], vs2[i]);
52 vec2 p = vec2_perpendicular(s);
53 norm2 pn = vec2_normalize(p);
54 axes[i + n1] = pn;
55 }
56
57 for (sz i = 0; i < n1 + n2; i++) {
58 norm2 axis = axes[i];
59
60 float2 a = sat_vec2_project(vs1, n1, axis);
61 float2 b = sat_vec2_project(vs2, n2, axis);
62
63 if(!sat_float2_is_overlap(a, b))
64 return false;
65
66 if (minimal) {
67 float depth = fmaxf(b.x, a.y) - fminf(b.y, a.x);
68 if (depth < minimal_depth) {
69 minimal_depth = depth;
70 *minimal = vec2_scale(axis, minimal_depth);
71 }
72 }
73 }
74
75 return true;
76}
77
78#endif
#define FLOAT32_NEG_INFTY
Definition defs.h:43
size_t sz
Definition defs.h:51
#define FLOAT32_INFTY
Definition defs.h:42
static bool sat_float2_is_overlap(float2 a, float2 b)
Definition sat.h:9
vec2 float2
Definition sat.h:7
static float2 sat_vec2_project(vec2 *vs, sz n, vec2 axis)
Definition sat.h:13
static bool sat_intersect(vec2 *vs1, sz n1, vec2 *vs2, sz n2, vec2 *minimal)
Definition sat.h:30
Definition vec2.h:11
float y
Definition vec2.h:12
float x
Definition vec2.h:12