From 93243283f02a6a49d88351ce39812cfe69833dc6 Mon Sep 17 00:00:00 2001 From: MacDue Date: Sun, 12 Nov 2023 20:43:39 +0000 Subject: [PATCH] LibGfx: Add BoundingBox helper class This is a small helper class to compute the bounding box of a set of points. --- Userland/Libraries/LibGfx/BoundingBox.h | 64 +++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Userland/Libraries/LibGfx/BoundingBox.h diff --git a/Userland/Libraries/LibGfx/BoundingBox.h b/Userland/Libraries/LibGfx/BoundingBox.h new file mode 100644 index 00000000000..fa95ba7db03 --- /dev/null +++ b/Userland/Libraries/LibGfx/BoundingBox.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2023, MacDue + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include +#include + +namespace Gfx { + +template +class BoundingBox { +public: + constexpr BoundingBox() = default; + + constexpr void add_point(T x, T y) + { + if (m_has_no_points) { + m_min_x = m_max_x = x; + m_min_y = m_max_y = y; + m_has_no_points = false; + } else { + m_min_x = min(m_min_x, x); + m_min_y = min(m_min_y, y); + m_max_x = max(m_max_x, x); + m_max_y = max(m_max_y, y); + } + } + + constexpr T x() const { return m_min_x; } + constexpr T y() const { return m_min_y; } + constexpr T width() const { return m_max_x - m_min_x; } + constexpr T height() const { return m_max_y - m_min_y; } + + void add_point(Point point) + { + add_point(point.x(), point.y()); + } + + constexpr Rect to_rect() const + { + return Rect { x(), y(), width(), height() }; + } + + constexpr operator Rect() const + { + return to_rect(); + } + +private: + T m_min_x { 0 }; + T m_min_y { 0 }; + T m_max_x { 0 }; + T m_max_y { 0 }; + bool m_has_no_points { true }; +}; + +using FloatBoundingBox = BoundingBox; +using IntBoundingBox = BoundingBox; + +}