Fix build for core classes.

This commit is contained in:
Relintai 2023-12-18 23:12:55 +01:00
parent 76a4ac5535
commit d694c74aed
32 changed files with 1942 additions and 303 deletions

View File

@ -10,5 +10,30 @@
#g++ -Wall -fexceptions -I/usr/include/SDL2 -D_REENTRANT -g -Isfw -c sfw/aabb.cpp -o sfw/aabb.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/aabb.cpp -o sfw/aabb.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/basis.cpp -o sfw/basis.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/color.cpp -o sfw/color.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/face3.cpp -o sfw/face3.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/logger.cpp -o sfw/logger.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/math_funcs.cpp -o sfw/math_funcs.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/memory.cpp -o sfw/memory.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/pcg.cpp -o sfw/pcg.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/plane.cpp -o sfw/plane.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/projection.cpp -o sfw/projection.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/quaternion.cpp -o sfw/quaternion.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/random_pcg.cpp -o sfw/random_pcg.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/rect2.cpp -o sfw/rect2.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/rect2i.cpp -o sfw/rect2i.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/safe_refcount.cpp -o sfw/safe_refcount.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/transform_2d.cpp -o sfw/transform_2d.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/transform.cpp -o sfw/transform.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/ustring.cpp -o sfw/ustring.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/vector2.cpp -o sfw/vector2.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/vector2i.cpp -o sfw/vector2i.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/vector3.cpp -o sfw/vector3.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/vector3i.cpp -o sfw/vector3i.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/vector4.cpp -o sfw/vector4.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/vector4i.cpp -o sfw/vector4i.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/pool_vector.cpp -o sfw/pool_vector.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/pool_allocator.cpp -o sfw/pool_allocator.o
g++ -Wall -D_REENTRANT -g -Isfw -c sfw/mutex.cpp -o sfw/mutex.o

View File

