From 334075aeca5c1ecde4d54eec7eebe2abe3e6fcc9 Mon Sep 17 00:00:00 2001 From: Relintai Date: Fri, 4 Feb 2022 13:06:13 +0100 Subject: [PATCH] Ported Rect2's clip from godot to both Rect2 and Rect2i. --- core/math/rect2.h | 24 ++++++++++++++++++++++++ core/math/rect2i.h | 24 ++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/core/math/rect2.h b/core/math/rect2.h index 31f0893..fe198a7 100644 --- a/core/math/rect2.h +++ b/core/math/rect2.h @@ -2,6 +2,7 @@ #define RECT2_H #include "vector2.h" +#include "math.h" class Rect2 { public: @@ -17,6 +18,7 @@ public: void shrink(const float by); void expand_to(const Vector2 &p_vector); + inline Rect2 clip(const Rect2 &p_rect) const; Vector2 position() const; Vector2 size() const; @@ -42,4 +44,26 @@ public: float h; }; +// Taken from the Godot Engine (MIT License) +// Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. +// Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). +inline Rect2 Rect2::clip(const Rect2 &p_rect) const { /// return a clipped rect + Rect2 new_rect = p_rect; + + if (!intersects(new_rect)) { + return Rect2(); + } + + new_rect.x = MAX(p_rect.x, x); + new_rect.y = MAX(p_rect.y, y); + + Vector2 p_rect_end = p_rect.position() + p_rect.size(); + Vector2 end = position() + size(); + + new_rect.w = MIN(p_rect_end.x, end.x) - new_rect.x; + new_rect.h = MIN(p_rect_end.y, end.y) - new_rect.y; + + return new_rect; +} + #endif \ No newline at end of file diff --git a/core/math/rect2i.h b/core/math/rect2i.h index 03fb0f6..0f224bb 100644 --- a/core/math/rect2i.h +++ b/core/math/rect2i.h @@ -2,6 +2,7 @@ #define RECT2I_H #include "vector2i.h" +#include "math.h" class Rect2i { public: @@ -17,6 +18,7 @@ public: void shrink(const int by); void expand_to(const Vector2i &p_vector); + inline Rect2i clip(const Rect2i &p_rect) const; Vector2i position() const; Vector2i size() const; @@ -42,4 +44,26 @@ public: int h; }; +// Taken from the Godot Engine (MIT License) +// Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. +// Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). +inline Rect2i Rect2i::clip(const Rect2i &p_rect) const { /// return a clipped rect + Rect2i new_rect = p_rect; + + if (!intersects(new_rect)) { + return Rect2i(); + } + + new_rect.x = MAX(p_rect.x, x); + new_rect.y = MAX(p_rect.y, y); + + Vector2i p_rect_end = p_rect.position() + p_rect.size(); + Vector2i end = position() + size(); + + new_rect.w = MIN(p_rect_end.x, end.x) - new_rect.x; + new_rect.h = MIN(p_rect_end.y, end.y) - new_rect.y; + + return new_rect; +} + #endif \ No newline at end of file