Add Span and some basic uses from Geometry.

This commit is contained in:
lawnjelly 2025-10-08 14:55:42 +01:00
parent 8c10cd6646
commit db9921b17f
12 changed files with 264 additions and 18 deletions

View file

@ -38,6 +38,7 @@
#include "core/error_macros.h" #include "core/error_macros.h"
#include "core/os/memory.h" #include "core/os/memory.h"
#include "core/safe_refcount.h" #include "core/safe_refcount.h"
#include "core/span.h"
template <class T> template <class T>
class Vector; class Vector;
@ -132,6 +133,9 @@ public:
} }
} }
_FORCE_INLINE_ operator Span<T>() const { return Span<T>(ptr(), size()); }
_FORCE_INLINE_ Span<T> span() const { return operator Span<T>(); }
_FORCE_INLINE_ void clear() { resize(0); } _FORCE_INLINE_ void clear() { resize(0); }
_FORCE_INLINE_ bool empty() const { return _ptr == nullptr; } _FORCE_INLINE_ bool empty() const { return _ptr == nullptr; }

View file

@ -35,6 +35,7 @@
#include "core/os/memory.h" #include "core/os/memory.h"
#include "core/pool_vector.h" #include "core/pool_vector.h"
#include "core/sort_array.h" #include "core/sort_array.h"
#include "core/span.h"
#include "core/vector.h" #include "core/vector.h"
#include <type_traits> #include <type_traits>
@ -283,6 +284,9 @@ public:
return ret; return ret;
} }
_FORCE_INLINE_ Span<T> span() const { return Span(data, count); }
_FORCE_INLINE_ operator Span<T>() const { return span(); }
_FORCE_INLINE_ LocalVector() {} _FORCE_INLINE_ LocalVector() {}
_FORCE_INLINE_ LocalVector(const LocalVector &p_from) { _FORCE_INLINE_ LocalVector(const LocalVector &p_from) {
resize(p_from.size()); resize(p_from.size());
@ -290,12 +294,21 @@ public:
data[i] = p_from.data[i]; data[i] = p_from.data[i];
} }
} }
LocalVector(const Span<T> &p_from) {
resize(p_from.size());
for (U i = 0; i < count; i++) {
data[i] = p_from[i];
}
}
LocalVector(const Vector<T> &p_from) { LocalVector(const Vector<T> &p_from) {
resize(p_from.size()); resize(p_from.size());
for (U i = 0; i < count; i++) { for (U i = 0; i < count; i++) {
data[i] = p_from[i]; data[i] = p_from[i];
} }
} }
LocalVector(const PoolVector<T> &p_from) { LocalVector(const PoolVector<T> &p_from) {
resize(p_from.size()); resize(p_from.size());
typename PoolVector<T>::Read r = p_from.read(); typename PoolVector<T>::Read r = p_from.read();

View file

@ -396,7 +396,7 @@ public:
return 0; return 0;
} }
Vector<Vector3> convex_points = Geometry::compute_convex_mesh_points(&p_convex[0], p_convex.size()); Vector<Vector3> convex_points = Geometry::compute_convex_mesh_points(p_convex);
if (convex_points.size() == 0) { if (convex_points.size() == 0) {
return 0; return 0;
} }

View file

