From 9306828192644cf367aeec30c00cc6bc178edb62 Mon Sep 17 00:00:00 2001 From: 3gg <3gg@shellblade.net> Date: Thu, 8 Feb 2024 07:53:43 -0800 Subject: Add AABB. --- include/math/aabb2.h | 35 +++++++++++++++++++++++++++++++++++ include/math/aabb3.h | 35 +++++++++++++++++++++++++++++++++++ include/math/fwd.h | 2 ++ 3 files changed, 72 insertions(+) create mode 100644 include/math/aabb2.h create mode 100644 include/math/aabb3.h diff --git a/include/math/aabb2.h b/include/math/aabb2.h new file mode 100644 index 0000000..edb6cb6 --- /dev/null +++ b/include/math/aabb2.h @@ -0,0 +1,35 @@ +#pragma once + +#include "vec2.h" + +#include + +typedef struct aabb2 { + vec2 min; + vec2 max; +} aabb2; + +/// Construct an AABB from min and max bounds. +static inline aabb2 aabb2_make(vec2 min, vec2 max) { + return (aabb2){.min = min, .max = max}; +} + +/// Construct an AABB from an array of points. +static inline aabb2 aabb2_from_array(const vec2 points[], size_t count) { + aabb2 box = (aabb2){0}; + for (size_t i = 0; i < count; ++i) { + box.min = vec2_min(box.min, points[i]); + box.max = vec2_max(box.max, points[i]); + } + return box; +} + +/// Add a point to the AABB. The AABB grows to contain the point. +static inline aabb2 aabb2_add(aabb2 box, vec2 p) { + return (aabb2){.min = vec2_min(box.min, p), .max = vec2_max(box.max, p)}; +} + +/// Return the AABB of two AABBs. +static inline aabb2 aabb2_sum(aabb2 a, aabb2 b) { + return (aabb2){.min = vec2_min(a.min, b.min), .max = vec2_max(a.max, b.max)}; +} diff --git a/include/math/aabb3.h b/include/math/aabb3.h new file mode 100644 index 0000000..0b0005c --- /dev/null +++ b/include/math/aabb3.h @@ -0,0 +1,35 @@ +#pragma once + +#include "vec3.h" + +#include + +typedef struct aabb3 { + vec3 min; + vec3 max; +} aabb3; + +/// Construct an AABB from min and max bounds. +static inline aabb3 aabb3_make(vec3 min, vec3 max) { + return (aabb3){.min = min, .max = max}; +} + +/// Construct an AABB from an array of points. +static inline aabb3 aabb3_from_array(const vec3 points[], size_t count) { + aabb3 box = (aabb3){0}; + for (size_t i = 0; i < count; ++i) { + box.min = vec3_min(box.min, points[i]); + box.max = vec3_max(box.max, points[i]); + } + return box; +} + +/// Add a point to the AABB. The AABB grows to contain the point. +static inline aabb3 aabb3_add(aabb3 box, vec3 p) { + return (aabb3){.min = vec3_min(box.min, p), .max = vec3_max(box.max, p)}; +} + +/// Return the AABB of two AABBs. +static inline aabb3 aabb3_sum(aabb3 a, aabb3 b) { + return (aabb3){.min = vec3_min(a.min, b.min), .max = vec3_max(a.max, b.max)}; +} diff --git a/include/math/fwd.h b/include/math/fwd.h index d70817a..283f821 100644 --- a/include/math/fwd.h +++ b/include/math/fwd.h @@ -1,6 +1,8 @@ /// Forward declarations for all math objects. #pragma once +typedef struct aabb2 aabb2; +typedef struct aabb3 aabb3; typedef struct Camera Camera; typedef struct mat4 mat4; typedef struct quat quat; -- cgit v1.2.3