summaryrefslogtreecommitdiff
path: root/include/vec.h
diff options
context:
space:
mode:
Diffstat (limited to 'include/vec.h')
-rw-r--r--include/vec.h64
1 files changed, 64 insertions, 0 deletions
diff --git a/include/vec.h b/include/vec.h
new file mode 100644
index 0000000..ce1b921
--- /dev/null
+++ b/include/vec.h
@@ -0,0 +1,64 @@
+// SPDX-FileCopyrightText: 2024 Lizzy Fleckenstein <lizzy@vlhl.dev>
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+#ifndef VEC_H
+#define VEC_H
+
+#include <stdint.h>
+#include <stdbool.h>
+#include "ser.h"
+
+#define VECFN static __attribute__((unused))
+
+#define MIN(X, Y) ((X) < (Y) ? (X) : (Y))
+#define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
+#define CHKSUB(A, B) ((A) > (B) ? (A) - (B) : 0)
+
+#define CAST(T, V) ((T) { (V).x, (V).y })
+
+#define MKVEC(V, B, S, SER) \
+typedef struct { S x; S y; } V; \
+typedef struct { V pos; uvec2 size; } B; \
+VECFN V V##_add(V a, V b) { return (V) { a.x+b.x, a.y+b.y }; } \
+VECFN V V##_sub(V a, V b) { return (V) { a.x-b.x, a.y-b.y }; } \
+VECFN uvec2 V##_chksub(V a, V b) { return (uvec2) { CHKSUB(a.x, b.x), CHKSUB(a.y, b.y) }; } \
+VECFN V V##_min(V a, V b) { return (V) { MIN(a.x, b.x), MIN(a.y, b.y) }; } \
+VECFN V V##_max(V a, V b) { return (V) { MAX(a.x, b.x), MAX(a.y, b.y) }; } \
+VECFN bool V##_eq(V a, V b) { return a.x == b.x && a.y == b.y; } \
+VECFN bool V##_le(V a, V b) { return a.x <= b.x && a.y <= b.y; } \
+VECFN bool V##_lt(V a, V b) { return a.x < b.x && a.y < b.y; } \
+VECFN void ser_##V(strbuf *w, V v) { ser_##SER(w, v.x); ser_##SER(w, v.y); } \
+VECFN bool deser_##V(str *r, V *v) { return deser_##SER(r, &v->x) && deser_##SER(r, &v->y); } \
+VECFN void ser_##B(strbuf *w, B b) { ser_##V(w, b.pos); ser_uvec2(w, b.size); } \
+VECFN bool deser_##B(str *r, B *b) { return deser_##V(r, &b->pos) && deser_uvec2(r, &b->size); } \
+VECFN V B##_upper(B b) { return V##_add(b.pos, CAST(V, b.size)); } \
+VECFN B B##_overlap(B a, B b) { V base = V##_max(a.pos, b.pos); \
+ return (B) { base, V##_chksub(V##_min(B##_upper(a), B##_upper(b)), base) }; } \
+VECFN bool B##_empty(B b) { return b.size.x == 0 || b.size.y == 0; } \
+VECFN bool B##_contains(B b, V v) { return V##_le(b.pos, v) && V##_lt(v, B##_upper(b)); } \
+VECFN B B##_around(V center, uint32_t radius) { uint32_t diam = radius*2+1; \
+ return (B) { V##_sub(center, (V) { radius, radius }), (uvec2) { diam, diam } }; }
+
+MKVEC(uvec2, ubox2, uint32_t, u32)
+MKVEC(vec2, box2, int32_t, i32)
+
+#define VEC2(X, Y) ((vec2) { (X), (Y) })
+#define UVEC2(X, Y) ((uvec2) { (X), (Y) })
+
+#define CUVEC2(V) ((uvec2) { (V).x, (V).y })
+#define CVEC2(V) ((vec2) { (V).x, (V).y })
+
+VECFN vec2 vec2_neg(vec2 v)
+{
+ return VEC2(-v.x, -v.y);
+}
+
+#undef MKVEC
+#undef VECFN
+#undef MIN
+#undef MAX
+#undef CHKSUB
+#undef CAST
+
+#endif