@ -31,6 +31,7 @@
#ifndef DELAUNAY_H #ifndef DELAUNAY_H
#define DELAUNAY_H #define DELAUNAY_H
#include "core/local_vector.h"
#include "core/math/rect2.h" #include "core/math/rect2.h"
class Delaunay2D { class Delaunay2D {
@ -58,7 +59,7 @@ public:
} }
}; };
static bool circum_circle_contains(const Vector<Vector2> &p_vertices, const Triangle &p_triangle, int p_vertex) { static bool circum_circle_contains(const Span<Vector2> &p_vertices, const Triangle &p_triangle, int p_vertex) {
Vector2 p1 = p_vertices[p_triangle.points[0]]; Vector2 p1 = p_vertices[p_triangle.points[0]];
Vector2 p2 = p_vertices[p_triangle.points[1]]; Vector2 p2 = p_vertices[p_triangle.points[1]];
Vector2 p3 = p_vertices[p_triangle.points[2]]; Vector2 p3 = p_vertices[p_triangle.points[2]];
@ -77,7 +78,7 @@ public:
return d <= r; return d <= r;
} }
static bool edge_compare(const Vector<Vector2> &p_vertices, const Edge &p_a, const Edge &p_b) { static bool edge_compare(const Span<Vector2> &p_vertices, const Edge &p_a, const Edge &p_b) {
if (p_vertices[p_a.edge[0]].is_equal_approx(p_vertices[p_b.edge[0]]) && p_vertices[p_a.edge[1]].is_equal_approx(p_vertices[p_b.edge[1]])) { if (p_vertices[p_a.edge[0]].is_equal_approx(p_vertices[p_b.edge[0]]) && p_vertices[p_a.edge[1]].is_equal_approx(p_vertices[p_b.edge[1]])) {
return true; return true;
} }
@ -89,12 +90,12 @@ public:
return false; return false;
} }
static Vector<Triangle> triangulate(const Vector<Vector2> &p_points) { static Vector<Triangle> triangulate(const Span<Vector2> &p_points) {
Vector<Vector2> points = p_points; LocalVector<Vector2> points(p_points);
Vector<Triangle> triangles; Vector<Triangle> triangles;
Rect2 rect; Rect2 rect;
for (int i = 0; i < p_points.size(); i++) { for (uint32_t i = 0; i < p_points.size(); i++) {
if (i == 0) { if (i == 0) {
rect.position = p_points[i]; rect.position = p_points[i];
} else { } else {
@ -111,7 +112,7 @@ public:
triangles.push_back(Triangle(p_points.size() + 0, p_points.size() + 1, p_points.size() + 2)); triangles.push_back(Triangle(p_points.size() + 0, p_points.size() + 1, p_points.size() + 2));
for (int i = 0; i < p_points.size(); i++) { for (uint32_t i = 0; i < p_points.size(); i++) {
//std::cout << "Traitement du point " << *p << std::endl; //std::cout << "Traitement du point " << *p << std::endl;
//std::cout << "_triangles contains " << _triangles.size() << " elements" << std::endl; //std::cout << "_triangles contains " << _triangles.size() << " elements" << std::endl;
@ -150,10 +151,12 @@ public:
} }
} }
int point_count = p_points.size();
for (int i = 0; i < triangles.size(); i++) { for (int i = 0; i < triangles.size(); i++) {
bool invalid = false; bool invalid = false;
for (int j = 0; j < 3; j++) { for (int j = 0; j < 3; j++) {
if (triangles[i].points[j] >= p_points.size()) { if (triangles[i].points[j] >= point_count) {
invalid = true; invalid = true;
break; break;
} }

View file

@ -1398,11 +1398,13 @@ bool Geometry::convex_hull_intersects_convex_hull(const Plane *p_planes_a, int p
return false; return false;
} }
Vector<Vector3> Geometry::compute_convex_mesh_points(const Plane *p_planes, int p_plane_count, real_t p_epsilon) { Vector<Vector3> Geometry::compute_convex_mesh_points(const Span<Plane> &p_planes, real_t p_epsilon) {
Vector<Vector3> points; Vector<Vector3> points;
// Iterate through every unique combination of any three planes. // Iterate through every unique combination of any three planes.
for (int i = p_plane_count - 1; i >= 0; i--) { int plane_count = p_planes.size();
for (int i = plane_count - 1; i >= 0; i--) {
for (int j = i - 1; j >= 0; j--) { for (int j = i - 1; j >= 0; j--) {
for (int k = j - 1; k >= 0; k--) { for (int k = j - 1; k >= 0; k--) {
// Find the point where these planes all cross over (if they // Find the point where these planes all cross over (if they
@ -1412,7 +1414,7 @@ Vector<Vector3> Geometry::compute_convex_mesh_points(const Plane *p_planes, int
// See if any *other* plane excludes this point because it's // See if any *other* plane excludes this point because it's
// on the wrong side. // on the wrong side.
bool excluded = false; bool excluded = false;
for (int n = 0; n < p_plane_count; n++) { for (int n = 0; n < plane_count; n++) {
if (n != i && n != j && n != k) { if (n != i && n != j && n != k) {
real_t dist = p_planes[n].distance_to(convex_shape_point); real_t dist = p_planes[n].distance_to(convex_shape_point);
if (dist > p_epsilon) { if (dist > p_epsilon) {

View file

@ -806,7 +806,7 @@ public:
return _polypath_offset(p_polygon, p_delta, p_join_type, p_end_type); return _polypath_offset(p_polygon, p_delta, p_join_type, p_end_type);
} }
static Vector<int> triangulate_delaunay_2d(const Vector<Vector2> &p_points) { static Vector<int> triangulate_delaunay_2d(const Span<Vector2> &p_points) {
Vector<Delaunay2D::Triangle> tr = Delaunay2D::triangulate(p_points); Vector<Delaunay2D::Triangle> tr = Delaunay2D::triangulate(p_points);
Vector<int> triangles; Vector<int> triangles;
@ -1017,7 +1017,7 @@ public:
}; };
static Vector<PackRectsResult> partial_pack_rects(const Vector<Vector2i> &p_sizes, const Size2i &p_atlas_size); static Vector<PackRectsResult> partial_pack_rects(const Vector<Vector2i> &p_sizes, const Size2i &p_atlas_size);
static Vector<Vector3> compute_convex_mesh_points(const Plane *p_planes, int p_plane_count, real_t p_epsilon = CMP_EPSILON); static Vector<Vector3> compute_convex_mesh_points(const Span<Plane> &p_planes, real_t p_epsilon = CMP_EPSILON);
static bool convex_hull_intersects_convex_hull(const Plane *p_planes_a, int p_plane_count_a, const Plane *p_planes_b, int p_plane_count_b); static bool convex_hull_intersects_convex_hull(const Plane *p_planes_a, int p_plane_count_a, const Plane *p_planes_b, int p_plane_count_b);
static real_t calculate_convex_hull_volume(const Geometry::MeshData &p_md); static real_t calculate_convex_hull_volume(const Geometry::MeshData &p_md);
static bool verify_indices(const int *p_indices, int p_num_indices, int p_num_vertices); static bool verify_indices(const int *p_indices, int p_num_indices, int p_num_vertices);

View file

@ -1575,7 +1575,7 @@ OCTREE_FUNC(int)::cull_convex(const Vector<Plane> &p_convex, T **p_result_array,
return 0; return 0;
} }
Vector<Vector3> convex_points = Geometry::compute_convex_mesh_points(&p_convex[0], p_convex.size()); Vector<Vector3> convex_points = Geometry::compute_convex_mesh_points(p_convex);
if (convex_points.size() == 0) { if (convex_points.size() == 0) {
return 0; return 0;
} }

220
core/span.h Normal file
View file

@ -0,0 +1,220 @@
/**************************************************************************/
/* span.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#pragma once
#include "core/error_macros.h"
#include "core/typedefs.h"
// Equivalent of std::span.
// Represents a view into a contiguous memory space.
// DISCLAIMER: This data type does not own the underlying buffer. DO NOT STORE IT.
// Additionally, for the lifetime of the Span, do not resize the buffer, and do not insert or remove elements from it.
// Failure to respect this may lead to crashes or undefined behavior.
template <typename T, class U = uint32_t>
class Span {
const T *_ptr = nullptr;
U _len = 0;
public:
static constexpr bool is_string = std::disjunction_v<
std::is_same<T, char>,
std::is_same<T, char16_t>,
std::is_same<T, char32_t>,
std::is_same<T, wchar_t>>;
_FORCE_INLINE_ constexpr Span() = default;
_FORCE_INLINE_ Span(const T *p_ptr, U p_len) :
_ptr(p_ptr), _len(p_len) {
#ifdef DEBUG_ENABLED
// TODO In c++20, make this check run only in non-consteval, and make this constructor constexpr.
if (_ptr == nullptr && _len > 0) {
ERR_PRINT("Internal bug, please report: Span was created from nullptr with size > 0. Recovering by using size = 0.");
_len = 0;
}
#endif
}
// Allows creating Span directly from C arrays and string literals.
template <size_t N>
_FORCE_INLINE_ constexpr Span(const T (&p_array)[N]) :
_ptr(p_array), _len(N) {
if constexpr (is_string) {
// Cut off the \0 terminator implicitly added to string literals.
if (N > 0 && p_array[N - 1] == '\0') {
_len--;
}
}
}
_FORCE_INLINE_ constexpr U size() const { return _len; }
_FORCE_INLINE_ constexpr bool is_empty() const { return _len == 0; }
_FORCE_INLINE_ constexpr const T *ptr() const { return _ptr; }
// NOTE: Span subscripts sanity check the bounds to avoid undefined behavior.
// This is slower than direct buffer access and can prevent autovectorization.
// If the bounds are known, use ptr() subscript instead.
_FORCE_INLINE_ constexpr const T &operator[](U p_idx) const {
CRASH_COND(p_idx >= _len);
return _ptr[p_idx];
}
_FORCE_INLINE_ constexpr const T *begin() const { return _ptr; }
_FORCE_INLINE_ constexpr const T *end() const { return _ptr + _len; }
template <typename T1>
_FORCE_INLINE_ constexpr Span<T1> reinterpret() const {
return Span<T1>(reinterpret_cast<const T1 *>(_ptr), _len * sizeof(T) / sizeof(T1));
}
// Algorithms.
constexpr int64_t find(const T &p_val, U p_from = 0) const;
constexpr int64_t find_sequence(const Span<T> &p_span, U p_from = 0) const;
constexpr int64_t rfind(const T &p_val, U p_from) const;
_FORCE_INLINE_ constexpr int64_t rfind(const T &p_val) const { return rfind(p_val, size() - 1); }
constexpr int64_t rfind_sequence(const Span<T> &p_span, U p_from) const;
_FORCE_INLINE_ constexpr int64_t rfind_sequence(const Span<T> &p_span) const { return rfind_sequence(p_span, size() - p_span.size()); }
constexpr U count(const T &p_val) const;
/// Find the index of the given value using binary search.
/// Note: Assumes that elements in the span are sorted. Otherwise, use find() instead.
template <typename Comparator = Comparator<T>>
constexpr U bisect(const T &p_value, bool p_before, Comparator compare = Comparator()) const;
/// The caller is responsible to ensure size() > 0.
constexpr T max() const;
};
template <typename T, class U>
constexpr int64_t Span<T, U>::find(const T &p_val, U p_from) const {
for (U i = p_from; i < size(); i++) {
if (ptr()[i] == p_val) {
return i;
}
}
return -1;
}
template <typename T, class U>
constexpr int64_t Span<T, U>::find_sequence(const Span<T> &p_span, U p_from) const {
for (U i = p_from; i <= size() - p_span.size(); i++) {
bool found = true;
for (U j = 0; j < p_span.size(); j++) {
if (ptr()[i + j] != p_span.ptr()[j]) {
found = false;
break;
}
}
if (found) {
return i;
}
}
return -1;
}
template <typename T, class U>
constexpr int64_t Span<T, U>::rfind(const T &p_val, U p_from) const {
for (int64_t i = p_from; i >= 0; i--) {
if (ptr()[i] == p_val) {
return i;
}
}
return -1;
}
template <typename T, class U>
constexpr int64_t Span<T, U>::rfind_sequence(const Span<T> &p_span, U p_from) const {
for (int64_t i = p_from; i >= 0; i--) {
bool found = true;
for (U j = 0; j < p_span.size(); j++) {
if (ptr()[i + j] != p_span.ptr()[j]) {
found = false;
break;
}
}
if (found) {
return i;
}
}
return -1;
}
template <typename T, class U>
constexpr U Span<T, U>::count(const T &p_val) const {
U amount = 0;
for (U i = 0; i < size(); i++) {
if (ptr()[i] == p_val) {
amount++;
}
}
return amount;
}
template <typename T, class U>
template <typename Comparator>
constexpr U Span<T, U>::bisect(const T &p_value, bool p_before, Comparator compare) const {
U lo = 0;
U hi = size();
if (p_before) {
while (lo < hi) {
const U mid = (lo + hi) / 2;
if (compare(ptr()[mid], p_value)) {
lo = mid + 1;
} else {
hi = mid;
}
}
} else {
while (lo < hi) {
const U mid = (lo + hi) / 2;
if (compare(p_value, ptr()[mid])) {
hi = mid;
} else {
lo = mid + 1;
}
}
}
return lo;
}
template <typename T, class U>
constexpr T Span<T, U>::max() const {
DEV_ASSERT(size() > 0);
T max_val = _ptr[0];
for (U i = 1; i < _len; ++i) {
if (_ptr[i] > max_val) {
max_val = _ptr[i];
}
}
return max_val;
}

View file

@ -84,6 +84,10 @@ public:
_FORCE_INLINE_ const T &get(int p_index) const { return _cowdata.get(p_index); } _FORCE_INLINE_ const T &get(int p_index) const { return _cowdata.get(p_index); }
_FORCE_INLINE_ void set(int p_index, const T &p_elem) { _cowdata.set(p_index, p_elem); } _FORCE_INLINE_ void set(int p_index, const T &p_elem) { _cowdata.set(p_index, p_elem); }
_FORCE_INLINE_ int size() const { return _cowdata.size(); } _FORCE_INLINE_ int size() const { return _cowdata.size(); }
_FORCE_INLINE_ operator Span<T>() const { return _cowdata.span(); }
_FORCE_INLINE_ Span<T> span() const { return _cowdata.span(); }
Error resize(int p_size) { return _cowdata.resize(p_size); } Error resize(int p_size) { return _cowdata.resize(p_size); }
_FORCE_INLINE_ const T &operator[](int p_index) const { return _cowdata.get(p_index); } _FORCE_INLINE_ const T &operator[](int p_index) const { return _cowdata.get(p_index); }
Error insert(int p_pos, T p_val) { return _cowdata.insert(p_pos, p_val); } Error insert(int p_pos, T p_val) { return _cowdata.insert(p_pos, p_val); }

View file

@ -535,7 +535,7 @@ bool EditorSpatialGizmo::intersect_frustum(const Camera *p_camera, const Vector<
transformed_frustum.push_back(it.xform(p_frustum[i])); transformed_frustum.push_back(it.xform(p_frustum[i]));
} }
Vector<Vector3> convex_points = Geometry::compute_convex_mesh_points(p_frustum.ptr(), p_frustum.size()); Vector<Vector3> convex_points = Geometry::compute_convex_mesh_points(p_frustum);
if (collision_mesh->inside_convex_shape(transformed_frustum.ptr(), transformed_frustum.size(), convex_points.ptr(), convex_points.size(), mesh_scale)) { if (collision_mesh->inside_convex_shape(transformed_frustum.ptr(), transformed_frustum.size(), convex_points.ptr(), convex_points.size(), mesh_scale)) {
return true; return true;

View file

@ -172,7 +172,7 @@ PoolVector<Vector3> Room::generate_points() {
scaled_epsilon = MAX(scaled_epsilon * 0.01, 0.001); scaled_epsilon = MAX(scaled_epsilon * 0.01, 0.001);
LocalVector<Vector3, int32_t> pts; LocalVector<Vector3, int32_t> pts;
pts = Geometry::compute_convex_mesh_points(&_planes[0], _planes.size(), scaled_epsilon); pts = Geometry::compute_convex_mesh_points(Span<Plane>(_planes.ptr(), _planes.size()), scaled_epsilon);
// eliminate duplicates // eliminate duplicates
for (int n = 0; n < pts.size(); n++) { for (int n = 0; n < pts.size(); n++) {

View file

@ -784,7 +784,7 @@ void RoomManager::_generate_room_overlap_zones() {
memcpy(dest, &other->_planes[0], other->_planes.size() * sizeof(Plane)); memcpy(dest, &other->_planes[0], other->_planes.size() * sizeof(Plane));
Vector<Vector3> overlap_pts = Geometry::compute_convex_mesh_points(planes.ptr(), planes.size()); Vector<Vector3> overlap_pts = Geometry::compute_convex_mesh_points(Span<Plane>(planes.ptr(), planes.size()));
if (overlap_pts.size() < 4) { if (overlap_pts.size() < 4) {
continue; continue;
@ -1642,7 +1642,7 @@ void RoomManager::_build_simplified_bound(const Room *p_room, Geometry::MeshData
return; return;
} }
Vector<Vector3> pts = Geometry::compute_convex_mesh_points(&r_planes[0], r_planes.size(), 0.001); Vector<Vector3> pts = Geometry::compute_convex_mesh_points(Span<Plane>(r_planes.ptr(), r_planes.size()), 0.001);
Error err = _build_room_convex_hull(p_room, pts, r_md); Error err = _build_room_convex_hull(p_room, pts, r_md);
if (err != OK) { if (err != OK) {