@ -31,10 +31,8 @@
#include "color.h"
#include "rb_map.h"
#include "math_funcs.h"
uint32_t Color::to_argb32() const {
uint32_t c = (uint8_t)Math::round(a * 255);
c <<= 8;
@ -399,24 +397,6 @@ bool Color::html_is_valid(const String &p_color) {
return true;
}
Color Color::named(const String &p_name) {
if (_named_colors.empty()) {
_populate_named_colors(); // from color_names.inc
}
String name = p_name;
// Normalize name
name = name.replace(" ", "");
name = name.replace("-", "");
name = name.replace("_", "");
name = name.replace("'", "");
name = name.replace(".", "");
name = name.to_lower();
const RBMap<String, Color>::Element *color = _named_colors.find(name);
ERR_FAIL_NULL_V_MSG(color, Color(), "Invalid color name: " + p_name + ".");
return color->value();
}
String _to_hex(float p_val) {
int v = Math::round(p_val * 255);
v = CLAMP(v, 0, 255);
@ -456,12 +436,6 @@ Color Color::from_hsv(float p_h, float p_s, float p_v, float p_a) const {
return c;
}
// FIXME: Remove once Pandemonium 3.1 has been released
float Color::gray() const {
WARN_DEPRECATED_MSG("'Color.gray()' is deprecated and will be removed in a future version. Use 'Color.v' for a better grayscale approximation.");
return (r + g + b) / 3.0;
}
Color::operator String() const {
return "(" + String::num(r, 4) + ", " + String::num(g, 4) + ", " + String::num(b, 4) + ", " + String::num(a, 4) + ")";
}

View File

@ -55,7 +55,6 @@ struct _NO_DISCARD_CLASS_ Color {
uint64_t to_rgba64() const;
uint64_t to_argb64() const;
uint64_t to_abgr64() const;
float gray() const;
float get_h() const;
float get_s() const;
float get_v() const;
@ -190,7 +189,6 @@ struct _NO_DISCARD_CLASS_ Color {
static Color hex64(uint64_t p_hex);
static Color html(const String &p_color);
static bool html_is_valid(const String &p_color);
static Color named(const String &p_name);
String to_html(bool p_alpha = true) const;
Color from_hsv(float p_h, float p_s, float p_v, float p_a) const;
static Color from_rgbe9995(uint32_t p_rgbe);

View File

@ -107,11 +107,13 @@ int Face3::split_by_plane(const Plane &p_plane, Face3 p_res[3], bool p_is_point_
}
bool Face3::intersects_ray(const Vector3 &p_from, const Vector3 &p_dir, Vector3 *p_intersection) const {
return Geometry::ray_intersects_triangle(p_from, p_dir, vertex[0], vertex[1], vertex[2], p_intersection);
//return Geometry::ray_intersects_triangle(p_from, p_dir, vertex[0], vertex[1], vertex[2], p_intersection);
return false;
}
bool Face3::intersects_segment(const Vector3 &p_from, const Vector3 &p_dir, Vector3 *p_intersection) const {
return Geometry::segment_intersects_triangle(p_from, p_dir, vertex[0], vertex[1], vertex[2], p_intersection);
//return Geometry::segment_intersects_triangle(p_from, p_dir, vertex[0], vertex[1], vertex[2], p_intersection);
return false;
}
bool Face3::is_degenerate() const {

View File

@ -10,7 +10,7 @@
void RLogger::print_trace(const String &str) {
print_trace(str.data());
print_trace(str.utf8().get_data());
}
void RLogger::print_trace(const char *str) {
printf("T %s\n", str);
@ -19,11 +19,11 @@ void RLogger::print_trace(const char *p_function, const char *p_file, int p_line
printf("T | %s::%s:%d | %s\n", p_file, p_function, p_line, str);
}
void RLogger::print_trace(const char *p_function, const char *p_file, int p_line, const String &str) {
printf("T | %s::%s:%d | %s\n", p_file, p_function, p_line, str.c_str());
printf("T | %s::%s:%d | %s\n", p_file, p_function, p_line, str.utf8().get_data());
}
void RLogger::print_message(const String &str) {
print_message(str.data());
print_message(str.utf8().get_data());
}
void RLogger::print_message(const char *str) {
printf("M %s\n", str);
@ -32,11 +32,11 @@ void RLogger::print_message(const char *p_function, const char *p_file, int p_li
printf("M | %s::%s:%d | %s\n", p_file, p_function, p_line, str);
}
void RLogger::print_message(const char *p_function, const char *p_file, int p_line, const String &str) {
printf("M | %s::%s:%d | %s\n", p_file, p_function, p_line, str.c_str());
printf("M | %s::%s:%d | %s\n", p_file, p_function, p_line, str.utf8().get_data());
}
void RLogger::print_warning(const String &str) {
print_warning(str.data());
print_warning(str.utf8().get_data());
}
void RLogger::print_warning(const char *str) {
printf("W %s\n", str);
@ -45,11 +45,11 @@ void RLogger::print_warning(const char *p_function, const char *p_file, int p_li
printf("W | %s::%s:%d | %s\n", p_file, p_function, p_line, str);
}
void RLogger::print_warning(const char *p_function, const char *p_file, int p_line, const String &str) {
printf("W | %s::%s:%d | %s\n", p_file, p_function, p_line, str.c_str());
printf("W | %s::%s:%d | %s\n", p_file, p_function, p_line, str.utf8().get_data());
}
void RLogger::print_error(const String &str) {
print_error(str.data());
print_error(str.utf8().get_data());
}
void RLogger::print_error(const char *str) {
printf("E %s\n", str);
@ -59,7 +59,7 @@ void RLogger::print_error(const char *p_function, const char *p_file, int p_line
printf("E | %s::%s:%d | %s\n", p_file, p_function, p_line, str);
}
void RLogger::print_error(const char *p_function, const char *p_file, int p_line, const String &str) {
printf("E | %s::%s:%d | %s\n", p_file, p_function, p_line, str.c_str());
printf("E | %s::%s:%d | %s\n", p_file, p_function, p_line, str.utf8().get_data());
}
void RLogger::print_msg_error(const char *p_function, const char *p_file, int p_line, const char *p_msg, const char *str) {
printf("E | %s::%s:%d | :: %s. %s\n", p_file, p_function, p_line, str, p_msg);
@ -69,7 +69,7 @@ void RLogger::print_index_error(const char *p_function, const char *p_file, int
}
void RLogger::log_trace(const String &str) {
log_trace(str.data());
log_trace(str.utf8().get_data());
}
void RLogger::log_trace(const char *str) {
printf("T %s\n", str);
@ -78,11 +78,11 @@ void RLogger::log_trace(const char *p_function, const char *p_file, int p_line,
printf("T | %s::%s:%d | %s\n", p_file, p_function, p_line, str);
}
void RLogger::log_trace(const char *p_function, const char *p_file, int p_line, const String &str) {
printf("T | %s::%s:%d | %s\n", p_file, p_function, p_line, str.c_str());
printf("T | %s::%s:%d | %s\n", p_file, p_function, p_line, str.utf8().get_data());
}
void RLogger::log_message(const String &str) {
log_message(str.data());
log_message(str.utf8().get_data());
}
void RLogger::log_message(const char *str) {
printf("M %s\n", str);
@ -91,11 +91,11 @@ void RLogger::log_message(const char *p_function, const char *p_file, int p_line
printf("M | %s::%s:%d | %s\n", p_file, p_function, p_line, str);
}
void RLogger::log_message(const char *p_function, const char *p_file, int p_line, const String &str) {
printf("M | %s::%s:%d | %s\n", p_file, p_function, p_line, str.c_str());
printf("M | %s::%s:%d | %s\n", p_file, p_function, p_line, str.utf8().get_data());
}
void RLogger::log_warning(const String &str) {
log_warning(str.data());
log_warning(str.utf8().get_data());
}
void RLogger::log_warning(const char *str) {
printf("W %s\n", str);
@ -104,11 +104,11 @@ void RLogger::log_warning(const char *p_function, const char *p_file, int p_line
printf("W | %s::%s:%d | %s\n", p_file, p_function, p_line, str);
}
void RLogger::log_warning(const char *p_function, const char *p_file, int p_line, const String &str) {
printf("W | %s::%s:%d | %s\n", p_file, p_function, p_line, str.c_str());
printf("W | %s::%s:%d | %s\n", p_file, p_function, p_line, str.utf8().get_data());
}
void RLogger::log_error(const String &str) {
log_error(str.data());
log_error(str.utf8().get_data());
}
void RLogger::log_error(const char *str) {
printf("E %s\n", str);
@ -118,7 +118,7 @@ void RLogger::log_error(const char *p_function, const char *p_file, int p_line,
printf("E | %s::%s:%d | %s\n", p_file, p_function, p_line, str);
}
void RLogger::log_error(const char *p_function, const char *p_file, int p_line, const String &str) {
printf("E | %s::%s:%d | %s\n", p_file, p_function, p_line, str.c_str());
printf("E | %s::%s:%d | %s\n", p_file, p_function, p_line, str.utf8().get_data());
}
void RLogger::log_msg_error(const char *p_function, const char *p_file, int p_line, const char *p_msg, const char *str) {
printf("E | %s::%s:%d | :: %s. %s\n", p_file, p_function, p_line, str, p_msg);
@ -128,31 +128,31 @@ void RLogger::log_index_error(const char *p_function, const char *p_file, int p_
}
String *RLogger::get_string_ptr(const int p_default_size) {
return new String(p_default_size);
return memnew(String());
}
String *RLogger::get_string_ptr(const char *p_function, const char *p_file, int p_line, const int p_default_size) {
String *s = new String(p_default_size);
String *s = memnew(String());
s->append_str(p_function);
s->append_str("::");
s->append_str(p_file);
s->append_str(":");
s->append_str(String::num(p_line));
s->append_str(" | ");
s->operator+=(p_function);
s->operator+=("::");
s->operator+=(p_file);
s->operator+=(":");
s->operator+=(String::num(p_line));
s->operator+=(" | ");
return s;
}
String *RLogger::get_string_ptr(const char *p_prefix, const char *p_function, const char *p_file, int p_line, const int p_default_size) {
String *s = new String(p_default_size);
String *s = memnew(String());
s->append_str(p_prefix);
s->append_str(" | ");
s->append_str(p_function);
s->append_str("::");
s->append_str(p_file);
s->append_str(":");
s->append_str(String::num(p_line));
s->append_str(" | ");
s->operator+=(p_prefix);
s->operator+=(" | ");
s->operator+=(p_function);
s->operator+=("::");
s->operator+=(p_file);
s->operator+=(":");
s->operator+=(String::num(p_line));
s->operator+=(" | ");
return s;
}
@ -162,22 +162,22 @@ void RLogger::return_string_ptr(String *str) {
String *RLogger::get_trace_string_ptr(const int p_default_size) {
String *str = get_string_ptr(p_default_size);
str->append_str("T ");
str->operator+=("T ");
return str;
}
String *RLogger::get_message_string_ptr(const int p_default_size) {
String *str = get_string_ptr(p_default_size);
str->append_str("M ");
str->operator+=("M ");
return str;
}
String *RLogger::get_warning_string_ptr(const int p_default_size) {
String *str = get_string_ptr(p_default_size);
str->append_str("W ");
str->operator+=("W ");
return str;
}
String *RLogger::get_error_string_ptr(const int p_default_size) {
String *str = get_string_ptr(p_default_size);
str->append_str("E ");
str->operator+=("E ");
return str;
}
@ -195,7 +195,7 @@ String *RLogger::get_error_string_ptr(const char *p_function, const char *p_file
}
void RLogger::log_ptr(String *str) {
printf("%s\n", str->data());
printf("%s\n", str->utf8().get_data());
}
void RLogger::log_ret_ptr(String *str) {

View File

@ -96,7 +96,6 @@ int Math::range_step_decimals(double p_step) {
}
double Math::dectime(double p_value, double p_amount, double p_step) {
WARN_DEPRECATED_MSG("The `dectime()` function has been deprecated and will be removed in Godot 4.0. Use `move_toward()` instead.");
double sgn = p_value < 0 ? -1.0 : 1.0;
double val = Math::abs(p_value);
val -= p_amount * p_step;

View File

@ -31,8 +31,8 @@
#include "memory.h"
#include "core/error/error_macros.h"
#include "core/os/safe_refcount.h"
#include "error_macros.h"
#include "safe_refcount.h"
#include <stdio.h>
#include <stdlib.h>

49
sfw/mutex.cpp Normal file
View File

@ -0,0 +1,49 @@
/*************************************************************************/
/* mutex.cpp */
/*************************************************************************/
/* This file is part of: */
/* PANDEMONIUM ENGINE */
/* https://github.com/Relintai/pandemonium_engine */
/*************************************************************************/
/* Copyright (c) 2022-present Péter Magyar. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* Copyright (c) 2007-2022 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. */
/*************************************************************************/
#include "mutex.h"
static Mutex _global_mutex;
void _global_lock() {
_global_mutex.lock();
}
void _global_unlock() {
_global_mutex.unlock();
}
#ifndef NO_THREADS
template class MutexImpl<std::recursive_mutex>;
template class MutexImpl<std::mutex>;
#endif

121
sfw/mutex.h Normal file
View File

@ -0,0 +1,121 @@
#ifndef MUTEX_H
#define MUTEX_H
/*************************************************************************/
/* mutex.h */
/*************************************************************************/
/* This file is part of: */
/* PANDEMONIUM ENGINE */
/* https://github.com/Relintai/pandemonium_engine */
/*************************************************************************/
/* Copyright (c) 2022-present Péter Magyar. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* Copyright (c) 2007-2022 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. */
/*************************************************************************/
#include "error_list.h"
#include "typedefs.h"
#if !defined(NO_THREADS)
#include <mutex>
template <class StdMutexT>
class MutexImpl {
mutable StdMutexT mutex;
friend class MutexLock;
public:
_ALWAYS_INLINE_ void lock() const {
mutex.lock();
}
_ALWAYS_INLINE_ void unlock() const {
mutex.unlock();
}
_ALWAYS_INLINE_ Error try_lock() const {
return mutex.try_lock() ? OK : ERR_BUSY;
}
};
// This is written this way instead of being a template to overcome a limitation of C++ pre-17
// that would require MutexLock to be used like this: MutexLock<Mutex> lock;
class MutexLock {
union {
std::recursive_mutex *recursive_mutex;
std::mutex *mutex;
};
bool recursive;
public:
_ALWAYS_INLINE_ explicit MutexLock(const MutexImpl<std::recursive_mutex> &p_mutex) :
recursive_mutex(&p_mutex.mutex),
recursive(true) {
recursive_mutex->lock();
}
_ALWAYS_INLINE_ explicit MutexLock(const MutexImpl<std::mutex> &p_mutex) :
mutex(&p_mutex.mutex),
recursive(false) {
mutex->lock();
}
_ALWAYS_INLINE_ ~MutexLock() {
if (recursive) {
recursive_mutex->unlock();
} else {
mutex->unlock();
}
}
};
using Mutex = MutexImpl<std::recursive_mutex>; // Recursive, for general use
using BinaryMutex = MutexImpl<std::mutex>; // Non-recursive, handle with care
extern template class MutexImpl<std::recursive_mutex>;
extern template class MutexImpl<std::mutex>;
#else
class FakeMutex {
FakeMutex() {}
};
template <class MutexT>
class MutexImpl {
public:
_ALWAYS_INLINE_ void lock() const {}
_ALWAYS_INLINE_ void unlock() const {}
_ALWAYS_INLINE_ Error try_lock() const { return OK; }
};
class MutexLock {
public:
explicit MutexLock(const MutexImpl<FakeMutex> &p_mutex) {}
};
using Mutex = MutexImpl<FakeMutex>;
using BinaryMutex = MutexImpl<FakeMutex>; // Non-recursive, handle with care
#endif // !NO_THREADS
#endif // MUTEX_H

View File

@ -32,7 +32,6 @@
#include "plane.h"
#include "math_funcs.h"
#include "variant/variant.h"
void Plane::set_normal(const Vector3 &p_normal) {
normal = p_normal;

585
sfw/pool_allocator.cpp Normal file
View File

@ -0,0 +1,585 @@
/*************************************************************************/
/* pool_allocator.cpp */
/*************************************************************************/
/* This file is part of: */
/* PANDEMONIUM ENGINE */
/* https://github.com/Relintai/pandemonium_engine */
/*************************************************************************/
/* Copyright (c) 2022-present Péter Magyar. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* Copyright (c) 2007-2022 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. */
/*************************************************************************/
#include "pool_allocator.h"
#include "error_macros.h"
#include "memory.h"
#define COMPACT_CHUNK(m_entry, m_to_pos) \
do { \
void *_dst = &((unsigned char *)pool)[m_to_pos]; \
void *_src = &((unsigned char *)pool)[(m_entry).pos]; \
memmove(_dst, _src, aligned((m_entry).len)); \
(m_entry).pos = m_to_pos; \
} while (0);
void PoolAllocator::mt_lock() const {
}
void PoolAllocator::mt_unlock() const {
}
bool PoolAllocator::get_free_entry(EntryArrayPos *p_pos) {
if (entry_count == entry_max) {
return false;
}
for (int i = 0; i < entry_max; i++) {
if (entry_array[i].len == 0) {
*p_pos = i;
return true;
}
}
ERR_PRINT("Out of memory Chunks!");
return false; //
}
/**
* Find a hole
* @param p_pos The hole is behind the block pointed by this variable upon return. if pos==entry_count, then allocate at end
* @param p_for_size hole size
* @return false if hole found, true if no hole found
*/
bool PoolAllocator::find_hole(EntryArrayPos *p_pos, int p_for_size) {
/* position where previous entry ends. Defaults to zero (begin of pool) */
int prev_entry_end_pos = 0;
for (int i = 0; i < entry_count; i++) {
Entry &entry = entry_array[entry_indices[i]];
/* determine hole size to previous entry */
int hole_size = entry.pos - prev_entry_end_pos;
/* determine if what we want fits in that hole */
if (hole_size >= p_for_size) {
*p_pos = i;
return true;
}
/* prepare for next one */
prev_entry_end_pos = entry_end(entry);
}
/* No holes between entries, check at the end..*/
if ((pool_size - prev_entry_end_pos) >= p_for_size) {
*p_pos = entry_count;
return true;
}
return false;
}
void PoolAllocator::compact(int p_up_to) {
uint32_t prev_entry_end_pos = 0;
if (p_up_to < 0) {
p_up_to = entry_count;
}
for (int i = 0; i < p_up_to; i++) {
Entry &entry = entry_array[entry_indices[i]];
/* determine hole size to previous entry */
int hole_size = entry.pos - prev_entry_end_pos;
/* if we can compact, do it */
if (hole_size > 0 && !entry.lock) {
COMPACT_CHUNK(entry, prev_entry_end_pos);
}
/* prepare for next one */
prev_entry_end_pos = entry_end(entry);
}
}
void PoolAllocator::compact_up(int p_from) {
uint32_t next_entry_end_pos = pool_size; // - static_area_size;
for (int i = entry_count - 1; i >= p_from; i--) {
Entry &entry = entry_array[entry_indices[i]];
/* determine hole size to nextious entry */
int hole_size = next_entry_end_pos - (entry.pos + aligned(entry.len));
/* if we can compact, do it */
if (hole_size > 0 && !entry.lock) {
COMPACT_CHUNK(entry, (next_entry_end_pos - aligned(entry.len)));
}
/* prepare for next one */
next_entry_end_pos = entry.pos;
}
}
bool PoolAllocator::find_entry_index(EntryIndicesPos *p_map_pos, Entry *p_entry) {
EntryArrayPos entry_pos = entry_max;
for (int i = 0; i < entry_count; i++) {
if (&entry_array[entry_indices[i]] == p_entry) {
entry_pos = i;
break;
}
}
if (entry_pos == entry_max) {
return false;
}
*p_map_pos = entry_pos;
return true;
}
PoolAllocator::ID PoolAllocator::alloc(int p_size) {
ERR_FAIL_COND_V(p_size < 1, POOL_ALLOCATOR_INVALID_ID);
ERR_FAIL_COND_V(p_size > free_mem, POOL_ALLOCATOR_INVALID_ID);
mt_lock();
if (entry_count == entry_max) {
mt_unlock();
ERR_PRINT("entry_count==entry_max");
return POOL_ALLOCATOR_INVALID_ID;
}
int size_to_alloc = aligned(p_size);
EntryIndicesPos new_entry_indices_pos;
if (!find_hole(&new_entry_indices_pos, size_to_alloc)) {
/* No hole could be found, try compacting mem */
compact();
/* Then search again */
if (!find_hole(&new_entry_indices_pos, size_to_alloc)) {
mt_unlock();
ERR_FAIL_V_MSG(POOL_ALLOCATOR_INVALID_ID, "Memory can't be compacted further.");
}
}
EntryArrayPos new_entry_array_pos;
bool found_free_entry = get_free_entry(&new_entry_array_pos);
if (!found_free_entry) {
mt_unlock();
ERR_FAIL_V_MSG(POOL_ALLOCATOR_INVALID_ID, "No free entry found in PoolAllocator.");
}
/* move all entry indices up, make room for this one */
for (int i = entry_count; i > new_entry_indices_pos; i--) {
entry_indices[i] = entry_indices[i - 1];
}
entry_indices[new_entry_indices_pos] = new_entry_array_pos;
entry_count++;
Entry &entry = entry_array[entry_indices[new_entry_indices_pos]];
entry.len = p_size;
entry.pos = (new_entry_indices_pos == 0) ? 0 : entry_end(entry_array[entry_indices[new_entry_indices_pos - 1]]); //alloc either at beginning or end of previous
entry.lock = 0;
entry.check = (check_count++) & CHECK_MASK;
free_mem -= size_to_alloc;
if (free_mem < free_mem_peak) {
free_mem_peak = free_mem;
}
ID retval = (entry_indices[new_entry_indices_pos] << CHECK_BITS) | entry.check;
mt_unlock();
//ERR_FAIL_COND_V( (uintptr_t)get(retval)%align != 0, retval );
return retval;
}
PoolAllocator::Entry *PoolAllocator::get_entry(ID p_mem) {
unsigned int check = p_mem & CHECK_MASK;
int entry = p_mem >> CHECK_BITS;
ERR_FAIL_INDEX_V(entry, entry_max, nullptr);
ERR_FAIL_COND_V(entry_array[entry].check != check, nullptr);
ERR_FAIL_COND_V(entry_array[entry].len == 0, nullptr);
return &entry_array[entry];
}
const PoolAllocator::Entry *PoolAllocator::get_entry(ID p_mem) const {
unsigned int check = p_mem & CHECK_MASK;
int entry = p_mem >> CHECK_BITS;
ERR_FAIL_INDEX_V(entry, entry_max, nullptr);
ERR_FAIL_COND_V(entry_array[entry].check != check, nullptr);
ERR_FAIL_COND_V(entry_array[entry].len == 0, nullptr);
return &entry_array[entry];
}
void PoolAllocator::free(ID p_mem) {
mt_lock();
Entry *e = get_entry(p_mem);
if (!e) {
mt_unlock();
ERR_PRINT("!e");
return;
}
if (e->lock) {
mt_unlock();
ERR_PRINT("e->lock");
return;
}
EntryIndicesPos entry_indices_pos;
bool index_found = find_entry_index(&entry_indices_pos, e);
if (!index_found) {
mt_unlock();
ERR_FAIL_COND(!index_found);
}
for (int i = entry_indices_pos; i < (entry_count - 1); i++) {
entry_indices[i] = entry_indices[i + 1];
}
entry_count--;
free_mem += aligned(e->len);
e->clear();
mt_unlock();
}
int PoolAllocator::get_size(ID p_mem) const {
int size;
mt_lock();
const Entry *e = get_entry(p_mem);
if (!e) {
mt_unlock();
ERR_PRINT("!e");
return 0;
}
size = e->len;
mt_unlock();
return size;
}
Error PoolAllocator::resize(ID p_mem, int p_new_size) {
mt_lock();
Entry *e = get_entry(p_mem);
if (!e) {
mt_unlock();
ERR_FAIL_COND_V(!e, ERR_INVALID_PARAMETER);
}
if (needs_locking && e->lock) {
mt_unlock();
ERR_FAIL_COND_V(e->lock, ERR_ALREADY_IN_USE);
}
uint32_t alloc_size = aligned(p_new_size);
if ((uint32_t)aligned(e->len) == alloc_size) {
e->len = p_new_size;
mt_unlock();
return OK;
} else if (e->len > (uint32_t)p_new_size) {
free_mem += aligned(e->len);
free_mem -= alloc_size;
e->len = p_new_size;
mt_unlock();
return OK;
}
//p_new_size = align(p_new_size)
int _free = free_mem; // - static_area_size;
if (uint32_t(_free + aligned(e->len)) < alloc_size) {
mt_unlock();
ERR_FAIL_V(ERR_OUT_OF_MEMORY);
};
EntryIndicesPos entry_indices_pos;
bool index_found = find_entry_index(&entry_indices_pos, e);
if (!index_found) {
mt_unlock();
ERR_FAIL_COND_V(!index_found, ERR_BUG);
}
//no need to move stuff around, it fits before the next block
uint32_t next_pos;
if (entry_indices_pos + 1 == entry_count) {
next_pos = pool_size; // - static_area_size;
} else {
next_pos = entry_array[entry_indices[entry_indices_pos + 1]].pos;
};
if ((next_pos - e->pos) > alloc_size) {
free_mem += aligned(e->len);
e->len = p_new_size;
free_mem -= alloc_size;
mt_unlock();
return OK;
}
//it doesn't fit, compact around BEFORE current index (make room behind)
compact(entry_indices_pos + 1);
if ((next_pos - e->pos) > alloc_size) {
//now fits! hooray!
free_mem += aligned(e->len);
e->len = p_new_size;
free_mem -= alloc_size;
mt_unlock();
if (free_mem < free_mem_peak) {
free_mem_peak = free_mem;
}
return OK;
}
//STILL doesn't fit, compact around AFTER current index (make room after)
compact_up(entry_indices_pos + 1);
if ((entry_array[entry_indices[entry_indices_pos + 1]].pos - e->pos) > alloc_size) {
//now fits! hooray!
free_mem += aligned(e->len);
e->len = p_new_size;
free_mem -= alloc_size;
mt_unlock();
if (free_mem < free_mem_peak) {
free_mem_peak = free_mem;
}
return OK;
}
mt_unlock();
ERR_FAIL_V(ERR_OUT_OF_MEMORY);
}
Error PoolAllocator::lock(ID p_mem) {
if (!needs_locking) {
return OK;
}
mt_lock();
Entry *e = get_entry(p_mem);
if (!e) {
mt_unlock();
ERR_PRINT("!e");
return ERR_INVALID_PARAMETER;
}
e->lock++;
mt_unlock();
return OK;
}
bool PoolAllocator::is_locked(ID p_mem) const {
if (!needs_locking) {
return false;
}
mt_lock();
const Entry *e = ((PoolAllocator *)(this))->get_entry(p_mem);
if (!e) {
mt_unlock();
ERR_PRINT("!e");
return false;
}
bool locked = e->lock;
mt_unlock();
return locked;
}
const void *PoolAllocator::get(ID p_mem) const {
if (!needs_locking) {
const Entry *e = get_entry(p_mem);
ERR_FAIL_COND_V(!e, nullptr);
return &pool[e->pos];
}
mt_lock();
const Entry *e = get_entry(p_mem);
if (!e) {
mt_unlock();
ERR_FAIL_COND_V(!e, nullptr);
}
if (e->lock == 0) {
mt_unlock();
ERR_PRINT("e->lock == 0");
return nullptr;
}
if ((int)e->pos >= pool_size) {
mt_unlock();
ERR_PRINT("e->pos<0 || e->pos>=pool_size");
return nullptr;
}
const void *ptr = &pool[e->pos];
mt_unlock();
return ptr;
}
void *PoolAllocator::get(ID p_mem) {
if (!needs_locking) {
Entry *e = get_entry(p_mem);
ERR_FAIL_COND_V(!e, nullptr);
return &pool[e->pos];
}
mt_lock();
Entry *e = get_entry(p_mem);
if (!e) {
mt_unlock();
ERR_FAIL_COND_V(!e, nullptr);
}
if (e->lock == 0) {
mt_unlock();
ERR_PRINT("e->lock == 0");
return nullptr;
}
if ((int)e->pos >= pool_size) {
mt_unlock();
ERR_PRINT("e->pos<0 || e->pos>=pool_size");
return nullptr;
}
void *ptr = &pool[e->pos];
mt_unlock();
return ptr;
}
void PoolAllocator::unlock(ID p_mem) {
if (!needs_locking) {
return;
}
mt_lock();
Entry *e = get_entry(p_mem);
if (!e) {
mt_unlock();
ERR_FAIL_COND(!e);
}
if (e->lock == 0) {
mt_unlock();
ERR_PRINT("e->lock == 0");
return;
}
e->lock--;
mt_unlock();
}
int PoolAllocator::get_used_mem() const {
return pool_size - free_mem;
}
int PoolAllocator::get_free_peak() {
return free_mem_peak;
}
int PoolAllocator::get_free_mem() {
return free_mem;
}
void PoolAllocator::create_pool(void *p_mem, int p_size, int p_max_entries) {
pool = (uint8_t *)p_mem;
pool_size = p_size;
entry_array = memnew_arr(Entry, p_max_entries);
entry_indices = memnew_arr(int, p_max_entries);
entry_max = p_max_entries;
entry_count = 0;
free_mem = p_size;
free_mem_peak = p_size;
check_count = 0;
}
PoolAllocator::PoolAllocator(int p_size, bool p_needs_locking, int p_max_entries) {
mem_ptr = memalloc(p_size);
ERR_FAIL_COND(!mem_ptr);
align = 1;
create_pool(mem_ptr, p_size, p_max_entries);
needs_locking = p_needs_locking;
}
PoolAllocator::PoolAllocator(void *p_mem, int p_size, int p_align, bool p_needs_locking, int p_max_entries) {
if (p_align > 1) {
uint8_t *mem8 = (uint8_t *)p_mem;
uint64_t ofs = (uint64_t)mem8;
if (ofs % p_align) {
int dif = p_align - (ofs % p_align);
mem8 += p_align - (ofs % p_align);
p_size -= dif;
p_mem = (void *)mem8;
};
};
create_pool(p_mem, p_size, p_max_entries);
needs_locking = p_needs_locking;
align = p_align;
mem_ptr = nullptr;
}
PoolAllocator::PoolAllocator(int p_align, int p_size, bool p_needs_locking, int p_max_entries) {
ERR_FAIL_COND(p_align < 1);
mem_ptr = Memory::alloc_static(p_size + p_align, true);
uint8_t *mem8 = (uint8_t *)mem_ptr;
uint64_t ofs = (uint64_t)mem8;
if (ofs % p_align) {
mem8 += p_align - (ofs % p_align);
}
create_pool(mem8, p_size, p_max_entries);
needs_locking = p_needs_locking;
align = p_align;
}
PoolAllocator::~PoolAllocator() {
if (mem_ptr) {
memfree(mem_ptr);
}
memdelete_arr(entry_array);
memdelete_arr(entry_indices);
}

151
sfw/pool_allocator.h Normal file
View File

@ -0,0 +1,151 @@
#ifndef POOL_ALLOCATOR_H
#define POOL_ALLOCATOR_H
/*************************************************************************/
/* pool_allocator.h */
/*************************************************************************/
/* This file is part of: */
/* PANDEMONIUM ENGINE */
/* https://github.com/Relintai/pandemonium_engine */
/*************************************************************************/
/* Copyright (c) 2022-present Péter Magyar. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* Copyright (c) 2007-2022 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. */
/*************************************************************************/
#include "typedefs.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
* Generic Pool Allocator.
* This is a generic memory pool allocator, with locking, compacting and alignment. (@TODO alignment)
* It used as a standard way to manage allocation in a specific region of memory, such as texture memory,
* audio sample memory, or just any kind of memory overall.
* (@TODO) abstraction should be greater, because in many platforms, you need to manage a nonreachable memory.
*/
enum {
POOL_ALLOCATOR_INVALID_ID = -1 ///< default invalid value. use INVALID_ID( id ) to test
};
class PoolAllocator {
public:
typedef int ID;
private:
enum {
CHECK_BITS = 8,
CHECK_LEN = (1 << CHECK_BITS),
CHECK_MASK = CHECK_LEN - 1
};
struct Entry {
unsigned int pos;
unsigned int len;
unsigned int lock;
unsigned int check;
inline void clear() {
pos = 0;
len = 0;
lock = 0;
check = 0;
}
Entry() { clear(); }
};
typedef int EntryArrayPos;
typedef int EntryIndicesPos;
Entry *entry_array;
int *entry_indices;
int entry_max;
int entry_count;
uint8_t *pool;
void *mem_ptr;
int pool_size;
int free_mem;
int free_mem_peak;
unsigned int check_count;
int align;
bool needs_locking;
inline int entry_end(const Entry &p_entry) const {
return p_entry.pos + aligned(p_entry.len);
}
inline int aligned(int p_size) const {
int rem = p_size % align;
if (rem) {
p_size += align - rem;
}
return p_size;
}
void compact(int p_up_to = -1);
void compact_up(int p_from = 0);
bool get_free_entry(EntryArrayPos *p_pos);
bool find_hole(EntryArrayPos *p_pos, int p_for_size);
bool find_entry_index(EntryIndicesPos *p_map_pos, Entry *p_entry);
Entry *get_entry(ID p_mem);
const Entry *get_entry(ID p_mem) const;
void create_pool(void *p_mem, int p_size, int p_max_entries);
protected:
virtual void mt_lock() const; ///< Reimplement for custom mt locking
virtual void mt_unlock() const; ///< Reimplement for custom mt locking
public:
enum {
DEFAULT_MAX_ALLOCS = 4096,
};
ID alloc(int p_size); ///< Alloc memory, get an ID on success, POOL_ALOCATOR_INVALID_ID on failure
void free(ID p_mem); ///< Free allocated memory
Error resize(ID p_mem, int p_new_size); ///< resize a memory chunk
int get_size(ID p_mem) const;
int get_free_mem(); ///< get free memory
int get_used_mem() const;
int get_free_peak(); ///< get free memory
Error lock(ID p_mem); //@todo move this out
void *get(ID p_mem);
const void *get(ID p_mem) const;
void unlock(ID p_mem);
bool is_locked(ID p_mem) const;
PoolAllocator(int p_size, bool p_needs_locking = false, int p_max_entries = DEFAULT_MAX_ALLOCS);
PoolAllocator(void *p_mem, int p_size, int p_align = 1, bool p_needs_locking = false, int p_max_entries = DEFAULT_MAX_ALLOCS);
PoolAllocator(int p_align, int p_size, bool p_needs_locking = false, int p_max_entries = DEFAULT_MAX_ALLOCS);
virtual ~PoolAllocator();
};
#endif

65
sfw/pool_vector.cpp Normal file
View File

@ -0,0 +1,65 @@
/*************************************************************************/
/* pool_vector.cpp */
/*************************************************************************/
/* This file is part of: */
/* PANDEMONIUM ENGINE */
/* https://github.com/Relintai/pandemonium_engine */
/*************************************************************************/
/* Copyright (c) 2022-present Péter Magyar. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* Copyright (c) 2007-2022 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. */
/*************************************************************************/
#include "pool_vector.h"
Mutex pool_vector_lock;
PoolAllocator *MemoryPool::memory_pool = nullptr;
uint8_t *MemoryPool::pool_memory = nullptr;
size_t *MemoryPool::pool_size = nullptr;
MemoryPool::Alloc *MemoryPool::allocs = nullptr;
MemoryPool::Alloc *MemoryPool::free_list = nullptr;
uint32_t MemoryPool::alloc_count = 0;
uint32_t MemoryPool::allocs_used = 0;
Mutex MemoryPool::alloc_mutex;
size_t MemoryPool::total_memory = 0;
size_t MemoryPool::max_memory = 0;
void MemoryPool::setup(uint32_t p_max_allocs) {
allocs = memnew_arr(Alloc, p_max_allocs);
alloc_count = p_max_allocs;
allocs_used = 0;
for (uint32_t i = 0; i < alloc_count - 1; i++) {
allocs[i].free_list = &allocs[i + 1];
}
free_list = &allocs[0];
}
void MemoryPool::cleanup() {
memdelete_arr(allocs);
ERR_FAIL_COND_MSG(allocs_used > 0, "There are still MemoryPool allocs in use at exit!");
}

736
sfw/pool_vector.h Normal file
View File

@ -0,0 +1,736 @@
#ifndef POOL_VECTOR_H
#define POOL_VECTOR_H
/*************************************************************************/
/* pool_vector.h */
/*************************************************************************/
/* This file is part of: */
/* PANDEMONIUM ENGINE */
/* https://github.com/Relintai/pandemonium_engine */
/*************************************************************************/
/* Copyright (c) 2022-present Péter Magyar. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* Copyright (c) 2007-2022 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. */
/*************************************************************************/
#include "memory.h"
#include "mutex.h"
#include "pool_allocator.h"
#include "rw_lock.h"
#include "safe_refcount.h"
#include "ustring.h"
struct MemoryPool {
//avoid accessing these directly, must be public for template access
static PoolAllocator *memory_pool;
static uint8_t *pool_memory;
static size_t *pool_size;
struct Alloc {
SafeRefCount refcount;
SafeNumeric<uint32_t> lock;
void *mem;
PoolAllocator::ID pool_id;
size_t size;
Alloc *free_list;
Alloc() :
lock(0),
mem(nullptr),
pool_id(POOL_ALLOCATOR_INVALID_ID),
size(0),
free_list(nullptr) {
}
};
static Alloc *allocs;
static Alloc *free_list;
static uint32_t alloc_count;
static uint32_t allocs_used;
static Mutex alloc_mutex;
static size_t total_memory;
static size_t max_memory;
static void setup(uint32_t p_max_allocs = (1 << 16));
static void cleanup();
};
template <class T>
class PoolVector {
MemoryPool::Alloc *alloc;
void _copy_on_write() {
if (!alloc) {
return;
}
// ERR_FAIL_COND(alloc->lock>0); should not be illegal to lock this for copy on write, as it's a copy on write after all
// Refcount should not be zero, otherwise it's a misuse of COW
if (alloc->refcount.get() == 1) {
return; //nothing to do
}
//must allocate something
MemoryPool::alloc_mutex.lock();
if (MemoryPool::allocs_used == MemoryPool::alloc_count) {
MemoryPool::alloc_mutex.unlock();
ERR_FAIL_MSG("All memory pool allocations are in use, can't COW.");
}
MemoryPool::Alloc *old_alloc = alloc;
//take one from the free list
alloc = MemoryPool::free_list;
MemoryPool::free_list = alloc->free_list;
//increment the used counter
MemoryPool::allocs_used++;
//copy the alloc data
alloc->size = old_alloc->size;
alloc->refcount.init();
alloc->pool_id = POOL_ALLOCATOR_INVALID_ID;
alloc->lock.set(0);
#ifdef DEBUG_ENABLED
MemoryPool::total_memory += alloc->size;
if (MemoryPool::total_memory > MemoryPool::max_memory) {
MemoryPool::max_memory = MemoryPool::total_memory;
}
#endif
MemoryPool::alloc_mutex.unlock();
if (MemoryPool::memory_pool) {
} else {
alloc->mem = memalloc(alloc->size);
}
{
Write w;
w._ref(alloc);
Read r;
r._ref(old_alloc);
int cur_elements = alloc->size / sizeof(T);
T *dst = (T *)w.ptr();
const T *src = (const T *)r.ptr();
for (int i = 0; i < cur_elements; i++) {
memnew_placement(&dst[i], T(src[i]));
}
}
if (old_alloc->refcount.unref()) {
//this should never happen but..
#ifdef DEBUG_ENABLED
MemoryPool::alloc_mutex.lock();
MemoryPool::total_memory -= old_alloc->size;
MemoryPool::alloc_mutex.unlock();
#endif
{
Write w;
w._ref(old_alloc);
int cur_elements = old_alloc->size / sizeof(T);
T *elems = (T *)w.ptr();
for (int i = 0; i < cur_elements; i++) {
elems[i].~T();
}
}
if (MemoryPool::memory_pool) {
//resize memory pool
//if none, create
//if some resize
} else {
memfree(old_alloc->mem);
old_alloc->mem = nullptr;
old_alloc->size = 0;
MemoryPool::alloc_mutex.lock();
old_alloc->free_list = MemoryPool::free_list;
MemoryPool::free_list = old_alloc;
MemoryPool::allocs_used--;
MemoryPool::alloc_mutex.unlock();
}
}
}
void _reference(const PoolVector &p_pool_vector) {
if (alloc == p_pool_vector.alloc) {
return;
}
_unreference();
if (!p_pool_vector.alloc) {
return;
}
if (p_pool_vector.alloc->refcount.ref()) {
alloc = p_pool_vector.alloc;
}
}
void _unreference() {
if (!alloc) {
return;
}
if (!alloc->refcount.unref()) {
alloc = nullptr;
return;
}
//must be disposed!
{
int cur_elements = alloc->size / sizeof(T);
// Don't use write() here because it could otherwise provoke COW,
// which is not desirable here because we are destroying the last reference anyways
Write w;
// Reference to still prevent other threads from touching the alloc
w._ref(alloc);
for (int i = 0; i < cur_elements; i++) {
w[i].~T();
}
}
#ifdef DEBUG_ENABLED
MemoryPool::alloc_mutex.lock();
MemoryPool::total_memory -= alloc->size;
MemoryPool::alloc_mutex.unlock();
#endif
if (MemoryPool::memory_pool) {
//resize memory pool
//if none, create
//if some resize
} else {
memfree(alloc->mem);
alloc->mem = nullptr;
alloc->size = 0;
MemoryPool::alloc_mutex.lock();
alloc->free_list = MemoryPool::free_list;
MemoryPool::free_list = alloc;
MemoryPool::allocs_used--;
MemoryPool::alloc_mutex.unlock();
}
alloc = nullptr;
}
public:
class Access {
friend class PoolVector;
protected:
MemoryPool::Alloc *alloc;
T *mem;
_FORCE_INLINE_ void _ref(MemoryPool::Alloc *p_alloc) {
alloc = p_alloc;
if (alloc) {
if (alloc->lock.increment() == 1) {
if (MemoryPool::memory_pool) {
//lock it and get mem
}
}
mem = (T *)alloc->mem;
}
}
_FORCE_INLINE_ void _unref() {
if (alloc) {
if (alloc->lock.decrement() == 0) {
if (MemoryPool::memory_pool) {
//put mem back
}
}
mem = nullptr;
alloc = nullptr;
}
}
Access() {
alloc = nullptr;
mem = nullptr;
}
public:
virtual ~Access() {
_unref();
}
void release() {
_unref();
}
};
class Read : public Access {
public:
_FORCE_INLINE_ const T &operator[](int p_index) const { return this->mem[p_index]; }
_FORCE_INLINE_ const T *ptr() const { return this->mem; }
void operator=(const Read &p_read) {
if (this->alloc == p_read.alloc) {
return;
}
this->_unref();
this->_ref(p_read.alloc);
}
Read(const Read &p_read) {
this->_ref(p_read.alloc);
}
Read() {}
};
class Write : public Access {
public:
_FORCE_INLINE_ T &operator[](int p_index) const { return this->mem[p_index]; }
_FORCE_INLINE_ T *ptr() const { return this->mem; }
void operator=(const Write &p_read) {
if (this->alloc == p_read.alloc) {
return;
}
this->_unref();
this->_ref(p_read.alloc);
}
Write(const Write &p_read) {
this->_ref(p_read.alloc);
}
Write() {}
};
Read read() const {
Read r;
if (alloc) {
r._ref(alloc);
}
return r;
}
Write write() {
Write w;
if (alloc) {
_copy_on_write(); //make sure there is only one being accessed
w._ref(alloc);
}
return w;
}
template <class MC>
void fill_with(const MC &p_mc) {
int c = p_mc.size();
resize(c);
Write w = write();
int idx = 0;
for (const typename MC::Element *E = p_mc.front(); E; E = E->next()) {
w[idx++] = E->get();
}
}
void remove(int p_index) {
int s = size();
ERR_FAIL_INDEX(p_index, s);
Write w = write();
for (int i = p_index; i < s - 1; i++) {
w[i] = w[i + 1];
};
w = Write();
resize(s - 1);
}
inline int size() const;
inline bool empty() const;
T get(int p_index) const;
void set(int p_index, const T &p_val);
void fill(const T &p_val);
void push_back(const T &p_val);
void append(const T &p_val) {
push_back(p_val);
}
void append_array(const PoolVector<T> &p_arr) {
int ds = p_arr.size();
if (ds == 0) {
return;
}
int bs = size();
resize(bs + ds);
Write w = write();
Read r = p_arr.read();
for (int i = 0; i < ds; i++) {
w[bs + i] = r[i];
}
}
PoolVector<T> subarray(int p_from, int p_to) const {
if (p_from < 0) {
p_from = size() + p_from;
}
if (p_to < 0) {
p_to = size() + p_to;
}
ERR_FAIL_INDEX_V(p_from, size(), PoolVector<T>());
ERR_FAIL_INDEX_V(p_to, size(), PoolVector<T>());
PoolVector<T> slice;
int span = 1 + p_to - p_from;
slice.resize(span);
Read r = read();
Write w = slice.write();
for (int i = 0; i < span; ++i) {
w[i] = r[p_from + i];
}
return slice;
}
Error insert(int p_pos, const T &p_val) {
int s = size();
ERR_FAIL_INDEX_V(p_pos, s + 1, ERR_INVALID_PARAMETER);
resize(s + 1);
{
Write w = write();
for (int i = s; i > p_pos; i--) {
w[i] = w[i - 1];
}
w[p_pos] = p_val;
}
return OK;
}
String join(const String &delimiter) const {
String rs = "";
int s = size();
Read r = read();
for (int i = 0; i < s; i++) {
rs += r[i] + delimiter;
}
rs.erase(rs.length() - delimiter.length(), delimiter.length());
return rs;
}
bool contains(const T &p_val) const;
int find(const T &p_val, int p_from = 0) const;
int rfind(const T &p_val, int p_from = -1) const;
int count(const T &p_val) const;
bool has(const T &p_val) const;
bool is_locked() const {
return alloc && alloc->lock.get() > 0;
}
inline T operator[](int p_index) const;
Error resize(int p_size);
Error clear() {
return resize(0);
}
void invert();
void sort();
void operator=(const PoolVector &p_pool_vector) {
_reference(p_pool_vector);
}
PoolVector() {
alloc = nullptr;
}
PoolVector(const PoolVector &p_pool_vector) {
alloc = nullptr;
_reference(p_pool_vector);
}
~PoolVector() {
_unreference();
}
};
template <class T>
int PoolVector<T>::size() const {
return alloc ? alloc->size / sizeof(T) : 0;
}
template <class T>
bool PoolVector<T>::empty() const {
return alloc ? alloc->size == 0 : true;
}
template <class T>
T PoolVector<T>::get(int p_index) const {
return operator[](p_index);
}
template <class T>
void PoolVector<T>::set(int p_index, const T &p_val) {
ERR_FAIL_INDEX(p_index, size());
Write w = write();
w[p_index] = p_val;
}
template <class T>
void PoolVector<T>::fill(const T &p_val) {
Write w = write();
for (int i = 0; i < size(); i++) {
w[i] = p_val;
}
}
template <class T>
void PoolVector<T>::push_back(const T &p_val) {
resize(size() + 1);
set(size() - 1, p_val);
}
template <class T>
bool PoolVector<T>::contains(const T &p_val) const {
Read r = read();
int s = size();
for (int i = 0; i < s; ++i) {
if (r[i] == p_val) {
return true;
}
}
return false;
}
template <class T>
int PoolVector<T>::find(const T &p_val, int p_from) const {
if (p_from < 0) {
return -1;
}
const int s = size();
const Read r = read();
for (int i = p_from; i < s; i++) {
if (r[i] == p_val) {
return i;
}
}
return -1;
}
template <class T>
int PoolVector<T>::rfind(const T &p_val, int p_from) const {
const int s = size();
const Read r = read();
if (p_from < 0) {
p_from = s + p_from;
}
if (p_from < 0 || p_from >= s) {
p_from = s - 1;
}
for (int i = p_from; i >= 0; i--) {
if (r[i] == p_val) {
return i;
}
}
return -1;
}
template <class T>
int PoolVector<T>::count(const T &p_val) const {
const int s = size();
const Read r = read();
int amount = 0;
for (int i = 0; i < s; i++) {
if (r[i] == p_val) {
amount++;
}
}
return amount;
}
template <class T>
bool PoolVector<T>::has(const T &p_val) const {
return find(p_val) != -1;
}
template <class T>
T PoolVector<T>::operator[](int p_index) const {
CRASH_BAD_INDEX(p_index, size());
Read r = read();
return r[p_index];
}
template <class T>
Error PoolVector<T>::resize(int p_size) {
ERR_FAIL_COND_V_MSG(p_size < 0, ERR_INVALID_PARAMETER, "Size of PoolVector cannot be negative.");
if (alloc == nullptr) {
if (p_size == 0) {
return OK; //nothing to do here
}
//must allocate something
MemoryPool::alloc_mutex.lock();
if (MemoryPool::allocs_used == MemoryPool::alloc_count) {
MemoryPool::alloc_mutex.unlock();
ERR_FAIL_V_MSG(ERR_OUT_OF_MEMORY, "All memory pool allocations are in use.");
}
//take one from the free list
alloc = MemoryPool::free_list;
MemoryPool::free_list = alloc->free_list;
//increment the used counter
MemoryPool::allocs_used++;
//cleanup the alloc
alloc->size = 0;
alloc->refcount.init();
alloc->pool_id = POOL_ALLOCATOR_INVALID_ID;
MemoryPool::alloc_mutex.unlock();
} else {
ERR_FAIL_COND_V_MSG(alloc->lock.get() > 0, ERR_LOCKED, "Can't resize PoolVector if locked."); //can't resize if locked!
}
size_t new_size = sizeof(T) * p_size;
if (alloc->size == new_size) {
return OK; //nothing to do
}
if (p_size == 0) {
_unreference();
return OK;
}
_copy_on_write(); // make it unique
#ifdef DEBUG_ENABLED
MemoryPool::alloc_mutex.lock();
MemoryPool::total_memory -= alloc->size;
MemoryPool::total_memory += new_size;
if (MemoryPool::total_memory > MemoryPool::max_memory) {
MemoryPool::max_memory = MemoryPool::total_memory;
}
MemoryPool::alloc_mutex.unlock();
#endif
int cur_elements = alloc->size / sizeof(T);
if (p_size > cur_elements) {
if (MemoryPool::memory_pool) {
//resize memory pool
//if none, create
//if some resize
} else {
if (alloc->size == 0) {
alloc->mem = memalloc(new_size);
} else {
alloc->mem = memrealloc(alloc->mem, new_size);
}
}
alloc->size = new_size;
Write w = write();
for (int i = cur_elements; i < p_size; i++) {
memnew_placement(&w[i], T);
}
} else {
{
Write w = write();
for (int i = p_size; i < cur_elements; i++) {
w[i].~T();
}
}
if (MemoryPool::memory_pool) {
//resize memory pool
//if none, create
//if some resize
} else {
if (new_size == 0) {
memfree(alloc->mem);
alloc->mem = nullptr;
alloc->size = 0;
MemoryPool::alloc_mutex.lock();
alloc->free_list = MemoryPool::free_list;
MemoryPool::free_list = alloc;
MemoryPool::allocs_used--;
MemoryPool::alloc_mutex.unlock();
} else {
alloc->mem = memrealloc(alloc->mem, new_size);
alloc->size = new_size;
}
}
}
return OK;
}
template <class T>
void PoolVector<T>::invert() {
T temp;
Write w = write();
int s = size();
int half_s = s / 2;
for (int i = 0; i < half_s; i++) {
temp = w[i];
w[i] = w[s - i - 1];
w[s - i - 1] = temp;
}
}
template <class T>
void PoolVector<T>::sort() {
int len = size();
if (len == 0) {
return;
}
Write w = write();
SortArray<T> sorter;
sorter.sort(w.ptr(), len);
}
#endif // POOL_VECTOR_H

View File

@ -36,9 +36,6 @@
#include "plane.h"
#include "rect2.h"
#include "transform.h"
#include "string/print_string.h"
#include "variant/array.h"
#include "variant/variant.h"
float Projection::determinant() const {
return matrix[0][3] * matrix[1][2] * matrix[2][1] * matrix[3][0] - matrix[0][2] * matrix[1][3] * matrix[2][1] * matrix[3][0] -
@ -565,88 +562,6 @@ Vector<Plane> Projection::get_projection_planes(const Transform &p_transform) co
return planes;
}
Array Projection::get_projection_planes_array(const Transform &p_transform) const {
/** Fast Plane Extraction from combined modelview/projection matrices.
* References:
* https://web.archive.org/web/20011221205252/https://www.markmorley.com/opengl/frustumculling.html
* https://web.archive.org/web/20061020020112/https://www2.ravensoft.com/users/ggribb/plane%20extraction.pdf
*/
Array planes;
const real_t *matrix = (const real_t *)this->matrix;
Plane new_plane;
///////--- Near Plane ---///////
new_plane = Plane(matrix[3] + matrix[2],
matrix[7] + matrix[6],
matrix[11] + matrix[10],
matrix[15] + matrix[14]);
new_plane.normal = -new_plane.normal;
new_plane.normalize();
planes.push_back(p_transform.xform(new_plane));
///////--- Far Plane ---///////
new_plane = Plane(matrix[3] - matrix[2],
matrix[7] - matrix[6],
matrix[11] - matrix[10],
matrix[15] - matrix[14]);
new_plane.normal = -new_plane.normal;
new_plane.normalize();
planes.push_back(p_transform.xform(new_plane));
///////--- Left Plane ---///////
new_plane = Plane(matrix[3] + matrix[0],
matrix[7] + matrix[4],
matrix[11] + matrix[8],
matrix[15] + matrix[12]);
new_plane.normal = -new_plane.normal;
new_plane.normalize();
planes.push_back(p_transform.xform(new_plane));
///////--- Top Plane ---///////
new_plane = Plane(matrix[3] - matrix[1],
matrix[7] - matrix[5],
matrix[11] - matrix[9],
matrix[15] - matrix[13]);
new_plane.normal = -new_plane.normal;
new_plane.normalize();
planes.push_back(p_transform.xform(new_plane));
///////--- Right Plane ---///////
new_plane = Plane(matrix[3] - matrix[0],
matrix[7] - matrix[4],
matrix[11] - matrix[8],
matrix[15] - matrix[12]);
new_plane.normal = -new_plane.normal;
new_plane.normalize();
planes.push_back(p_transform.xform(new_plane));
///////--- Bottom Plane ---///////
new_plane = Plane(matrix[3] + matrix[1],
matrix[7] + matrix[5],
matrix[11] + matrix[9],
matrix[15] + matrix[13]);
new_plane.normal = -new_plane.normal;
new_plane.normalize();
planes.push_back(p_transform.xform(new_plane));
return planes;
}
Projection Projection::inverse() const {
Projection cm = *this;
cm.invert();

View File

@ -37,7 +37,6 @@
#include "vector3.h"
#include "vector4.h"
class Array;
struct AABB;
struct Plane;
struct Rect2;
@ -113,7 +112,6 @@ struct _NO_DISCARD_CLASS_ Projection {
bool is_orthogonal() const;
Vector<Plane> get_projection_planes(const Transform &p_transform) const;
Array get_projection_planes_array(const Transform &p_transform) const;
bool get_endpoints(const Transform &p_transform, Vector3 *p_8points) const;
Vector2 get_viewport_half_extents() const;

View File

@ -32,7 +32,6 @@
#include "quaternion.h"
#include "basis.h"
#include "string/print_string.h"
real_t Quaternion::angle_to(const Quaternion &p_to) const {
real_t d = dot(p_to);

View File

@ -31,7 +31,8 @@
#include "random_pcg.h"
#include "os/os.h"
//#include "os/os.h"
#include "error_macros.h"
RandomPCG::RandomPCG(uint64_t p_seed, uint64_t p_inc) :
pcg(),
@ -40,7 +41,8 @@ RandomPCG::RandomPCG(uint64_t p_seed, uint64_t p_inc) :
}
void RandomPCG::randomize() {
seed((OS::get_singleton()->get_unix_time() + OS::get_singleton()->get_ticks_usec()) * pcg.state + PCG_DEFAULT_INC_64);
//seed((OS::get_singleton()->get_unix_time() + OS::get_singleton()->get_ticks_usec()) * pcg.state + PCG_DEFAULT_INC_64);
ERR_PRINT("RandomPCG::randomize() fix!");
}
double RandomPCG::random(double p_from, double p_to) {

117
sfw/rw_lock.h Normal file
View File

@ -0,0 +1,117 @@
#ifndef RWLOCK_H
#define RWLOCK_H
/*************************************************************************/
/* rw_lock.h */
/*************************************************************************/
/* This file is part of: */
/* PANDEMONIUM ENGINE */
/* https://github.com/Relintai/pandemonium_engine */
/*************************************************************************/
/* Copyright (c) 2022-present Péter Magyar. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* Copyright (c) 2007-2022 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. */
/*************************************************************************/
#include "error_list.h"
#if !defined(NO_THREADS)
#include <shared_mutex>
class RWLock {
mutable std::shared_timed_mutex mutex;
public:
// Lock the rwlock, block if locked by someone else
void read_lock() const {
mutex.lock_shared();
}
// Unlock the rwlock, let other threads continue
void read_unlock() const {
mutex.unlock_shared();
}
// Attempt to lock the rwlock, OK on success, ERR_BUSY means it can't lock.
Error read_try_lock() const {
return mutex.try_lock_shared() ? OK : ERR_BUSY;
}
// Lock the rwlock, block if locked by someone else
void write_lock() {
mutex.lock();
}
// Unlock the rwlock, let other thwrites continue
void write_unlock() {
mutex.unlock();
}
// Attempt to lock the rwlock, OK on success, ERR_BUSY means it can't lock.
Error write_try_lock() {
return mutex.try_lock() ? OK : ERR_BUSY;
}
};
#else
class RWLock {
public:
void read_lock() const {}
void read_unlock() const {}
Error read_try_lock() const { return OK; }
void write_lock() {}
void write_unlock() {}
Error write_try_lock() { return OK; }
};
#endif
class RWLockRead {
const RWLock &lock;
public:
RWLockRead(const RWLock &p_lock) :
lock(p_lock) {
lock.read_lock();
}
~RWLockRead() {
lock.read_unlock();
}
};
class RWLockWrite {
RWLock &lock;
public:
RWLockWrite(RWLock &p_lock) :
lock(p_lock) {
lock.write_lock();
}
~RWLockWrite() {
lock.write_unlock();
}
};
#endif // RWLOCK_H

View File

@ -32,7 +32,6 @@
#include "transform.h"
#include "math_funcs.h"
#include "string/print_string.h"
void Transform::invert() {
basis.transpose();

View File

@ -36,6 +36,7 @@
#include "basis.h"
#include "plane.h"
#include "vector3i.h"
#include "pool_vector.h"
struct _NO_DISCARD_CLASS_ Transform {
Basis basis;

View File

@ -35,15 +35,10 @@
#include "ustring.h"
#include "crypto/crypto_core.h"
#include "color.h"
#include "math_funcs.h"
#include "os/memory.h"
#include "string/print_string.h"
#include "string/translation.h"
#include "string/ucaps.h"
#include "variant/variant.h"
#include "version_generated.gen.h"
#include "memory.h"
#include "ucaps.h"
#include <wchar.h>
#include <cstdint>
@ -330,12 +325,14 @@ void String::copy_from(const CharType &p_char) {
print_unicode_error("NUL character", true);
return;
}
/*
if ((p_char & 0xfffff800) == 0xd800) {
print_unicode_error(vformat("Unpaired surrogate (%x)", (uint32_t)p_char));
}
if (p_char > 0x10ffff) {
print_unicode_error(vformat("Invalid unicode codepoint (%x)", (uint32_t)p_char));
}
*/
resize(2);
@ -399,12 +396,14 @@ void String::copy_from_unchecked(const CharType *p_char, const int p_length) {
dst[i] = 0x20;
continue;
}
/*
if ((p_char[i] & 0xfffff800) == 0xd800) {
print_unicode_error(vformat("Unpaired surrogate (%x)", (uint32_t)p_char[i]));
}
if (p_char[i] > 0x10ffff) {
print_unicode_error(vformat("Invalid unicode codepoint (%x)", (uint32_t)p_char[i]));
}
*/
dst[i] = p_char[i];
}
}
@ -477,12 +476,14 @@ String &String::operator+=(CharType p_char) {
print_unicode_error("NUL character", true);
return *this;
}
/*
if ((p_char & 0xfffff800) == 0xd800) {
print_unicode_error(vformat("Unpaired surrogate (%x)", (uint32_t)p_char));
}
if (p_char > 0x10ffff) {
print_unicode_error(vformat("Invalid unicode codepoint (%x)", (uint32_t)p_char));
}
*/
const int lhs_len = length();
set_length(lhs_len + 1);
@ -868,11 +869,13 @@ bool String::is_valid_string() const {
}
void String::print_unicode_error(const String &p_message, bool p_critical) const {
/*
if (p_critical) {
print_error(vformat("Unicode parsing error, some characters were replaced with spaces: %s", p_message));
} else {
print_error(vformat("Unicode parsing error: %s", p_message));
}
*/
}
/* complex helpers */
@ -2496,18 +2499,6 @@ String String::camelcase_to_underscore(bool lowercase) const {
return lowercase ? new_string.to_lower() : new_string;
}
String String::get_with_code_lines() const {
const Vector<String> lines = split("\n");
String ret;
for (int i = 0; i < lines.size(); i++) {
if (i > 0) {
ret += "\n";
}
ret += vformat("%4d | %s", i + 1, lines[i]);
}
return ret;
}
int String::get_slice_count(String p_splitter) const {
if (empty()) {
return 0;
@ -3120,7 +3111,7 @@ CharString String::ascii(bool p_allow_extended) const {
if ((c <= 0x7f) || (c <= 0xff && p_allow_extended)) {
cs[i] = c;
} else {
print_unicode_error(vformat("Invalid unicode codepoint (%x), cannot represent as ASCII/Latin-1", (uint32_t)c));
//print_unicode_error(vformat("Invalid unicode codepoint (%x), cannot represent as ASCII/Latin-1", (uint32_t)c));
cs[i] = 0x20;
}
}
@ -3187,23 +3178,23 @@ Error String::parse_utf8(const char *p_utf8, int p_len, bool p_skip_cr) {
skip = 5;
} else {
skip = 0;
print_unicode_error(vformat("Invalid UTF-8 leading byte (%x)", c), true);
//print_unicode_error(vformat("Invalid UTF-8 leading byte (%x)", c), true);
decode_failed = true;
}
c_start = c;
if (skip == 1 && (c & 0x1e) == 0) {
print_unicode_error(vformat("Overlong encoding (%x ...)", c));
//print_unicode_error(vformat("Overlong encoding (%x ...)", c));
decode_error = true;
}
str_size++;
} else {
if ((c_start == 0xe0 && skip == 2 && c < 0xa0) || (c_start == 0xf0 && skip == 3 && c < 0x90) || (c_start == 0xf8 && skip == 4 && c < 0x88) || (c_start == 0xfc && skip == 5 && c < 0x84)) {
print_unicode_error(vformat("Overlong encoding (%x %x ...)", c_start, c));
//print_unicode_error(vformat("Overlong encoding (%x %x ...)", c_start, c));
decode_error = true;
}
if (c < 0x80 || c > 0xbf) {
print_unicode_error(vformat("Invalid UTF-8 continuation byte (%x ... %x ...)", c_start, c), true);
//print_unicode_error(vformat("Invalid UTF-8 continuation byte (%x ... %x ...)", c_start, c), true);
decode_failed = true;
skip = 0;
} else {
@ -3216,7 +3207,7 @@ Error String::parse_utf8(const char *p_utf8, int p_len, bool p_skip_cr) {
}
if (skip) {
print_unicode_error(vformat("Missing %d UTF-8 continuation byte(s)", skip), true);
//rrprint_unicode_error(vformat("Missing %d UTF-8 continuation byte(s)", skip), true);
decode_failed = true;
}
}
@ -3274,16 +3265,16 @@ Error String::parse_utf8(const char *p_utf8, int p_len, bool p_skip_cr) {
--skip;
if (skip == 0) {
if (unichar == 0) {
print_unicode_error("NUL character", true);
//print_unicode_error("NUL character", true);
decode_failed = true;
unichar = 0x20;
}
if ((unichar & 0xfffff800) == 0xd800) {
print_unicode_error(vformat("Unpaired surrogate (%x)", unichar));
//print_unicode_error(vformat("Unpaired surrogate (%x)", unichar));
decode_error = true;
}
if (unichar > 0x10ffff) {
print_unicode_error(vformat("Invalid unicode codepoint (%x)", unichar));
//print_unicode_error(vformat("Invalid unicode codepoint (%x)", unichar));
decode_error = true;
}
*(dst++) = unichar;
@ -3327,13 +3318,13 @@ CharString String::utf8() const {
fl += 4;
} else if (c <= 0x03ffffff) { // 26 bits
fl += 5;
print_unicode_error(vformat("Invalid unicode codepoint (%x)", c));
//print_unicode_error(vformat("Invalid unicode codepoint (%x)", c));
} else if (c <= 0x7fffffff) { // 31 bits
fl += 6;
print_unicode_error(vformat("Invalid unicode codepoint (%x)", c));
//print_unicode_error(vformat("Invalid unicode codepoint (%x)", c));
} else {
fl += 1;
print_unicode_error(vformat("Invalid unicode codepoint (%x), cannot represent as UTF-8", c), true);
//print_unicode_error(vformat("Invalid unicode codepoint (%x), cannot represent as UTF-8", c), true);
}
}
@ -3407,13 +3398,13 @@ int String::utf8_byte_length() const {
fl += 4;
} else if (c <= 0x03ffffff) { // 26 bits
fl += 5;
print_unicode_error(vformat("Invalid unicode codepoint (%x)", c));
//print_unicode_error(vformat("Invalid unicode codepoint (%x)", c));
} else if (c <= 0x7fffffff) { // 31 bits
fl += 6;
print_unicode_error(vformat("Invalid unicode codepoint (%x)", c));
//print_unicode_error(vformat("Invalid unicode codepoint (%x)", c));
} else {
fl += 1;
print_unicode_error(vformat("Invalid unicode codepoint (%x), cannot represent as UTF-8", c), true);
//print_unicode_error(vformat("Invalid unicode codepoint (%x), cannot represent as UTF-8", c), true);
}
}
@ -3460,14 +3451,14 @@ Error String::parse_utf16(const char16_t *p_utf16, int p_len) {
{
const char16_t *ptrtmp = p_utf16;
const char16_t *ptrtmp_limit = &p_utf16[p_len];
uint32_t c_prev = 0;
//uint32_t c_prev = 0;
bool skip = false;
while (ptrtmp != ptrtmp_limit && *ptrtmp) {
uint32_t c = (byteswap) ? BSWAP16(*ptrtmp) : *ptrtmp;
if ((c & 0xfffffc00) == 0xd800) { // lead surrogate
if (skip) {
print_unicode_error(vformat("Unpaired lead surrogate (%x [trail?] %x)", c_prev, c));
//print_unicode_error(vformat("Unpaired lead surrogate (%x [trail?] %x)", c_prev, c));
decode_error = true;
}
skip = true;
@ -3475,7 +3466,7 @@ Error String::parse_utf16(const char16_t *p_utf16, int p_len) {
if (skip) {
str_size--;
} else {
print_unicode_error(vformat("Unpaired trail surrogate (%x [lead?] %x)", c_prev, c));
//print_unicode_error(vformat("Unpaired trail surrogate (%x [lead?] %x)", c_prev, c));
decode_error = true;
}
skip = false;
@ -3483,14 +3474,14 @@ Error String::parse_utf16(const char16_t *p_utf16, int p_len) {
skip = false;
}
c_prev = c;
//c_prev = c;
str_size++;
cstr_size++;
ptrtmp++;
}
if (skip) {
print_unicode_error(vformat("Unpaired lead surrogate (%x [eol])", c_prev));
//print_unicode_error(vformat("Unpaired lead surrogate (%x [eol])", c_prev));
decode_error = true;
}
}
@ -3555,12 +3546,12 @@ Char16String String::utf16() const {
if (c <= 0xffff) { // 16 bits.
fl += 1;
if ((c & 0xfffff800) == 0xd800) {
print_unicode_error(vformat("Unpaired surrogate (%x)", c));
//print_unicode_error(vformat("Unpaired surrogate (%x)", c));
}
} else if (c <= 0x10ffff) { // 32 bits.
fl += 2;
} else {
print_unicode_error(vformat("Invalid unicode codepoint (%x), cannot represent as UTF-16", c), true);
//print_unicode_error(vformat("Invalid unicode codepoint (%x), cannot represent as UTF-16", c), true);
fl += 1;
}
}
@ -3606,12 +3597,12 @@ int String::utf16_byte_length() const {
if (c <= 0xffff) { // 16 bits.
fl += 1;
if ((c & 0xfffff800) == 0xd800) {
print_unicode_error(vformat("Unpaired surrogate (%x)", c));
//print_unicode_error(vformat("Unpaired surrogate (%x)", c));
}
} else if (c <= 0x10ffff) { // 32 bits.
fl += 2;
} else {
print_unicode_error(vformat("Invalid unicode codepoint (%x), cannot represent as UTF-16", c), true);
//print_unicode_error(vformat("Invalid unicode codepoint (%x), cannot represent as UTF-16", c), true);
fl += 1;
}
}
@ -3707,67 +3698,6 @@ uint64_t String::hash64() const {
return hashv;
}
String String::md5_text() const {
CharString cs = utf8();
unsigned char hash[16];
CryptoCore::md5((unsigned char *)cs.ptr(), cs.length(), hash);
return String::hex_encode_buffer(hash, 16);
}
String String::sha1_text() const {
CharString cs = utf8();
unsigned char hash[20];
CryptoCore::sha1((unsigned char *)cs.ptr(), cs.length(), hash);
return String::hex_encode_buffer(hash, 20);
}
String String::sha256_text() const {
CharString cs = utf8();
unsigned char hash[32];
CryptoCore::sha256((unsigned char *)cs.ptr(), cs.length(), hash);
return String::hex_encode_buffer(hash, 32);
}
Vector<uint8_t> String::md5_buffer() const {
CharString cs = utf8();
unsigned char hash[16];
CryptoCore::md5((unsigned char *)cs.ptr(), cs.length(), hash);
Vector<uint8_t> ret;
ret.resize(16);
for (int i = 0; i < 16; i++) {
ret.write[i] = hash[i];
}
return ret;
};
Vector<uint8_t> String::sha1_buffer() const {
CharString cs = utf8();
unsigned char hash[20];
CryptoCore::sha1((unsigned char *)cs.ptr(), cs.length(), hash);
Vector<uint8_t> ret;
ret.resize(20);
for (int i = 0; i < 20; i++) {
ret.write[i] = hash[i];
}
return ret;
}
Vector<uint8_t> String::sha256_buffer() const {
CharString cs = utf8();
unsigned char hash[32];
CryptoCore::sha256((unsigned char *)cs.ptr(), cs.length(), hash);
Vector<uint8_t> ret;
ret.resize(32);
for (int i = 0; i < 32; i++) {
ret.write[i] = hash[i];
}
return ret;
}
bool String::is_abs_path() const {
if (length() > 1) {
return (operator[](0) == '/' || operator[](0) == '\\' || find(":/") != -1 || find(":\\") != -1);
@ -5400,7 +5330,7 @@ static double built_in_strtod(
if (exp > maxExponent) {
exp = maxExponent;
WARN_PRINT("Exponent too high");
//WARN_PRINT("Exponent too high");
}
dblExp = 1.0;
for (d = powersOf10; exp != 0; exp >>= 1, ++d) {
@ -5780,10 +5710,6 @@ String rtoss(double p_val) {
#ifdef TOOLS_ENABLED
String TTR(const String &p_text, const String &p_context) {
if (TranslationServer::get_singleton()) {
return TranslationServer::get_singleton()->tool_translate(p_text, p_context);
}
return p_text;
}
@ -5795,23 +5721,10 @@ String DTR(const String &p_text) {
// Comes straight from the XML, so remove indentation and any trailing whitespace.
const String text = p_text.dedent().strip_edges();
if (TranslationServer::get_singleton()) {
return String(TranslationServer::get_singleton()->doc_translate(text)).replace("$DOCS_URL", VERSION_DOCS_URL);
}
return text.replace("$DOCS_URL", VERSION_DOCS_URL);
}
#endif
String RTR(const String &p_text) {
if (TranslationServer::get_singleton()) {
String rtr = TranslationServer::get_singleton()->tool_translate(p_text, StringName());
if (rtr == String() || rtr == p_text) {
return TranslationServer::get_singleton()->translate(p_text);
} else {
return rtr;
}
}
return p_text;
}

View File

@ -393,7 +393,6 @@ public:
String capitalize() const;
String camelcase_to_underscore(bool lowercase = true) const;
String get_with_code_lines() const;
int get_slice_count(String p_splitter) const;
String get_slice(String p_splitter, int p_slice) const;
String get_slicec(CharType p_splitter, int p_slice) const;
@ -456,13 +455,6 @@ public:
uint32_t hash() const; /* hash the string */
uint64_t hash64() const; /* hash the string */
String md5_text() const;
String sha1_text() const;
String sha256_text() const;
Vector<uint8_t> md5_buffer() const;
Vector<uint8_t> sha1_buffer() const;
Vector<uint8_t> sha256_buffer() const;
_FORCE_INLINE_ bool empty() const { return length() == 0; }
_FORCE_INLINE_ bool contains(const char *p_str) const { return find(p_str) != -1; }
_FORCE_INLINE_ bool contains(const String &p_str) const { return find(p_str) != -1; }

View File

@ -31,7 +31,7 @@
#include "vector2.h"
#include "string/ustring.h"
#include "ustring.h"
real_t Vector2::angle() const {
return Math::atan2(y, x);

View File

@ -34,7 +34,7 @@
#include "math_funcs.h"
#include "error/error_macros.h"
#include "error_macros.h"
class String;

View File

@ -31,7 +31,7 @@
#include "vector2i.h"
#include "string/ustring.h"
#include "ustring.h"
Vector2i Vector2i::clamp(const Vector2i &p_min, const Vector2i &p_max) const {
return Vector2i(

View File

@ -32,7 +32,7 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "error/error_macros.h"
#include "error_macros.h"
#include "math_funcs.h"
#include "vector2.h"

View File

@ -32,7 +32,7 @@
#include "vector3i.h"
#include "vector3.h"
#include "string/ustring.h"
#include "ustring.h"
void Vector3i::set_axis(const int p_axis, const int32_t p_value) {
ERR_FAIL_INDEX(p_axis, 3);

View File

@ -32,7 +32,6 @@
#include "vector4.h"
#include "basis.h"
#include "string/print_string.h"
void Vector4::set_axis(const int p_axis, const real_t p_value) {
ERR_FAIL_INDEX(p_axis, 4);

View File

@ -34,7 +34,7 @@
#include "math_defs.h"
#include "math_funcs.h"
#include "string/ustring.h"
#include "ustring.h"
struct _NO_DISCARD_CLASS_ Vector4 {
enum Axis {

View File

@ -32,7 +32,7 @@
#include "vector4i.h"
#include "vector4.h"
#include "string/ustring.h"
#include "ustring.h"
void Vector4i::set_axis(const int p_axis, const int32_t p_value) {
ERR_FAIL_INDEX(p_axis, 4);

View File

@ -32,7 +32,7 @@
#ifndef VECTOR4I_H
#define VECTOR4I_H
#include "error/error_macros.h"
#include "error_macros.h"
#include "math_funcs.h"
class String;