Ported Rect2's clip from godot to both Rect2 and Rect2i.

This commit is contained in:
Relintai 2022-02-04 13:06:13 +01:00
parent 69a2d2f1b7
commit 334075aeca
2 changed files with 48 additions and 0 deletions

View File

@ -2,6 +2,7 @@
#define RECT2_H #define RECT2_H
#include "vector2.h" #include "vector2.h"
#include "math.h"
class Rect2 { class Rect2 {
public: public:
@ -17,6 +18,7 @@ public:
void shrink(const float by); void shrink(const float by);
void expand_to(const Vector2 &p_vector); void expand_to(const Vector2 &p_vector);
inline Rect2 clip(const Rect2 &p_rect) const;
Vector2 position() const; Vector2 position() const;
Vector2 size() const; Vector2 size() const;
@ -42,4 +44,26 @@ public:
float h; 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 #endif

View File

@ -2,6 +2,7 @@
#define RECT2I_H #define RECT2I_H
#include "vector2i.h" #include "vector2i.h"
#include "math.h"
class Rect2i { class Rect2i {
public: public:
@ -17,6 +18,7 @@ public:
void shrink(const int by); void shrink(const int by);
void expand_to(const Vector2i &p_vector); void expand_to(const Vector2i &p_vector);
inline Rect2i clip(const Rect2i &p_rect) const;
Vector2i position() const; Vector2i position() const;
Vector2i size() const; Vector2i size() const;
@ -42,4 +44,26 @@ public:
int h; 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 #endif