diff options
Diffstat (limited to 'modules')
112 files changed, 15888 insertions, 2726 deletions
diff --git a/modules/basis_universal/texture_basisu.cpp b/modules/basis_universal/texture_basisu.cpp index 2ed0340927..5831d3de2a 100644 --- a/modules/basis_universal/texture_basisu.cpp +++ b/modules/basis_universal/texture_basisu.cpp @@ -39,44 +39,36 @@ #include <transcoder/basisu_transcoder.h> void TextureBasisU::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_basisu_data", "data"), &TextureBasisU::set_basisu_data); ClassDB::bind_method(D_METHOD("get_basisu_data"), &TextureBasisU::get_data); ClassDB::bind_method(D_METHOD("import"), &TextureBasisU::import); ADD_PROPERTY(PropertyInfo(Variant::PACKED_BYTE_ARRAY, "basisu_data"), "set_basisu_data", "get_basisu_data"); - }; int TextureBasisU::get_width() const { - return tex_size.x; }; int TextureBasisU::get_height() const { - return tex_size.y; }; RID TextureBasisU::get_rid() const { - return texture; }; bool TextureBasisU::has_alpha() const { - return false; }; void TextureBasisU::set_flags(uint32_t p_flags) { - flags = p_flags; RenderingServer::get_singleton()->texture_set_flags(texture, p_flags); }; uint32_t TextureBasisU::get_flags() const { - return flags; }; @@ -95,12 +87,10 @@ void TextureBasisU::set_basisu_data(const Vector<uint8_t>& p_data) { Image::Format imgfmt; if (OS::get_singleton()->has_feature("s3tc")) { - format = basist::cTFBC3; // get this from renderer imgfmt = Image::FORMAT_DXT5; } else if (OS::get_singleton()->has_feature("etc2")) { - format = basist::cTFETC2; imgfmt = Image::FORMAT_ETC2_RGBA8; }; @@ -126,7 +116,6 @@ void TextureBasisU::set_basisu_data(const Vector<uint8_t>& p_data) { int ofs = 0; tr.start_transcoding(ptr, size); for (int i=0; i<info.m_total_levels; i++) { - basist::basisu_image_level_info level; tr.get_image_level_info(ptr, size, level, 0, i); @@ -214,19 +203,16 @@ Error TextureBasisU::import(const Ref<Image>& p_img) { Vector<uint8_t> TextureBasisU::get_basisu_data() const { - return data; }; TextureBasisU::TextureBasisU() { - flags = FLAGS_DEFAULT; texture = RenderingServer::get_singleton()->texture_create(); }; TextureBasisU::~TextureBasisU() { - RenderingServer::get_singleton()->free(texture); }; diff --git a/modules/basis_universal/texture_basisu.h b/modules/basis_universal/texture_basisu.h index 20ecf15a59..99248f9162 100644 --- a/modules/basis_universal/texture_basisu.h +++ b/modules/basis_universal/texture_basisu.h @@ -41,7 +41,6 @@ #if 0 class TextureBasisU : public Texture { - GDCLASS(TextureBasisU, Texture); RES_BASE_EXTENSION("butex"); @@ -74,7 +73,6 @@ public: TextureBasisU(); ~TextureBasisU(); - }; #endif diff --git a/modules/bullet/bullet_physics_server.cpp b/modules/bullet/bullet_physics_server.cpp index f7290666ad..663ad6e3e1 100644 --- a/modules/bullet/bullet_physics_server.cpp +++ b/modules/bullet/bullet_physics_server.cpp @@ -1553,9 +1553,6 @@ void BulletPhysicsServer3D::step(float p_deltaTime) { } } -void BulletPhysicsServer3D::sync() { -} - void BulletPhysicsServer3D::flush_queries() { if (!active) { return; diff --git a/modules/bullet/bullet_physics_server.h b/modules/bullet/bullet_physics_server.h index 02ba5458d8..dca9339c44 100644 --- a/modules/bullet/bullet_physics_server.h +++ b/modules/bullet/bullet_physics_server.h @@ -397,7 +397,6 @@ public: virtual void init() override; virtual void step(float p_deltaTime) override; - virtual void sync() override; virtual void flush_queries() override; virtual void finish() override; diff --git a/modules/dds/texture_loader_dds.cpp b/modules/dds/texture_loader_dds.cpp index 2f4f7d7a4c..627153fbc8 100644 --- a/modules/dds/texture_loader_dds.cpp +++ b/modules/dds/texture_loader_dds.cpp @@ -373,7 +373,6 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path, int colcount = size/4; for(int i=0;i<colcount;i++) { - uint8_t r = wb[i*4+1]; uint8_t g = wb[i*4+2]; uint8_t b = wb[i*4+3]; @@ -392,7 +391,6 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path, int colcount = size/3; for(int i=0;i<colcount;i++) { - SWAP( wb[i*3+0],wb[i*3+2] ); }*/ } break; diff --git a/modules/etc/image_etc.cpp b/modules/etc/image_etc.cpp index 6cac2458f9..4e9e64c6a7 100644 --- a/modules/etc/image_etc.cpp +++ b/modules/etc/image_etc.cpp @@ -106,7 +106,6 @@ static void _compress_etc(Image *p_img, float p_lossy_quality, bool force_etc1_f // If VRAM compression is using ETC, but image has alpha, convert to RGBA4444 or LA8 // This saves space while maintaining the alpha channel if (detected_channels == Image::USED_CHANNELS_RGBA) { - if (p_img->has_mipmaps()) { // Image doesn't support mipmaps with RGBA4444 textures p_img->clear_mipmaps(); @@ -114,7 +113,6 @@ static void _compress_etc(Image *p_img, float p_lossy_quality, bool force_etc1_f p_img->convert(Image::FORMAT_RGBA4444); return; } else if (detected_channels == Image::USE_CHANNELS_LA) { - p_img->convert(Image::FORMAT_LA8); return; } diff --git a/modules/gdnative/SCsub b/modules/gdnative/SCsub index 0e2291c1f9..45354ce692 100644 --- a/modules/gdnative/SCsub +++ b/modules/gdnative/SCsub @@ -20,6 +20,7 @@ SConscript("net/SCsub") SConscript("xr/SCsub") SConscript("pluginscript/SCsub") SConscript("videodecoder/SCsub") +SConscript("text/SCsub") import gdnative_builders @@ -30,5 +31,3 @@ _, gensource = env_gdnative.CommandNoCache( env.Run(gdnative_builders.build_gdnative_api_struct, "Generating GDNative API."), ) env_gdnative.add_source_files(env.modules_sources, [gensource]) - -env.use_ptrcall = True diff --git a/modules/gdnative/config.py b/modules/gdnative/config.py index 7603e7d69d..fd860e9763 100644 --- a/modules/gdnative/config.py +++ b/modules/gdnative/config.py @@ -3,7 +3,7 @@ def can_build(env, platform): def configure(env): - env.use_ptrcall = True + pass def get_doc_classes(): diff --git a/modules/gdnative/gdnative/array.cpp b/modules/gdnative/gdnative/array.cpp index a5567f1e6b..863889acbc 100644 --- a/modules/gdnative/gdnative/array.cpp +++ b/modules/gdnative/gdnative/array.cpp @@ -90,6 +90,18 @@ void GDAPI godot_array_new_packed_vector2_array(godot_array *r_dest, const godot } } +void GDAPI godot_array_new_packed_vector2i_array(godot_array *r_dest, const godot_packed_vector2i_array *p_pv2a) { + Array *dest = (Array *)r_dest; + Vector<Vector2i> *pca = (Vector<Vector2i> *)p_pv2a; + memnew_placement(dest, Array); + dest->resize(pca->size()); + + for (int i = 0; i < dest->size(); i++) { + Variant v = pca->operator[](i); + dest->operator[](i) = v; + } +} + void GDAPI godot_array_new_packed_string_array(godot_array *r_dest, const godot_packed_string_array *p_psa) { Array *dest = (Array *)r_dest; Vector<String> *pca = (Vector<String> *)p_psa; diff --git a/modules/gdnative/gdnative/packed_arrays.cpp b/modules/gdnative/gdnative/packed_arrays.cpp index 9139fd89a1..cc1e05b8a4 100644 --- a/modules/gdnative/gdnative/packed_arrays.cpp +++ b/modules/gdnative/gdnative/packed_arrays.cpp @@ -49,6 +49,7 @@ static_assert(sizeof(godot_packed_float32_array) == sizeof(Vector<float>), "Vect static_assert(sizeof(godot_packed_float64_array) == sizeof(Vector<double>), "Vector<double> size mismatch"); static_assert(sizeof(godot_packed_string_array) == sizeof(Vector<String>), "Vector<String> size mismatch"); static_assert(sizeof(godot_packed_vector2_array) == sizeof(Vector<Vector2>), "Vector<Vector2> size mismatch"); +static_assert(sizeof(godot_packed_vector2i_array) == sizeof(Vector<Vector2i>), "Vector<Vector2i> size mismatch"); static_assert(sizeof(godot_packed_vector3_array) == sizeof(Vector<Vector3>), "Vector<Vector3> size mismatch"); static_assert(sizeof(godot_packed_color_array) == sizeof(Vector<Color>), "Vector<Color> size mismatch"); @@ -799,6 +800,118 @@ void GDAPI godot_packed_vector2_array_destroy(godot_packed_vector2_array *p_self ((Vector<Vector2> *)p_self)->~Vector(); } +// vector2i + +void GDAPI godot_packed_vector2i_array_new(godot_packed_vector2i_array *r_dest) { + Vector<Vector2i> *dest = (Vector<Vector2i> *)r_dest; + memnew_placement(dest, Vector<Vector2i>); +} + +void GDAPI godot_packed_vector2i_array_new_copy(godot_packed_vector2i_array *r_dest, const godot_packed_vector2i_array *p_src) { + Vector<Vector2i> *dest = (Vector<Vector2i> *)r_dest; + const Vector<Vector2i> *src = (const Vector<Vector2i> *)p_src; + memnew_placement(dest, Vector<Vector2i>(*src)); +} + +void GDAPI godot_packed_vector2i_array_new_with_array(godot_packed_vector2i_array *r_dest, const godot_array *p_a) { + Vector<Vector2i> *dest = (Vector<Vector2i> *)r_dest; + Array *a = (Array *)p_a; + memnew_placement(dest, Vector<Vector2i>); + + dest->resize(a->size()); + for (int i = 0; i < a->size(); i++) { + dest->set(i, (*a)[i]); + } +} + +const godot_vector2i GDAPI *godot_packed_vector2i_array_ptr(const godot_packed_vector2i_array *p_self) { + const Vector<Vector2i> *self = (const Vector<Vector2i> *)p_self; + return (const godot_vector2i *)self->ptr(); +} + +godot_vector2i GDAPI *godot_packed_vector2i_array_ptrw(godot_packed_vector2i_array *p_self) { + Vector<Vector2i> *self = (Vector<Vector2i> *)p_self; + return (godot_vector2i *)self->ptrw(); +} + +void GDAPI godot_packed_vector2i_array_append(godot_packed_vector2i_array *p_self, const godot_vector2i *p_data) { + Vector<Vector2i> *self = (Vector<Vector2i> *)p_self; + Vector2i &s = *(Vector2i *)p_data; + self->push_back(s); +} + +void GDAPI godot_packed_vector2i_array_append_array(godot_packed_vector2i_array *p_self, const godot_packed_vector2i_array *p_array) { + Vector<Vector2i> *self = (Vector<Vector2i> *)p_self; + Vector<Vector2i> *array = (Vector<Vector2i> *)p_array; + self->append_array(*array); +} + +godot_error GDAPI godot_packed_vector2i_array_insert(godot_packed_vector2i_array *p_self, const godot_int p_idx, const godot_vector2i *p_data) { + Vector<Vector2i> *self = (Vector<Vector2i> *)p_self; + Vector2i &s = *(Vector2i *)p_data; + return (godot_error)self->insert(p_idx, s); +} + +godot_bool GDAPI godot_packed_vector2i_array_has(godot_packed_vector2i_array *p_self, const godot_vector2i *p_value) { + Vector<Vector2i> *self = (Vector<Vector2i> *)p_self; + Vector2i &v = *(Vector2i *)p_value; + return (godot_bool)self->has(v); +} + +void GDAPI godot_packed_vector2i_array_sort(godot_packed_vector2i_array *p_self) { + Vector<Vector2i> *self = (Vector<Vector2i> *)p_self; + self->sort(); +} + +void GDAPI godot_packed_vector2i_array_invert(godot_packed_vector2i_array *p_self) { + Vector<Vector2i> *self = (Vector<Vector2i> *)p_self; + self->invert(); +} + +void GDAPI godot_packed_vector2i_array_push_back(godot_packed_vector2i_array *p_self, const godot_vector2i *p_data) { + Vector<Vector2i> *self = (Vector<Vector2i> *)p_self; + Vector2i &s = *(Vector2i *)p_data; + self->push_back(s); +} + +void GDAPI godot_packed_vector2i_array_remove(godot_packed_vector2i_array *p_self, const godot_int p_idx) { + Vector<Vector2i> *self = (Vector<Vector2i> *)p_self; + self->remove(p_idx); +} + +void GDAPI godot_packed_vector2i_array_resize(godot_packed_vector2i_array *p_self, const godot_int p_size) { + Vector<Vector2i> *self = (Vector<Vector2i> *)p_self; + self->resize(p_size); +} + +void GDAPI godot_packed_vector2i_array_set(godot_packed_vector2i_array *p_self, const godot_int p_idx, const godot_vector2i *p_data) { + Vector<Vector2i> *self = (Vector<Vector2i> *)p_self; + Vector2i &s = *(Vector2i *)p_data; + self->set(p_idx, s); +} + +godot_vector2i GDAPI godot_packed_vector2i_array_get(const godot_packed_vector2i_array *p_self, const godot_int p_idx) { + const Vector<Vector2i> *self = (const Vector<Vector2i> *)p_self; + godot_vector2i v; + Vector2i *s = (Vector2i *)&v; + *s = self->get(p_idx); + return v; +} + +godot_int GDAPI godot_packed_vector2i_array_size(const godot_packed_vector2i_array *p_self) { + const Vector<Vector2i> *self = (const Vector<Vector2i> *)p_self; + return self->size(); +} + +godot_bool GDAPI godot_packed_vector2i_array_empty(const godot_packed_vector2i_array *p_self) { + const Vector<Vector2i> *self = (const Vector<Vector2i> *)p_self; + return self->empty(); +} + +void GDAPI godot_packed_vector2i_array_destroy(godot_packed_vector2i_array *p_self) { + ((Vector<Vector2i> *)p_self)->~Vector(); +} + // vector3 void GDAPI godot_packed_vector3_array_new(godot_packed_vector3_array *r_dest) { diff --git a/modules/gdnative/gdnative_api.json b/modules/gdnative/gdnative_api.json index 40d0f75871..84b36b3745 100644 --- a/modules/gdnative/gdnative_api.json +++ b/modules/gdnative/gdnative_api.json @@ -260,6 +260,14 @@ ] }, { + "name": "godot_array_new_packed_vector2i_array", + "return_type": "void", + "arguments": [ + ["godot_array *", "r_dest"], + ["const godot_packed_vector2i_array *", "p_pv2a"] + ] + }, + { "name": "godot_array_new_packed_string_array", "return_type": "void", "arguments": [ @@ -2638,6 +2646,152 @@ ] }, { + "name": "godot_packed_vector2i_array_new", + "return_type": "void", + "arguments": [ + ["godot_packed_vector2i_array *", "r_dest"] + ] + }, + { + "name": "godot_packed_vector2i_array_new_copy", + "return_type": "void", + "arguments": [ + ["godot_packed_vector2i_array *", "r_dest"], + ["const godot_packed_vector2i_array *", "p_src"] + ] + }, + { + "name": "godot_packed_vector2i_array_new_with_array", + "return_type": "void", + "arguments": [ + ["godot_packed_vector2i_array *", "r_dest"], + ["const godot_array *", "p_a"] + ] + }, + { + "name": "godot_packed_vector2i_array_empty", + "return_type": "godot_bool", + "arguments": [ + ["const godot_packed_vector2i_array *", "p_self"] + ] + }, + { + "name": "godot_packed_vector2i_array_append", + "return_type": "void", + "arguments": [ + ["godot_packed_vector2i_array *", "p_self"], + ["const godot_vector2i *", "p_data"] + ] + }, + { + "name": "godot_packed_vector2i_array_append_array", + "return_type": "void", + "arguments": [ + ["godot_packed_vector2i_array *", "p_self"], + ["const godot_packed_vector2i_array *", "p_array"] + ] + }, + { + "name": "godot_packed_vector2i_array_insert", + "return_type": "godot_error", + "arguments": [ + ["godot_packed_vector2i_array *", "p_self"], + ["const godot_int", "p_idx"], + ["const godot_vector2i *", "p_data"] + ] + }, + { + "name": "godot_packed_vector2i_array_has", + "return_type": "godot_bool", + "arguments": [ + ["godot_packed_vector2i_array *", "p_self"], + ["const godot_vector2i *", "p_value"] + ] + }, + { + "name": "godot_packed_vector2i_array_sort", + "return_type": "void", + "arguments": [ + ["godot_packed_vector2i_array *", "p_self"] + ] + }, + { + "name": "godot_packed_vector2i_array_invert", + "return_type": "void", + "arguments": [ + ["godot_packed_vector2i_array *", "p_self"] + ] + }, + { + "name": "godot_packed_vector2i_array_push_back", + "return_type": "void", + "arguments": [ + ["godot_packed_vector2i_array *", "p_self"], + ["const godot_vector2i *", "p_data"] + ] + }, + { + "name": "godot_packed_vector2i_array_remove", + "return_type": "void", + "arguments": [ + ["godot_packed_vector2i_array *", "p_self"], + ["const godot_int", "p_idx"] + ] + }, + { + "name": "godot_packed_vector2i_array_resize", + "return_type": "void", + "arguments": [ + ["godot_packed_vector2i_array *", "p_self"], + ["const godot_int", "p_size"] + ] + }, + { + "name": "godot_packed_vector2i_array_ptr", + "return_type": "const godot_vector2i *", + "arguments": [ + ["const godot_packed_vector2i_array *", "p_self"] + ] + }, + { + "name": "godot_packed_vector2i_array_ptrw", + "return_type": "godot_vector2i *", + "arguments": [ + ["godot_packed_vector2i_array *", "p_self"] + ] + }, + { + "name": "godot_packed_vector2i_array_set", + "return_type": "void", + "arguments": [ + ["godot_packed_vector2i_array *", "p_self"], + ["const godot_int", "p_idx"], + ["const godot_vector2i *", "p_data"] + ] + }, + { + "name": "godot_packed_vector2i_array_get", + "return_type": "godot_vector2i", + "arguments": [ + ["const godot_packed_vector2i_array *", "p_self"], + ["const godot_int", "p_idx"] + ] + }, + { + "name": "godot_packed_vector2i_array_size", + "return_type": "godot_int", + "arguments": [ + ["const godot_packed_vector2i_array *", "p_self"] + ] + }, + { + "name": "godot_packed_vector2i_array_destroy", + "return_type": "void", + "arguments": [ + ["godot_packed_vector2i_array *", "p_self"] + ] + }, + { "name": "godot_packed_vector3_array_new", "return_type": "void", "arguments": [ @@ -7615,6 +7769,306 @@ ] } ] + }, + { + "name": "text", + "type": "TEXT", + "version": { + "major": 1, + "minor": 0 + }, + "next": null, + "api": [ + { + "name": "godot_text_register_interface", + "return_type": "void", + "arguments": [ + ["const godot_text_interface_gdnative *", "p_interface"], + ["const godot_string *", "p_name"], + ["uint32_t", "p_features"] + ] + }, + { + "name": "godot_glyph_new", + "return_type": "void", + "arguments": [ + ["godot_glyph *", "r_dest"] + ] + }, + { + "name": "godot_glyph_get_range", + "return_type": "godot_vector2i", + "arguments": [ + ["const godot_glyph *", "p_self"] + ] + }, + { + "name": "godot_glyph_set_range", + "return_type": "void", + "arguments": [ + ["godot_glyph *", "p_self"], + ["const godot_vector2i *", "p_range"] + ] + }, + { + "name": "godot_glyph_get_count", + "return_type": "godot_int", + "arguments": [ + ["const godot_glyph *", "p_self"] + ] + }, + { + "name": "godot_glyph_set_count", + "return_type": "void", + "arguments": [ + ["godot_glyph *", "p_self"], + ["godot_int", "p_count"] + ] + }, + { + "name": "godot_glyph_get_repeat", + "return_type": "godot_int", + "arguments": [ + ["const godot_glyph *", "p_self"] + ] + }, + { + "name": "godot_glyph_set_repeat", + "return_type": "void", + "arguments": [ + ["godot_glyph *", "p_self"], + ["godot_int", "p_repeat"] + ] + }, + { + "name": "godot_glyph_get_flags", + "return_type": "godot_int", + "arguments": [ + ["const godot_glyph *", "p_self"] + ] + }, + { + "name": "godot_glyph_set_flags", + "return_type": "void", + "arguments": [ + ["godot_glyph *", "p_self"], + ["godot_int", "p_flags"] + ] + }, + { + "name": "godot_glyph_get_offset", + "return_type": "godot_vector2", + "arguments": [ + ["const godot_glyph *", "p_self"] + ] + }, + { + "name": "godot_glyph_set_offset", + "return_type": "void", + "arguments": [ + ["godot_glyph *", "p_self"], + ["const godot_vector2 *", "p_offset"] + ] + }, + { + "name": "godot_glyph_get_advance", + "return_type": "godot_real", + "arguments": [ + ["const godot_glyph *", "p_self"] + ] + }, + { + "name": "godot_glyph_set_advance", + "return_type": "void", + "arguments": [ + ["godot_glyph *", "p_self"], + ["godot_real", "p_advance"] + ] + }, + { + "name": "godot_glyph_get_font", + "return_type": "godot_rid", + "arguments": [ + ["const godot_glyph *", "p_self"] + ] + }, + { + "name": "godot_glyph_set_font", + "return_type": "void ", + "arguments": [ + ["godot_glyph *", "p_self"], + ["godot_rid *", "p_font"] + ] + }, + { + "name": "godot_glyph_get_font_size", + "return_type": "godot_int", + "arguments": [ + ["const godot_glyph *", "p_self"] + ] + }, + { + "name": "godot_glyph_set_font_size", + "return_type": "void", + "arguments": [ + ["godot_glyph *", "p_self"], + ["godot_int", "p_size"] + ] + }, + { + "name": "godot_glyph_get_index", + "return_type": "godot_int", + "arguments": [ + ["const godot_glyph *", "p_self"] + ] + }, + { + "name": "godot_glyph_set_index", + "return_type": "void", + "arguments": [ + ["godot_glyph *", "p_self"], + ["godot_int", "p_index"] + ] + }, + { + "name": "godot_packed_glyph_array_new", + "return_type": "void", + "arguments": [ + ["godot_packed_glyph_array *", "r_dest"] + ] + }, + { + "name": "godot_packed_glyph_array_new_copy", + "return_type": "void", + "arguments": [ + ["godot_packed_glyph_array *", "r_dest"], + ["const godot_packed_glyph_array *", "p_src"] + ] + }, + { + "name": "godot_packed_glyph_array_empty", + "return_type": "godot_bool", + "arguments": [ + ["const godot_packed_glyph_array *", "p_self"] + ] + }, + { + "name": "godot_packed_glyph_array_append", + "return_type": "void", + "arguments": [ + ["godot_packed_glyph_array *", "p_self"], + ["const godot_glyph *", "p_data"] + ] + }, + { + "name": "godot_packed_glyph_array_append_array", + "return_type": "void", + "arguments": [ + ["godot_packed_glyph_array *", "p_self"], + ["const godot_packed_glyph_array *", "p_array"] + ] + }, + { + "name": "godot_packed_glyph_array_insert", + "return_type": "godot_error", + "arguments": [ + ["godot_packed_glyph_array *", "p_self"], + ["const godot_int", "p_idx"], + ["const godot_glyph *", "p_data"] + ] + }, + { + "name": "godot_packed_glyph_array_has", + "return_type": "godot_bool", + "arguments": [ + ["godot_packed_glyph_array *", "p_self"], + ["const godot_glyph *", "p_value"] + ] + }, + { + "name": "godot_packed_glyph_array_sort", + "return_type": "void", + "arguments": [ + ["godot_packed_glyph_array *", "p_self"] + ] + }, + { + "name": "godot_packed_glyph_array_invert", + "return_type": "void", + "arguments": [ + ["godot_packed_glyph_array *", "p_self"] + ] + }, + { + "name": "godot_packed_glyph_array_push_back", + "return_type": "void", + "arguments": [ + ["godot_packed_glyph_array *", "p_self"], + ["const godot_glyph *", "p_data"] + ] + }, + { + "name": "godot_packed_glyph_array_remove", + "return_type": "void", + "arguments": [ + ["godot_packed_glyph_array *", "p_self"], + ["const godot_int", "p_idx"] + ] + }, + { + "name": "godot_packed_glyph_array_resize", + "return_type": "void", + "arguments": [ + ["godot_packed_glyph_array *", "p_self"], + ["const godot_int", "p_size"] + ] + }, + { + "name": "godot_packed_glyph_array_ptr", + "return_type": "const godot_glyph *", + "arguments": [ + ["const godot_packed_glyph_array *", "p_self"] + ] + }, + { + "name": "godot_packed_glyph_array_ptrw", + "return_type": "godot_glyph *", + "arguments": [ + ["godot_packed_glyph_array *", "p_self"] + ] + }, + { + "name": "godot_packed_glyph_array_set", + "return_type": "void", + "arguments": [ + ["godot_packed_glyph_array *", "p_self"], + ["const godot_int", "p_idx"], + ["const godot_glyph *", "p_data"] + ] + }, + { + "name": "godot_packed_glyph_array_get", + "return_type": "godot_glyph", + "arguments": [ + ["const godot_packed_glyph_array *", "p_self"], + ["const godot_int", "p_idx"] + ] + }, + { + "name": "godot_packed_glyph_array_size", + "return_type": "godot_int", + "arguments": [ + ["const godot_packed_glyph_array *", "p_self"] + ] + }, + { + "name": "godot_packed_glyph_array_destroy", + "return_type": "void", + "arguments": [ + ["godot_packed_glyph_array *", "p_self"] + ] + } + ] } ] } diff --git a/modules/gdnative/gdnative_builders.py b/modules/gdnative/gdnative_builders.py index 28e4957b2f..d03298d7a9 100644 --- a/modules/gdnative/gdnative_builders.py +++ b/modules/gdnative/gdnative_builders.py @@ -24,6 +24,7 @@ def _build_gdnative_api_struct_header(api): "#include <net/godot_net.h>", "#include <pluginscript/godot_pluginscript.h>", "#include <videodecoder/godot_videodecoder.h>", + "#include <text/godot_text.h>", "", "#ifdef __cplusplus", 'extern "C" {', diff --git a/modules/gdnative/include/gdnative/array.h b/modules/gdnative/include/gdnative/array.h index 4db685873f..7a59493b7d 100644 --- a/modules/gdnative/include/gdnative/array.h +++ b/modules/gdnative/include/gdnative/array.h @@ -65,6 +65,7 @@ void GDAPI godot_array_new_copy(godot_array *r_dest, const godot_array *p_src); void GDAPI godot_array_new_packed_color_array(godot_array *r_dest, const godot_packed_color_array *p_pca); void GDAPI godot_array_new_packed_vector3_array(godot_array *r_dest, const godot_packed_vector3_array *p_pv3a); void GDAPI godot_array_new_packed_vector2_array(godot_array *r_dest, const godot_packed_vector2_array *p_pv2a); +void GDAPI godot_array_new_packed_vector2i_array(godot_array *r_dest, const godot_packed_vector2i_array *p_pv2a); void GDAPI godot_array_new_packed_string_array(godot_array *r_dest, const godot_packed_string_array *p_psa); void GDAPI godot_array_new_packed_float32_array(godot_array *r_dest, const godot_packed_float32_array *p_pra); void GDAPI godot_array_new_packed_float64_array(godot_array *r_dest, const godot_packed_float64_array *p_pra); diff --git a/modules/gdnative/include/gdnative/packed_arrays.h b/modules/gdnative/include/gdnative/packed_arrays.h index 6a1727d76f..ce9579f307 100644 --- a/modules/gdnative/include/gdnative/packed_arrays.h +++ b/modules/gdnative/include/gdnative/packed_arrays.h @@ -114,6 +114,17 @@ typedef struct { } godot_packed_vector2_array; #endif +/////// PackedVector2iArray + +#define GODOT_PACKED_VECTOR2I_ARRAY_SIZE (2 * sizeof(void *)) + +#ifndef GODOT_CORE_API_GODOT_PACKED_VECTOR2I_ARRAY_TYPE_DEFINED +#define GODOT_CORE_API_GODOT_PACKED_VECTOR2I_ARRAY_TYPE_DEFINED +typedef struct { + uint8_t _dont_touch_that[GODOT_PACKED_VECTOR2I_ARRAY_SIZE]; +} godot_packed_vector2i_array; +#endif + /////// PackedVector3Array #define GODOT_PACKED_VECTOR3_ARRAY_SIZE (2 * sizeof(void *)) @@ -404,6 +415,42 @@ godot_bool GDAPI godot_packed_vector2_array_empty(const godot_packed_vector2_arr void GDAPI godot_packed_vector2_array_destroy(godot_packed_vector2_array *p_self); +// vector2i + +void GDAPI godot_packed_vector2i_array_new(godot_packed_vector2i_array *r_dest); +void GDAPI godot_packed_vector2i_array_new_copy(godot_packed_vector2i_array *r_dest, const godot_packed_vector2i_array *p_src); +void GDAPI godot_packed_vector2i_array_new_with_array(godot_packed_vector2i_array *r_dest, const godot_array *p_a); + +const godot_vector2i GDAPI *godot_packed_vector2i_array_ptr(const godot_packed_vector2i_array *p_self); +godot_vector2i GDAPI *godot_packed_vector2i_array_ptrw(godot_packed_vector2i_array *p_self); + +void GDAPI godot_packed_vector2i_array_append(godot_packed_vector2i_array *p_self, const godot_vector2i *p_data); + +void GDAPI godot_packed_vector2i_array_append_array(godot_packed_vector2i_array *p_self, const godot_packed_vector2i_array *p_array); + +godot_error GDAPI godot_packed_vector2i_array_insert(godot_packed_vector2i_array *p_self, const godot_int p_idx, const godot_vector2i *p_data); + +godot_bool GDAPI godot_packed_vector2i_array_has(godot_packed_vector2i_array *p_self, const godot_vector2i *p_value); + +void GDAPI godot_packed_vector2i_array_sort(godot_packed_vector2i_array *p_self); + +void GDAPI godot_packed_vector2i_array_invert(godot_packed_vector2i_array *p_self); + +void GDAPI godot_packed_vector2i_array_push_back(godot_packed_vector2i_array *p_self, const godot_vector2i *p_data); + +void GDAPI godot_packed_vector2i_array_remove(godot_packed_vector2i_array *p_self, const godot_int p_idx); + +void GDAPI godot_packed_vector2i_array_resize(godot_packed_vector2i_array *p_self, const godot_int p_size); + +void GDAPI godot_packed_vector2i_array_set(godot_packed_vector2i_array *p_self, const godot_int p_idx, const godot_vector2i *p_data); +godot_vector2i GDAPI godot_packed_vector2i_array_get(const godot_packed_vector2i_array *p_self, const godot_int p_idx); + +godot_int GDAPI godot_packed_vector2i_array_size(const godot_packed_vector2i_array *p_self); + +godot_bool GDAPI godot_packed_vector2i_array_empty(const godot_packed_vector2i_array *p_self); + +void GDAPI godot_packed_vector2i_array_destroy(godot_packed_vector2i_array *p_self); + // vector3 void GDAPI godot_packed_vector3_array_new(godot_packed_vector3_array *r_dest); diff --git a/modules/gdnative/include/nativescript/godot_nativescript.h b/modules/gdnative/include/nativescript/godot_nativescript.h index 825033c99c..cc12d58037 100644 --- a/modules/gdnative/include/nativescript/godot_nativescript.h +++ b/modules/gdnative/include/nativescript/godot_nativescript.h @@ -85,7 +85,6 @@ typedef enum { } godot_nativescript_property_hint; typedef enum { - GODOT_PROPERTY_USAGE_STORAGE = 1, GODOT_PROPERTY_USAGE_EDITOR = 2, GODOT_PROPERTY_USAGE_NETWORK = 4, diff --git a/modules/gdnative/include/text/godot_text.h b/modules/gdnative/include/text/godot_text.h new file mode 100644 index 0000000000..2eac6adfb5 --- /dev/null +++ b/modules/gdnative/include/text/godot_text.h @@ -0,0 +1,228 @@ +/*************************************************************************/ +/* godot_text.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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. */ +/*************************************************************************/ + +#ifndef GODOT_NATIVETEXT_H +#define GODOT_NATIVETEXT_H + +#include <gdnative/gdnative.h> + +#ifdef __cplusplus +extern "C" { +#endif + +#define GODOT_TEXT_API_MAJOR 1 +#define GODOT_TEXT_API_MINOR 0 + +#define GODOT_GLYPH_SIZE 40 + +#ifndef GODOT_TEXT_API_GODOT_GLYPH_TYPE_DEFINED +#define GODOT_TEXT_API_GODOT_GLYPH_TYPE_DEFINED +typedef struct { + uint8_t _dont_touch_that[GODOT_GLYPH_SIZE]; +} godot_glyph; +#endif + +#define GODOT_PACKED_GLYPH_ARRAY_SIZE (2 * sizeof(void *)) + +#ifndef GODOT_TEXT_API_GODOT_PACKED_GLYPH_ARRAY_TYPE_DEFINED +#define GODOT_TEXT_API_GODOT_PACKED_GLYPH_ARRAY_TYPE_DEFINED +typedef struct { + uint8_t _dont_touch_that[GODOT_PACKED_GLYPH_ARRAY_SIZE]; +} godot_packed_glyph_array; +#endif + +typedef struct { + godot_gdnative_api_version version; + void *(*constructor)(godot_object *); + void (*destructor)(void *); + godot_string (*get_name)(const void *); + godot_bool (*has_feature)(const void *, godot_int); + bool (*load_support_data)(void *, const godot_string *); + godot_string (*get_support_data_filename)(const void *); + godot_string (*get_support_data_info)(const void *); + bool (*save_support_data)(void *, const godot_string *); + bool (*is_locale_right_to_left)(void *, const godot_string *); + void (*free)(void *, godot_rid *); + bool (*has)(void *, godot_rid *); + godot_rid (*create_font_system)(void *, const godot_string *, int); + godot_rid (*create_font_resource)(void *, const godot_string *, int); + godot_rid (*create_font_memory)(void *, const uint8_t *, size_t, godot_string *, int); + float (*font_get_height)(void *, godot_rid *, int); + float (*font_get_ascent)(void *, godot_rid *, int); + float (*font_get_descent)(void *, godot_rid *, int); + float (*font_get_underline_position)(void *, godot_rid *, int); + float (*font_get_underline_thickness)(void *, godot_rid *, int); + void (*font_set_antialiased)(void *, godot_rid *, bool); + bool (*font_get_antialiased)(void *, godot_rid *); + godot_dictionary (*font_get_feature_list)(void *, godot_rid *); + void (*font_set_distance_field_hint)(void *, godot_rid *, bool); + bool (*font_get_distance_field_hint)(void *, godot_rid *); + void (*font_set_hinting)(void *, godot_rid *, godot_int); + godot_int (*font_get_hinting)(void *, godot_rid *); + void (*font_set_force_autohinter)(void *, godot_rid *, bool); + bool (*font_get_force_autohinter)(void *, godot_rid *); + bool (*font_has_char)(void *, godot_rid *, char32_t); + godot_string (*font_get_supported_chars)(void *, godot_rid *); + bool (*font_has_outline)(void *, godot_rid *); + int (*font_get_base_size)(void *, godot_rid *); + bool (*font_is_language_supported)(void *, godot_rid *, const godot_string *); + void (*font_set_language_support_override)(void *, godot_rid *, const godot_string *, bool); + bool (*font_get_language_support_override)(void *, godot_rid *, const godot_string *); + void (*font_remove_language_support_override)(void *, godot_rid *, const godot_string *); + godot_packed_string_array (*font_get_language_support_overrides)(void *, godot_rid *); + bool (*font_is_script_supported)(void *, godot_rid *, const godot_string *); + void (*font_set_script_support_override)(void *, godot_rid *, const godot_string *, bool); + bool (*font_get_script_support_override)(void *, godot_rid *, const godot_string *); + void (*font_remove_script_support_override)(void *, godot_rid *, const godot_string *); + godot_packed_string_array (*font_get_script_support_overrides)(void *, godot_rid *); + uint32_t (*font_get_glyph_index)(void *, godot_rid *, char32_t, char32_t); + godot_vector2 (*font_get_glyph_advance)(void *, godot_rid *, uint32_t, int); + godot_vector2 (*font_get_glyph_kerning)(void *, godot_rid *, uint32_t, uint32_t, int); + godot_vector2 (*font_draw_glyph)(void *, godot_rid *, godot_rid *, int, const godot_vector2 *, uint32_t, const godot_color *); + godot_vector2 (*font_draw_glyph_outline)(void *, godot_rid *, godot_rid *, int, int, const godot_vector2 *, uint32_t, const godot_color *); + float (*font_get_oversampling)(void *); + void (*font_set_oversampling)(void *, float); + godot_packed_string_array (*get_system_fonts)(void *); + godot_rid (*create_shaped_text)(void *, godot_int, godot_int); + void (*shaped_text_clear)(void *, godot_rid *); + void (*shaped_text_set_direction)(void *, godot_rid *, godot_int); + godot_int (*shaped_text_get_direction)(void *, godot_rid *); + void (*shaped_text_set_bidi_override)(void *, godot_rid *, const godot_packed_vector2i_array *); + void (*shaped_text_set_orientation)(void *, godot_rid *, godot_int); + godot_int (*shaped_text_get_orientation)(void *, godot_rid *); + void (*shaped_text_set_preserve_invalid)(void *, godot_rid *, bool); + bool (*shaped_text_get_preserve_invalid)(void *, godot_rid *); + void (*shaped_text_set_preserve_control)(void *, godot_rid *, bool); + bool (*shaped_text_get_preserve_control)(void *, godot_rid *); + bool (*shaped_text_add_string)(void *, godot_rid *, const godot_string *, const godot_rid **, int, const godot_dictionary *, const godot_string *); + bool (*shaped_text_add_object)(void *, godot_rid *, const godot_variant *, const godot_vector2 *, godot_int, godot_int); + bool (*shaped_text_resize_object)(void *, godot_rid *, const godot_variant *, const godot_vector2 *, godot_int); + godot_rid (*shaped_text_substr)(void *, godot_rid *, godot_int, godot_int); + godot_rid (*shaped_text_get_parent)(void *, godot_rid *); + float (*shaped_text_fit_to_width)(void *, godot_rid *, float, uint8_t); + float (*shaped_text_tab_align)(void *, godot_rid *, godot_packed_float32_array *); + bool (*shaped_text_shape)(void *, godot_rid *); + bool (*shaped_text_update_breaks)(void *, godot_rid *); + bool (*shaped_text_update_justification_ops)(void *, godot_rid *); + bool (*shaped_text_is_ready)(void *, godot_rid *); + godot_packed_glyph_array (*shaped_text_get_glyphs)(void *, godot_rid *); + godot_vector2i (*shaped_text_get_range)(void *, godot_rid *); + godot_packed_glyph_array (*shaped_text_sort_logical)(void *, godot_rid *); + godot_packed_vector2i_array (*shaped_text_get_line_breaks_adv)(void *, godot_rid *, godot_packed_float32_array *, int, bool, uint8_t); + godot_packed_vector2i_array (*shaped_text_get_line_breaks)(void *, godot_rid *, float, int, uint8_t); + godot_packed_vector2i_array (*shaped_text_get_word_breaks)(void *, godot_rid *); + godot_array (*shaped_text_get_objects)(void *, godot_rid *); + godot_rect2 (*shaped_text_get_object_rect)(void *, godot_rid *, const godot_variant *); + godot_vector2 (*shaped_text_get_size)(void *, godot_rid *); + float (*shaped_text_get_ascent)(void *, godot_rid *); + float (*shaped_text_get_descent)(void *, godot_rid *); + float (*shaped_text_get_width)(void *, godot_rid *); + float (*shaped_text_get_underline_position)(void *, godot_rid *); + float (*shaped_text_get_underline_thickness)(void *, godot_rid *); + godot_string (*format_number)(void *, const godot_string *, const godot_string *); + godot_string (*parse_number)(void *, const godot_string *, const godot_string *); + godot_string (*percent_sign)(void *, const godot_string *); +} godot_text_interface_gdnative; + +void GDAPI godot_text_register_interface(const godot_text_interface_gdnative *p_interface, const godot_string *p_name, uint32_t p_features); + +// Glyph + +void GDAPI godot_glyph_new(godot_glyph *r_dest); + +godot_vector2i GDAPI godot_glyph_get_range(const godot_glyph *p_self); +void GDAPI godot_glyph_set_range(godot_glyph *p_self, const godot_vector2i *p_range); + +godot_int GDAPI godot_glyph_get_count(const godot_glyph *p_self); +void GDAPI godot_glyph_set_count(godot_glyph *p_self, godot_int p_count); + +godot_int GDAPI godot_glyph_get_repeat(const godot_glyph *p_self); +void GDAPI godot_glyph_set_repeat(godot_glyph *p_self, godot_int p_repeat); + +godot_int GDAPI godot_glyph_get_flags(const godot_glyph *p_self); +void GDAPI godot_glyph_set_flags(godot_glyph *p_self, godot_int p_flags); + +godot_vector2 GDAPI godot_glyph_get_offset(const godot_glyph *p_self); +void GDAPI godot_glyph_set_offset(godot_glyph *p_self, const godot_vector2 *p_offset); + +godot_real GDAPI godot_glyph_get_advance(const godot_glyph *p_self); +void GDAPI godot_glyph_set_advance(godot_glyph *p_self, godot_real p_advance); + +godot_rid GDAPI godot_glyph_get_font(const godot_glyph *p_self); +void GDAPI godot_glyph_set_font(godot_glyph *p_self, godot_rid *p_font); + +godot_int GDAPI godot_glyph_get_font_size(const godot_glyph *p_self); +void GDAPI godot_glyph_set_font_size(godot_glyph *p_self, godot_int p_size); + +godot_int GDAPI godot_glyph_get_index(const godot_glyph *p_self); +void GDAPI godot_glyph_set_index(godot_glyph *p_self, godot_int p_index); + +// GlyphArray + +void GDAPI godot_packed_glyph_array_new(godot_packed_glyph_array *r_dest); +void GDAPI godot_packed_glyph_array_new_copy(godot_packed_glyph_array *r_dest, const godot_packed_glyph_array *p_src); + +const godot_glyph GDAPI *godot_packed_glyph_array_ptr(const godot_packed_glyph_array *p_self); +godot_glyph GDAPI *godot_packed_glyph_array_ptrw(godot_packed_glyph_array *p_self); + +void GDAPI godot_packed_glyph_array_append(godot_packed_glyph_array *p_self, const godot_glyph *p_data); + +void GDAPI godot_packed_glyph_array_append_array(godot_packed_glyph_array *p_self, const godot_packed_glyph_array *p_array); + +godot_error GDAPI godot_packed_glyph_array_insert(godot_packed_glyph_array *p_self, const godot_int p_idx, const godot_glyph *p_data); + +godot_bool GDAPI godot_packed_glyph_array_has(godot_packed_glyph_array *p_self, const godot_glyph *p_value); + +void GDAPI godot_packed_glyph_array_sort(godot_packed_glyph_array *p_self); + +void GDAPI godot_packed_glyph_array_invert(godot_packed_glyph_array *p_self); + +void GDAPI godot_packed_glyph_array_push_back(godot_packed_glyph_array *p_self, const godot_glyph *p_data); + +void GDAPI godot_packed_glyph_array_remove(godot_packed_glyph_array *p_self, godot_int p_idx); + +void GDAPI godot_packed_glyph_array_resize(godot_packed_glyph_array *p_self, godot_int p_size); + +void GDAPI godot_packed_glyph_array_set(godot_packed_glyph_array *p_self, godot_int p_idx, const godot_glyph *p_data); +godot_glyph GDAPI godot_packed_glyph_array_get(const godot_packed_glyph_array *p_self, godot_int p_idx); + +godot_int GDAPI godot_packed_glyph_array_size(const godot_packed_glyph_array *p_self); + +godot_bool GDAPI godot_packed_glyph_array_empty(const godot_packed_glyph_array *p_self); + +void GDAPI godot_packed_glyph_array_destroy(godot_packed_glyph_array *p_self); + +// Grapheme + +#ifdef __cplusplus +} +#endif + +#endif /* !GODOT_NATIVETEXT_H */ diff --git a/modules/gdnative/tests/test_string.h b/modules/gdnative/tests/test_string.h index aeb855a1c4..2b1aa5bf28 100644 --- a/modules/gdnative/tests/test_string.h +++ b/modules/gdnative/tests/test_string.h @@ -1974,7 +1974,6 @@ TEST_CASE("[GDNative String] humanize_size") { CHECK(u32scmp(godot_string_get_data(&s), U"4.97 GiB") == 0); godot_string_destroy(&s); } - } // namespace TestGDNativeString #endif // TEST_GDNATIVE_STRING_H diff --git a/modules/gdnative/text/SCsub b/modules/gdnative/text/SCsub new file mode 100644 index 0000000000..0b2db3b504 --- /dev/null +++ b/modules/gdnative/text/SCsub @@ -0,0 +1,6 @@ +#!/usr/bin/env python + +Import("env") +Import("env_gdnative") + +env_gdnative.add_source_files(env.modules_sources, "*.cpp") diff --git a/modules/gdnative/text/config.py b/modules/gdnative/text/config.py new file mode 100644 index 0000000000..d22f9454ed --- /dev/null +++ b/modules/gdnative/text/config.py @@ -0,0 +1,6 @@ +def can_build(env, platform): + return True + + +def configure(env): + pass diff --git a/modules/gdnative/text/register_types.cpp b/modules/gdnative/text/register_types.cpp new file mode 100644 index 0000000000..e1d4547aa0 --- /dev/null +++ b/modules/gdnative/text/register_types.cpp @@ -0,0 +1,36 @@ +/*************************************************************************/ +/* register_types.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 "register_types.h" +#include "text_server_gdnative.h" + +void register_text_server_gdn_types() {} + +void unregister_text_server_gdn_types() {} diff --git a/modules/gdnative/text/register_types.h b/modules/gdnative/text/register_types.h new file mode 100644 index 0000000000..027653e58e --- /dev/null +++ b/modules/gdnative/text/register_types.h @@ -0,0 +1,37 @@ +/*************************************************************************/ +/* register_types.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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. */ +/*************************************************************************/ + +#ifndef TEXT_REGISTER_TYPES_H +#define TEXT_REGISTER_TYPES_H + +void register_text_server_gdn_types(); +void unregister_text_server_gdn_types(); + +#endif // TEXT_REGISTER_TYPES_H diff --git a/modules/gdnative/text/text_server_gdnative.cpp b/modules/gdnative/text/text_server_gdnative.cpp new file mode 100644 index 0000000000..68624260a6 --- /dev/null +++ b/modules/gdnative/text/text_server_gdnative.cpp @@ -0,0 +1,835 @@ +/*************************************************************************/ +/* text_server_gdnative.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 "text_server_gdnative.h" + +bool TextServerGDNative::has_feature(Feature p_feature) { + ERR_FAIL_COND_V(interface == nullptr, false); + return interface->has_feature(data, (godot_int)p_feature); +} + +String TextServerGDNative::get_name() const { + ERR_FAIL_COND_V(interface == nullptr, String()); + godot_string result = interface->get_name(data); + String name = *(String *)&result; + godot_string_destroy(&result); + return name; +} + +void TextServerGDNative::free(RID p_rid) { + ERR_FAIL_COND(interface == nullptr); + interface->free(data, (godot_rid *)&p_rid); +} + +bool TextServerGDNative::has(RID p_rid) { + ERR_FAIL_COND_V(interface == nullptr, false); + return interface->has(data, (godot_rid *)&p_rid); +} + +bool TextServerGDNative::load_support_data(const String &p_filename) { + ERR_FAIL_COND_V(interface == nullptr, false); + return interface->load_support_data(data, (godot_string *)&p_filename); +} + +#ifdef TOOLS_ENABLED + +String TextServerGDNative::get_support_data_filename() { + ERR_FAIL_COND_V(interface == nullptr, String()); + godot_string result = interface->get_support_data_filename(data); + String name = *(String *)&result; + godot_string_destroy(&result); + return name; +} + +String TextServerGDNative::get_support_data_info() { + ERR_FAIL_COND_V(interface == nullptr, String()); + godot_string result = interface->get_support_data_info(data); + String info = *(String *)&result; + godot_string_destroy(&result); + return info; +} + +bool TextServerGDNative::save_support_data(const String &p_filename) { + ERR_FAIL_COND_V(interface == nullptr, false); + return interface->save_support_data(data, (godot_string *)&p_filename); +} + +#endif + +bool TextServerGDNative::is_locale_right_to_left(const String &p_locale) { + ERR_FAIL_COND_V(interface == nullptr, false); + return interface->is_locale_right_to_left(data, (godot_string *)&p_locale); +} + +/*************************************************************************/ +/* Font interface */ +/*************************************************************************/ + +RID TextServerGDNative::create_font_system(const String &p_name, int p_base_size) { + ERR_FAIL_COND_V(interface == nullptr, RID()); + godot_rid result = interface->create_font_system(data, (const godot_string *)&p_name, p_base_size); + RID rid = *(RID *)&result; + return rid; +} + +RID TextServerGDNative::create_font_resource(const String &p_filename, int p_base_size) { + ERR_FAIL_COND_V(interface == nullptr, RID()); + godot_rid result = interface->create_font_resource(data, (const godot_string *)&p_filename, p_base_size); + RID rid = *(RID *)&result; + return rid; +} + +RID TextServerGDNative::create_font_memory(const uint8_t *p_data, size_t p_size, const String &p_type, int p_base_size) { + ERR_FAIL_COND_V(interface == nullptr, RID()); + godot_rid result = interface->create_font_memory(data, p_data, p_size, (godot_string *)&p_type, p_base_size); + RID rid = *(RID *)&result; + return rid; +} + +float TextServerGDNative::font_get_height(RID p_font, int p_size) const { + ERR_FAIL_COND_V(interface == nullptr, 0.f); + return interface->font_get_height(data, (godot_rid *)&p_font, p_size); +} + +float TextServerGDNative::font_get_ascent(RID p_font, int p_size) const { + ERR_FAIL_COND_V(interface == nullptr, 0.f); + return interface->font_get_ascent(data, (godot_rid *)&p_font, p_size); +} + +float TextServerGDNative::font_get_descent(RID p_font, int p_size) const { + ERR_FAIL_COND_V(interface == nullptr, 0.f); + return interface->font_get_descent(data, (godot_rid *)&p_font, p_size); +} + +float TextServerGDNative::font_get_underline_position(RID p_font, int p_size) const { + ERR_FAIL_COND_V(interface == nullptr, 0.f); + return interface->font_get_underline_position(data, (godot_rid *)&p_font, p_size); +} + +float TextServerGDNative::font_get_underline_thickness(RID p_font, int p_size) const { + ERR_FAIL_COND_V(interface == nullptr, 0.f); + return interface->font_get_underline_thickness(data, (godot_rid *)&p_font, p_size); +} + +void TextServerGDNative::font_set_antialiased(RID p_font, bool p_antialiased) { + ERR_FAIL_COND(interface == nullptr); + interface->font_set_antialiased(data, (godot_rid *)&p_font, p_antialiased); +} + +bool TextServerGDNative::font_get_antialiased(RID p_font) const { + ERR_FAIL_COND_V(interface == nullptr, false); + return interface->font_get_antialiased(data, (godot_rid *)&p_font); +} + +void TextServerGDNative::font_set_hinting(RID p_font, TextServer::Hinting p_hinting) { + ERR_FAIL_COND(interface == nullptr); + interface->font_set_hinting(data, (godot_rid *)&p_font, (godot_int)p_hinting); +} + +TextServer::Hinting TextServerGDNative::font_get_hinting(RID p_font) const { + ERR_FAIL_COND_V(interface == nullptr, TextServer::HINTING_NONE); + return (TextServer::Hinting)interface->font_get_hinting(data, (godot_rid *)&p_font); +} + +Dictionary TextServerGDNative::font_get_feature_list(RID p_font) const { + ERR_FAIL_COND_V(interface == nullptr, Dictionary()); + godot_dictionary result = interface->font_get_feature_list(data, (godot_rid *)&p_font); + Dictionary info = *(Dictionary *)&result; + godot_dictionary_destroy(&result); + + return info; +} + +void TextServerGDNative::font_set_distance_field_hint(RID p_font, bool p_distance_field) { + ERR_FAIL_COND(interface == nullptr); + interface->font_set_distance_field_hint(data, (godot_rid *)&p_font, p_distance_field); +} + +bool TextServerGDNative::font_get_distance_field_hint(RID p_font) const { + ERR_FAIL_COND_V(interface == nullptr, false); + return interface->font_get_distance_field_hint(data, (godot_rid *)&p_font); +} + +void TextServerGDNative::font_set_force_autohinter(RID p_font, bool p_enabeld) { + ERR_FAIL_COND(interface == nullptr); + interface->font_set_force_autohinter(data, (godot_rid *)&p_font, p_enabeld); +} + +bool TextServerGDNative::font_get_force_autohinter(RID p_font) const { + ERR_FAIL_COND_V(interface == nullptr, false); + return interface->font_get_force_autohinter(data, (godot_rid *)&p_font); +} + +bool TextServerGDNative::font_has_char(RID p_font, char32_t p_char) const { + ERR_FAIL_COND_V(interface == nullptr, false); + return interface->font_has_char(data, (godot_rid *)&p_font, p_char); +} + +String TextServerGDNative::font_get_supported_chars(RID p_font) const { + ERR_FAIL_COND_V(interface == nullptr, String()); + godot_string result = interface->font_get_supported_chars(data, (godot_rid *)&p_font); + String ret = *(String *)&result; + godot_string_destroy(&result); + return ret; +} + +bool TextServerGDNative::font_has_outline(RID p_font) const { + ERR_FAIL_COND_V(interface == nullptr, false); + return interface->font_has_outline(data, (godot_rid *)&p_font); +} + +float TextServerGDNative::font_get_base_size(RID p_font) const { + ERR_FAIL_COND_V(interface == nullptr, 0.f); + return interface->font_get_base_size(data, (godot_rid *)&p_font); +} + +bool TextServerGDNative::font_is_language_supported(RID p_font, const String &p_language) const { + ERR_FAIL_COND_V(interface == nullptr, false); + return interface->font_is_language_supported(data, (godot_rid *)&p_font, (godot_string *)&p_language); +} + +void TextServerGDNative::font_set_language_support_override(RID p_font, const String &p_language, bool p_supported) { + ERR_FAIL_COND(interface == nullptr); + return interface->font_set_language_support_override(data, (godot_rid *)&p_font, (godot_string *)&p_language, p_supported); +} + +bool TextServerGDNative::font_get_language_support_override(RID p_font, const String &p_language) { + ERR_FAIL_COND_V(interface == nullptr, false); + return interface->font_get_language_support_override(data, (godot_rid *)&p_font, (godot_string *)&p_language); +} + +void TextServerGDNative::font_remove_language_support_override(RID p_font, const String &p_language) { + ERR_FAIL_COND(interface == nullptr); + interface->font_remove_language_support_override(data, (godot_rid *)&p_font, (godot_string *)&p_language); +} + +Vector<String> TextServerGDNative::font_get_language_support_overrides(RID p_font) { + ERR_FAIL_COND_V(interface == nullptr, Vector<String>()); + godot_packed_string_array result = interface->font_get_language_support_overrides(data, (godot_rid *)&p_font); + Vector<String> ret = *(Vector<String> *)&result; + godot_packed_string_array_destroy(&result); + return ret; +} + +bool TextServerGDNative::font_is_script_supported(RID p_font, const String &p_script) const { + ERR_FAIL_COND_V(interface == nullptr, false); + return interface->font_is_script_supported(data, (godot_rid *)&p_font, (godot_string *)&p_script); +} + +void TextServerGDNative::font_set_script_support_override(RID p_font, const String &p_script, bool p_supported) { + ERR_FAIL_COND(interface == nullptr); + return interface->font_set_script_support_override(data, (godot_rid *)&p_font, (godot_string *)&p_script, p_supported); +} + +bool TextServerGDNative::font_get_script_support_override(RID p_font, const String &p_script) { + ERR_FAIL_COND_V(interface == nullptr, false); + return interface->font_get_script_support_override(data, (godot_rid *)&p_font, (godot_string *)&p_script); +} + +void TextServerGDNative::font_remove_script_support_override(RID p_font, const String &p_script) { + ERR_FAIL_COND(interface == nullptr); + interface->font_remove_script_support_override(data, (godot_rid *)&p_font, (godot_string *)&p_script); +} + +Vector<String> TextServerGDNative::font_get_script_support_overrides(RID p_font) { + ERR_FAIL_COND_V(interface == nullptr, Vector<String>()); + godot_packed_string_array result = interface->font_get_script_support_overrides(data, (godot_rid *)&p_font); + Vector<String> ret = *(Vector<String> *)&result; + godot_packed_string_array_destroy(&result); + return ret; +} + +uint32_t TextServerGDNative::font_get_glyph_index(RID p_font, char32_t p_char, char32_t p_variation_selector) const { + ERR_FAIL_COND_V(interface == nullptr, 0); + return interface->font_get_glyph_index(data, (godot_rid *)&p_font, p_char, p_variation_selector); +} + +Vector2 TextServerGDNative::font_get_glyph_advance(RID p_font, uint32_t p_index, int p_size) const { + ERR_FAIL_COND_V(interface == nullptr, Vector2()); + godot_vector2 result = interface->font_get_glyph_advance(data, (godot_rid *)&p_font, p_index, p_size); + Vector2 advance = *(Vector2 *)&result; + return advance; +} + +Vector2 TextServerGDNative::font_get_glyph_kerning(RID p_font, uint32_t p_index_a, uint32_t p_index_b, int p_size) const { + ERR_FAIL_COND_V(interface == nullptr, Vector2()); + godot_vector2 result = interface->font_get_glyph_kerning(data, (godot_rid *)&p_font, p_index_a, p_index_b, p_size); + Vector2 kerning = *(Vector2 *)&result; + return kerning; +} + +Vector2 TextServerGDNative::font_draw_glyph(RID p_font, RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const { + ERR_FAIL_COND_V(interface == nullptr, Vector2()); + godot_vector2 result = interface->font_draw_glyph(data, (godot_rid *)&p_font, (godot_rid *)&p_canvas, p_size, (const godot_vector2 *)&p_pos, p_index, (const godot_color *)&p_color); + Vector2 advance = *(Vector2 *)&result; + return advance; +} + +Vector2 TextServerGDNative::font_draw_glyph_outline(RID p_font, RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const { + ERR_FAIL_COND_V(interface == nullptr, Vector2()); + godot_vector2 result = interface->font_draw_glyph_outline(data, (godot_rid *)&p_font, (godot_rid *)&p_canvas, p_size, p_outline_size, (const godot_vector2 *)&p_pos, p_index, (const godot_color *)&p_color); + Vector2 advance = *(Vector2 *)&result; + return advance; +} + +float TextServerGDNative::font_get_oversampling() const { + ERR_FAIL_COND_V(interface == nullptr, 1.f); + return interface->font_get_oversampling(data); +} + +void TextServerGDNative::font_set_oversampling(float p_oversampling) { + ERR_FAIL_COND(interface == nullptr); + return interface->font_set_oversampling(data, p_oversampling); +} + +Vector<String> TextServerGDNative::get_system_fonts() const { + ERR_FAIL_COND_V(interface == nullptr, Vector<String>()); + godot_packed_string_array result = interface->get_system_fonts(data); + Vector<String> fonts = *(Vector<String> *)&result; + godot_packed_string_array_destroy(&result); + return fonts; +} + +/*************************************************************************/ +/* Shaped text buffer interface */ +/*************************************************************************/ + +RID TextServerGDNative::create_shaped_text(TextServer::Direction p_direction, TextServer::Orientation p_orientation) { + ERR_FAIL_COND_V(interface == nullptr, RID()); + godot_rid result = interface->create_shaped_text(data, (godot_int)p_direction, (godot_int)p_orientation); + RID rid = *(RID *)&result; + return rid; +} + +void TextServerGDNative::shaped_text_clear(RID p_shaped) { + ERR_FAIL_COND(interface == nullptr); + interface->shaped_text_clear(data, (godot_rid *)&p_shaped); +} + +void TextServerGDNative::shaped_text_set_direction(RID p_shaped, TextServer::Direction p_direction) { + ERR_FAIL_COND(interface == nullptr); + interface->shaped_text_set_direction(data, (godot_rid *)&p_shaped, (godot_int)p_direction); +} + +TextServer::Direction TextServerGDNative::shaped_text_get_direction(RID p_shaped) const { + ERR_FAIL_COND_V(interface == nullptr, TextServer::DIRECTION_LTR); + return (TextServer::Direction)interface->shaped_text_get_direction(data, (godot_rid *)&p_shaped); +} + +void TextServerGDNative::shaped_text_set_orientation(RID p_shaped, TextServer::Orientation p_orientation) { + ERR_FAIL_COND(interface == nullptr); + interface->shaped_text_set_orientation(data, (godot_rid *)&p_shaped, (godot_int)p_orientation); +} + +TextServer::Orientation TextServerGDNative::shaped_text_get_orientation(RID p_shaped) const { + ERR_FAIL_COND_V(interface == nullptr, TextServer::ORIENTATION_HORIZONTAL); + return (TextServer::Orientation)interface->shaped_text_get_orientation(data, (godot_rid *)&p_shaped); +} + +void TextServerGDNative::shaped_text_set_bidi_override(RID p_shaped, const Vector<Vector2i> &p_override) { + ERR_FAIL_COND(interface == nullptr); + interface->shaped_text_set_bidi_override(data, (godot_rid *)&p_shaped, (const godot_packed_vector2i_array *)&p_override); +} + +void TextServerGDNative::shaped_text_set_preserve_invalid(RID p_shaped, bool p_enabled) { + ERR_FAIL_COND(interface == nullptr); + interface->shaped_text_set_preserve_invalid(data, (godot_rid *)&p_shaped, p_enabled); +} + +bool TextServerGDNative::shaped_text_get_preserve_invalid(RID p_shaped) const { + ERR_FAIL_COND_V(interface == nullptr, false); + return (TextServer::Orientation)interface->shaped_text_get_preserve_invalid(data, (godot_rid *)&p_shaped); +} + +void TextServerGDNative::shaped_text_set_preserve_control(RID p_shaped, bool p_enabled) { + ERR_FAIL_COND(interface == nullptr); + interface->shaped_text_set_preserve_control(data, (godot_rid *)&p_shaped, p_enabled); +} + +bool TextServerGDNative::shaped_text_get_preserve_control(RID p_shaped) const { + ERR_FAIL_COND_V(interface == nullptr, false); + return (TextServer::Orientation)interface->shaped_text_get_preserve_control(data, (godot_rid *)&p_shaped); +} + +bool TextServerGDNative::shaped_text_add_string(RID p_shaped, const String &p_text, const Vector<RID> &p_fonts, int p_size, const Dictionary &p_opentype_features, const String &p_language) { + ERR_FAIL_COND_V(interface == nullptr, false); + return interface->shaped_text_add_string(data, (godot_rid *)&p_shaped, (const godot_string *)&p_text, (const godot_rid **)p_fonts.ptr(), p_size, (const godot_dictionary *)&p_opentype_features, (const godot_string *)&p_language); +} + +bool TextServerGDNative::shaped_text_add_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align, int p_length) { + ERR_FAIL_COND_V(interface == nullptr, false); + return interface->shaped_text_add_object(data, (godot_rid *)&p_shaped, (const godot_variant *)&p_key, (const godot_vector2 *)&p_size, (godot_int)p_inline_align, p_length); +} + +bool TextServerGDNative::shaped_text_resize_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align) { + ERR_FAIL_COND_V(interface == nullptr, false); + return interface->shaped_text_resize_object(data, (godot_rid *)&p_shaped, (const godot_variant *)&p_key, (const godot_vector2 *)&p_size, (godot_int)p_inline_align); +} + +RID TextServerGDNative::shaped_text_substr(RID p_shaped, int p_start, int p_length) const { + ERR_FAIL_COND_V(interface == nullptr, RID()); + godot_rid result = interface->shaped_text_substr(data, (godot_rid *)&p_shaped, (godot_int)p_start, (godot_int)p_length); + RID rid = *(RID *)&result; + return rid; +} + +RID TextServerGDNative::shaped_text_get_parent(RID p_shaped) const { + ERR_FAIL_COND_V(interface == nullptr, RID()); + godot_rid result = interface->shaped_text_get_parent(data, (godot_rid *)&p_shaped); + RID rid = *(RID *)&result; + return rid; +} + +float TextServerGDNative::shaped_text_fit_to_width(RID p_shaped, float p_width, uint8_t p_jst_flags) { + ERR_FAIL_COND_V(interface == nullptr, 0.f); + return interface->shaped_text_fit_to_width(data, (godot_rid *)&p_shaped, p_width, p_jst_flags); +} + +float TextServerGDNative::shaped_text_tab_align(RID p_shaped, const Vector<float> &p_tab_stops) { + ERR_FAIL_COND_V(interface == nullptr, 0.f); + return interface->shaped_text_tab_align(data, (godot_rid *)&p_shaped, (godot_packed_float32_array *)&p_tab_stops); +} + +bool TextServerGDNative::shaped_text_shape(RID p_shaped) { + ERR_FAIL_COND_V(interface == nullptr, false); + return interface->shaped_text_shape(data, (godot_rid *)&p_shaped); +} + +bool TextServerGDNative::shaped_text_update_breaks(RID p_shaped) { + ERR_FAIL_COND_V(interface == nullptr, false); + return interface->shaped_text_update_breaks(data, (godot_rid *)&p_shaped); +} + +bool TextServerGDNative::shaped_text_update_justification_ops(RID p_shaped) { + ERR_FAIL_COND_V(interface == nullptr, false); + return interface->shaped_text_update_justification_ops(data, (godot_rid *)&p_shaped); +} + +bool TextServerGDNative::shaped_text_is_ready(RID p_shaped) const { + ERR_FAIL_COND_V(interface == nullptr, false); + return interface->shaped_text_is_ready(data, (godot_rid *)&p_shaped); +} + +Vector<TextServer::Glyph> TextServerGDNative::shaped_text_get_glyphs(RID p_shaped) const { + ERR_FAIL_COND_V(interface == nullptr, Vector<TextServer::Glyph>()); + godot_packed_glyph_array result = interface->shaped_text_get_glyphs(data, (godot_rid *)&p_shaped); + Vector<TextServer::Glyph> glyphs = *(Vector<TextServer::Glyph> *)&result; + godot_packed_glyph_array_destroy(&result); + return glyphs; +} + +Vector2i TextServerGDNative::shaped_text_get_range(RID p_shaped) const { + ERR_FAIL_COND_V(interface == nullptr, Vector2i()); + godot_vector2i result = interface->shaped_text_get_range(data, (godot_rid *)&p_shaped); + Vector2i range = *(Vector2i *)&result; + return range; +} + +Vector<TextServer::Glyph> TextServerGDNative::shaped_text_sort_logical(RID p_shaped) { + ERR_FAIL_COND_V(interface == nullptr, Vector<TextServer::Glyph>()); + godot_packed_glyph_array result = interface->shaped_text_sort_logical(data, (godot_rid *)&p_shaped); + Vector<TextServer::Glyph> glyphs = *(Vector<TextServer::Glyph> *)&result; + godot_packed_glyph_array_destroy(&result); + return glyphs; +} + +Vector<Vector2i> TextServerGDNative::shaped_text_get_line_breaks_adv(RID p_shaped, const Vector<float> &p_width, int p_start, bool p_once, uint8_t p_break_flags) const { + ERR_FAIL_COND_V(interface == nullptr, Vector<Vector2i>()); + if (interface->shaped_text_get_line_breaks_adv != nullptr) { + godot_packed_vector2i_array result = interface->shaped_text_get_line_breaks_adv(data, (godot_rid *)&p_shaped, (godot_packed_float32_array *)&p_width, p_start, p_once, p_break_flags); + Vector<Vector2i> breaks = *(Vector<Vector2i> *)&result; + godot_packed_vector2i_array_destroy(&result); + return breaks; + } else { + return TextServer::shaped_text_get_line_breaks_adv(p_shaped, p_width, p_break_flags); + } +} + +Vector<Vector2i> TextServerGDNative::shaped_text_get_line_breaks(RID p_shaped, float p_width, int p_start, uint8_t p_break_flags) const { + ERR_FAIL_COND_V(interface == nullptr, Vector<Vector2i>()); + if (interface->shaped_text_get_line_breaks != nullptr) { + godot_packed_vector2i_array result = interface->shaped_text_get_line_breaks(data, (godot_rid *)&p_shaped, p_width, p_start, p_break_flags); + Vector<Vector2i> breaks = *(Vector<Vector2i> *)&result; + godot_packed_vector2i_array_destroy(&result); + return breaks; + } else { + return TextServer::shaped_text_get_line_breaks(p_shaped, p_width, p_break_flags); + } +} + +Vector<Vector2i> TextServerGDNative::shaped_text_get_word_breaks(RID p_shaped) const { + ERR_FAIL_COND_V(interface == nullptr, Vector<Vector2i>()); + if (interface->shaped_text_get_word_breaks != nullptr) { + godot_packed_vector2i_array result = interface->shaped_text_get_word_breaks(data, (godot_rid *)&p_shaped); + Vector<Vector2i> breaks = *(Vector<Vector2i> *)&result; + godot_packed_vector2i_array_destroy(&result); + return breaks; + } else { + return TextServer::shaped_text_get_word_breaks(p_shaped); + } +} + +Array TextServerGDNative::shaped_text_get_objects(RID p_shaped) const { + ERR_FAIL_COND_V(interface == nullptr, Array()); + godot_array result = interface->shaped_text_get_objects(data, (godot_rid *)&p_shaped); + Array rect = *(Array *)&result; + return rect; +} + +Rect2 TextServerGDNative::shaped_text_get_object_rect(RID p_shaped, Variant p_key) const { + ERR_FAIL_COND_V(interface == nullptr, Rect2()); + godot_rect2 result = interface->shaped_text_get_object_rect(data, (godot_rid *)&p_shaped, (const godot_variant *)&p_key); + Rect2 rect = *(Rect2 *)&result; + return rect; +} + +Size2 TextServerGDNative::shaped_text_get_size(RID p_shaped) const { + ERR_FAIL_COND_V(interface == nullptr, Size2()); + godot_vector2 result = interface->shaped_text_get_size(data, (godot_rid *)&p_shaped); + Size2 size = *(Size2 *)&result; + return size; +} + +float TextServerGDNative::shaped_text_get_ascent(RID p_shaped) const { + ERR_FAIL_COND_V(interface == nullptr, 0.f); + return interface->shaped_text_get_ascent(data, (godot_rid *)&p_shaped); +} + +float TextServerGDNative::shaped_text_get_descent(RID p_shaped) const { + ERR_FAIL_COND_V(interface == nullptr, 0.f); + return interface->shaped_text_get_descent(data, (godot_rid *)&p_shaped); +} + +float TextServerGDNative::shaped_text_get_width(RID p_shaped) const { + ERR_FAIL_COND_V(interface == nullptr, 0.f); + return interface->shaped_text_get_width(data, (godot_rid *)&p_shaped); +} + +float TextServerGDNative::shaped_text_get_underline_position(RID p_shaped) const { + ERR_FAIL_COND_V(interface == nullptr, 0.f); + return interface->shaped_text_get_underline_position(data, (godot_rid *)&p_shaped); +} + +float TextServerGDNative::shaped_text_get_underline_thickness(RID p_shaped) const { + ERR_FAIL_COND_V(interface == nullptr, 0.f); + return interface->shaped_text_get_underline_thickness(data, (godot_rid *)&p_shaped); +} + +String TextServerGDNative::format_number(const String &p_string, const String &p_language) const { + ERR_FAIL_COND_V(interface == nullptr, String()); + godot_string result = interface->format_number(data, (const godot_string *)&p_string, (const godot_string *)&p_language); + if (interface->format_number == nullptr) { + return p_string; + } + String ret = *(String *)&result; + godot_string_destroy(&result); + return ret; +} + +String TextServerGDNative::parse_number(const String &p_string, const String &p_language) const { + ERR_FAIL_COND_V(interface == nullptr, String()); + if (interface->parse_number == nullptr) { + return p_string; + } + godot_string result = interface->parse_number(data, (const godot_string *)&p_string, (const godot_string *)&p_language); + String ret = *(String *)&result; + godot_string_destroy(&result); + return ret; +} + +String TextServerGDNative::percent_sign(const String &p_language) const { + ERR_FAIL_COND_V(interface == nullptr, String()); + if (interface->percent_sign == nullptr) { + return "%"; + } + godot_string result = interface->percent_sign(data, (const godot_string *)&p_language); + String ret = *(String *)&result; + godot_string_destroy(&result); + return ret; +} + +TextServer *TextServerGDNative::create_func(Error &r_error, void *p_user_data) { + const godot_text_interface_gdnative *interface = (const godot_text_interface_gdnative *)p_user_data; + r_error = OK; + + TextServerGDNative *server = memnew(TextServerGDNative()); + server->interface = interface; + server->data = interface->constructor((godot_object *)server); + + return server; +} + +TextServerGDNative::TextServerGDNative() { + data = nullptr; + interface = nullptr; +} + +TextServerGDNative::~TextServerGDNative() { + if (interface != nullptr) { + interface->destructor(data); + data = nullptr; + interface = nullptr; + } +} + +/*************************************************************************/ +/* GDNative functions */ +/*************************************************************************/ + +#ifdef __cplusplus +extern "C" { +#endif + +static_assert(sizeof(godot_glyph) == sizeof(TextServer::Glyph), "Glyph size mismatch"); +static_assert(sizeof(godot_packed_glyph_array) == sizeof(Vector<TextServer::Glyph>), "Vector<Glyph> size mismatch"); + +void GDAPI godot_text_register_interface(const godot_text_interface_gdnative *p_interface, const godot_string *p_name, uint32_t p_features) { + ERR_FAIL_COND(p_interface->version.major != 1); + String name = *(String *)p_name; + TextServerManager::register_create_function(name + "(GDNative)", p_features, TextServerGDNative::create_func, (void *)p_interface); +} + +// Glyph + +void GDAPI godot_glyph_new(godot_glyph *r_dest) { + TextServer::Glyph *dest = (TextServer::Glyph *)r_dest; + *dest = TextServer::Glyph(); +} + +godot_vector2i GDAPI godot_glyph_get_range(const godot_glyph *p_self) { + godot_vector2i dest; + Vector2i *d = (Vector2i *)&dest; + const TextServer::Glyph *self = (const TextServer::Glyph *)p_self; + d->x = self->start; + d->y = self->end; + return dest; +} + +void GDAPI godot_glyph_set_range(godot_glyph *p_self, const godot_vector2i *p_range) { + TextServer::Glyph *self = (TextServer::Glyph *)p_self; + const Vector2i *range = (const Vector2i *)p_range; + self->start = range->x; + self->end = range->y; +} + +godot_int GDAPI godot_glyph_get_count(const godot_glyph *p_self) { + const TextServer::Glyph *self = (const TextServer::Glyph *)p_self; + return self->count; +} + +void GDAPI godot_glyph_set_count(godot_glyph *p_self, godot_int p_count) { + TextServer::Glyph *self = (TextServer::Glyph *)p_self; + self->count = p_count; +} + +godot_int GDAPI godot_glyph_get_repeat(const godot_glyph *p_self) { + const TextServer::Glyph *self = (const TextServer::Glyph *)p_self; + return self->repeat; +} + +void GDAPI godot_glyph_set_repeat(godot_glyph *p_self, godot_int p_repeat) { + TextServer::Glyph *self = (TextServer::Glyph *)p_self; + self->repeat = p_repeat; +} + +godot_int GDAPI godot_glyph_get_flags(const godot_glyph *p_self) { + const TextServer::Glyph *self = (const TextServer::Glyph *)p_self; + return self->flags; +} + +void GDAPI godot_glyph_set_flags(godot_glyph *p_self, godot_int p_flags) { + TextServer::Glyph *self = (TextServer::Glyph *)p_self; + self->flags = p_flags; +} + +godot_vector2 GDAPI godot_glyph_get_offset(const godot_glyph *p_self) { + godot_vector2 dest; + Vector2 *d = (Vector2 *)&dest; + const TextServer::Glyph *self = (const TextServer::Glyph *)p_self; + d->x = self->x_off; + d->y = self->y_off; + return dest; +} + +void GDAPI godot_glyph_set_offset(godot_glyph *p_self, const godot_vector2 *p_offset) { + TextServer::Glyph *self = (TextServer::Glyph *)p_self; + const Vector2 *offset = (const Vector2 *)p_offset; + self->x_off = offset->x; + self->y_off = offset->y; +} + +godot_real GDAPI godot_glyph_get_advance(const godot_glyph *p_self) { + const TextServer::Glyph *self = (const TextServer::Glyph *)p_self; + return self->advance; +} + +void GDAPI godot_glyph_set_advance(godot_glyph *p_self, godot_real p_advance) { + TextServer::Glyph *self = (TextServer::Glyph *)p_self; + self->advance = p_advance; +} + +godot_rid GDAPI godot_glyph_get_font(const godot_glyph *p_self) { + godot_rid dest; + RID *d = (RID *)&dest; + const TextServer::Glyph *self = (const TextServer::Glyph *)p_self; + *d = self->font_rid; + return dest; +} + +void GDAPI godot_glyph_set_font(godot_glyph *p_self, godot_rid *p_font) { + TextServer::Glyph *self = (TextServer::Glyph *)p_self; + const RID *font = (const RID *)p_font; + self->font_rid = *font; +} + +godot_int GDAPI godot_glyph_get_font_size(const godot_glyph *p_self) { + const TextServer::Glyph *self = (const TextServer::Glyph *)p_self; + return self->font_size; +} + +void GDAPI godot_glyph_set_font_size(godot_glyph *p_self, godot_int p_size) { + TextServer::Glyph *self = (TextServer::Glyph *)p_self; + self->font_size = p_size; +} + +godot_int GDAPI godot_glyph_get_index(const godot_glyph *p_self) { + const TextServer::Glyph *self = (const TextServer::Glyph *)p_self; + return self->index; +} + +void GDAPI godot_glyph_set_index(godot_glyph *p_self, godot_int p_index) { + TextServer::Glyph *self = (TextServer::Glyph *)p_self; + self->index = p_index; +} + +// GlyphArray + +void GDAPI godot_packed_glyph_array_new(godot_packed_glyph_array *r_dest) { + Vector<TextServer::Glyph> *dest = (Vector<TextServer::Glyph> *)r_dest; + memnew_placement(dest, Vector<TextServer::Glyph>); +} + +void GDAPI godot_packed_glyph_array_new_copy(godot_packed_glyph_array *r_dest, const godot_packed_glyph_array *p_src) { + Vector<TextServer::Glyph> *dest = (Vector<TextServer::Glyph> *)r_dest; + const Vector<TextServer::Glyph> *src = (const Vector<TextServer::Glyph> *)p_src; + memnew_placement(dest, Vector<TextServer::Glyph>(*src)); +} + +const godot_glyph GDAPI *godot_packed_glyph_array_ptr(const godot_packed_glyph_array *p_self) { + const Vector<TextServer::Glyph> *self = (const Vector<TextServer::Glyph> *)p_self; + return (const godot_glyph *)self->ptr(); +} + +godot_glyph GDAPI *godot_packed_glyph_array_ptrw(godot_packed_glyph_array *p_self) { + Vector<TextServer::Glyph> *self = (Vector<TextServer::Glyph> *)p_self; + return (godot_glyph *)self->ptrw(); +} + +void GDAPI godot_packed_glyph_array_append(godot_packed_glyph_array *p_self, const godot_glyph *p_data) { + Vector<TextServer::Glyph> *self = (Vector<TextServer::Glyph> *)p_self; + TextServer::Glyph &s = *(TextServer::Glyph *)p_data; + self->push_back(s); +} + +void GDAPI godot_packed_glyph_array_append_array(godot_packed_glyph_array *p_self, const godot_packed_glyph_array *p_array) { + Vector<TextServer::Glyph> *self = (Vector<TextServer::Glyph> *)p_self; + Vector<TextServer::Glyph> *array = (Vector<TextServer::Glyph> *)p_array; + self->append_array(*array); +} + +godot_error GDAPI godot_packed_glyph_array_insert(godot_packed_glyph_array *p_self, const godot_int p_idx, const godot_glyph *p_data) { + Vector<TextServer::Glyph> *self = (Vector<TextServer::Glyph> *)p_self; + TextServer::Glyph &s = *(TextServer::Glyph *)p_data; + return (godot_error)self->insert(p_idx, s); +} + +godot_bool GDAPI godot_packed_glyph_array_has(godot_packed_glyph_array *p_self, const godot_glyph *p_value) { + Vector<TextServer::Glyph> *self = (Vector<TextServer::Glyph> *)p_self; + TextServer::Glyph &v = *(TextServer::Glyph *)p_value; + return (godot_bool)self->has(v); +} + +void GDAPI godot_packed_glyph_array_sort(godot_packed_glyph_array *p_self) { + Vector<TextServer::Glyph> *self = (Vector<TextServer::Glyph> *)p_self; + self->sort(); +} + +void GDAPI godot_packed_glyph_array_invert(godot_packed_glyph_array *p_self) { + Vector<TextServer::Glyph> *self = (Vector<TextServer::Glyph> *)p_self; + self->invert(); +} + +void GDAPI godot_packed_glyph_array_push_back(godot_packed_glyph_array *p_self, const godot_glyph *p_data) { + Vector<TextServer::Glyph> *self = (Vector<TextServer::Glyph> *)p_self; + TextServer::Glyph &s = *(TextServer::Glyph *)p_data; + self->push_back(s); +} + +void GDAPI godot_packed_glyph_array_remove(godot_packed_glyph_array *p_self, const godot_int p_idx) { + Vector<TextServer::Glyph> *self = (Vector<TextServer::Glyph> *)p_self; + self->remove(p_idx); +} + +void GDAPI godot_packed_glyph_array_resize(godot_packed_glyph_array *p_self, const godot_int p_size) { + Vector<TextServer::Glyph> *self = (Vector<TextServer::Glyph> *)p_self; + self->resize(p_size); +} + +void GDAPI godot_packed_glyph_array_set(godot_packed_glyph_array *p_self, const godot_int p_idx, const godot_glyph *p_data) { + Vector<TextServer::Glyph> *self = (Vector<TextServer::Glyph> *)p_self; + TextServer::Glyph &s = *(TextServer::Glyph *)p_data; + self->set(p_idx, s); +} + +godot_glyph GDAPI godot_packed_glyph_array_get(const godot_packed_glyph_array *p_self, const godot_int p_idx) { + const Vector<TextServer::Glyph> *self = (const Vector<TextServer::Glyph> *)p_self; + godot_glyph v; + TextServer::Glyph *s = (TextServer::Glyph *)&v; + *s = self->get(p_idx); + return v; +} + +godot_int GDAPI godot_packed_glyph_array_size(const godot_packed_glyph_array *p_self) { + const Vector<TextServer::Glyph> *self = (const Vector<TextServer::Glyph> *)p_self; + return self->size(); +} + +godot_bool GDAPI godot_packed_glyph_array_empty(const godot_packed_glyph_array *p_self) { + const Vector<TextServer::Glyph> *self = (const Vector<TextServer::Glyph> *)p_self; + return self->empty(); +} + +void GDAPI godot_packed_glyph_array_destroy(godot_packed_glyph_array *p_self) { + ((Vector<TextServer::Glyph> *)p_self)->~Vector(); +} + +#ifdef __cplusplus +} +#endif diff --git a/modules/gdnative/text/text_server_gdnative.h b/modules/gdnative/text/text_server_gdnative.h new file mode 100644 index 0000000000..0196120c00 --- /dev/null +++ b/modules/gdnative/text/text_server_gdnative.h @@ -0,0 +1,183 @@ +/*************************************************************************/ +/* text_server_gdnative.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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. */ +/*************************************************************************/ + +#ifndef TEXT_SERVER_GDNATIVE_H +#define TEXT_SERVER_GDNATIVE_H + +#include "modules/gdnative/gdnative.h" + +#include "servers/text_server.h" + +class TextServerGDNative : public TextServer { + GDCLASS(TextServerGDNative, TextServer); + + const godot_text_interface_gdnative *interface = nullptr; + void *data = nullptr; + +protected: + static void _bind_methods(){}; + +public: + virtual bool has_feature(Feature p_feature) override; + virtual String get_name() const override; + + virtual void free(RID p_rid) override; + virtual bool has(RID p_rid) override; + virtual bool load_support_data(const String &p_filename) override; + +#ifdef TOOLS_ENABLED + virtual String get_support_data_filename() override; + virtual String get_support_data_info() override; + virtual bool save_support_data(const String &p_filename) override; +#endif + + virtual bool is_locale_right_to_left(const String &p_locale) override; + + /* Font interface */ + virtual RID create_font_system(const String &p_name, int p_base_size = 16) override; + virtual RID create_font_resource(const String &p_filename, int p_base_size = 16) override; + virtual RID create_font_memory(const uint8_t *p_data, size_t p_size, const String &p_type, int p_base_size = 16) override; + + virtual float font_get_height(RID p_font, int p_size) const override; + virtual float font_get_ascent(RID p_font, int p_size) const override; + virtual float font_get_descent(RID p_font, int p_size) const override; + + virtual float font_get_underline_position(RID p_font, int p_size) const override; + virtual float font_get_underline_thickness(RID p_font, int p_size) const override; + + virtual void font_set_antialiased(RID p_font, bool p_antialiased) override; + virtual bool font_get_antialiased(RID p_font) const override; + + virtual Dictionary font_get_feature_list(RID p_font) const override; + + virtual void font_set_hinting(RID p_font, Hinting p_hinting) override; + virtual Hinting font_get_hinting(RID p_font) const override; + + virtual void font_set_distance_field_hint(RID p_font, bool p_distance_field) override; + virtual bool font_get_distance_field_hint(RID p_font) const override; + + virtual void font_set_force_autohinter(RID p_font, bool p_enabeld) override; + virtual bool font_get_force_autohinter(RID p_font) const override; + + virtual bool font_has_char(RID p_font, char32_t p_char) const override; + virtual String font_get_supported_chars(RID p_font) const override; + + virtual bool font_has_outline(RID p_font) const override; + virtual float font_get_base_size(RID p_font) const override; + + virtual bool font_is_language_supported(RID p_font, const String &p_language) const override; + virtual void font_set_language_support_override(RID p_font, const String &p_language, bool p_supported) override; + virtual bool font_get_language_support_override(RID p_font, const String &p_language) override; + virtual void font_remove_language_support_override(RID p_font, const String &p_language) override; + Vector<String> font_get_language_support_overrides(RID p_font) override; + + virtual bool font_is_script_supported(RID p_font, const String &p_script) const override; + virtual void font_set_script_support_override(RID p_font, const String &p_script, bool p_supported) override; + virtual bool font_get_script_support_override(RID p_font, const String &p_script) override; + virtual void font_remove_script_support_override(RID p_font, const String &p_script) override; + Vector<String> font_get_script_support_overrides(RID p_font) override; + + virtual uint32_t font_get_glyph_index(RID p_font, char32_t p_char, char32_t p_variation_selector = 0x0000) const override; + virtual Vector2 font_get_glyph_advance(RID p_font, uint32_t p_index, int p_size) const override; + virtual Vector2 font_get_glyph_kerning(RID p_font, uint32_t p_index_a, uint32_t p_index_b, int p_size) const override; + + virtual Vector2 font_draw_glyph(RID p_font, RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color = Color(1, 1, 1)) const override; + virtual Vector2 font_draw_glyph_outline(RID p_font, RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color = Color(1, 1, 1)) const override; + + virtual float font_get_oversampling() const override; + virtual void font_set_oversampling(float p_oversampling) override; + + virtual Vector<String> get_system_fonts() const override; + + /* Shaped text buffer interface */ + + virtual RID create_shaped_text(Direction p_direction = DIRECTION_AUTO, Orientation p_orientation = ORIENTATION_HORIZONTAL) override; + + virtual void shaped_text_clear(RID p_shaped) override; + + virtual void shaped_text_set_direction(RID p_shaped, Direction p_direction = DIRECTION_AUTO) override; + virtual Direction shaped_text_get_direction(RID p_shaped) const override; + + virtual void shaped_text_set_bidi_override(RID p_shaped, const Vector<Vector2i> &p_override) override; + + virtual void shaped_text_set_orientation(RID p_shaped, Orientation p_orientation = ORIENTATION_HORIZONTAL) override; + virtual Orientation shaped_text_get_orientation(RID p_shaped) const override; + + virtual void shaped_text_set_preserve_invalid(RID p_shaped, bool p_enabled) override; + virtual bool shaped_text_get_preserve_invalid(RID p_shaped) const override; + + virtual void shaped_text_set_preserve_control(RID p_shaped, bool p_enabled) override; + virtual bool shaped_text_get_preserve_control(RID p_shaped) const override; + + virtual bool shaped_text_add_string(RID p_shaped, const String &p_text, const Vector<RID> &p_fonts, int p_size, const Dictionary &p_opentype_features = Dictionary(), const String &p_language = "") override; + virtual bool shaped_text_add_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align = VALIGN_CENTER, int p_length = 1) override; + virtual bool shaped_text_resize_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align = VALIGN_CENTER) override; + + virtual RID shaped_text_substr(RID p_shaped, int p_start, int p_length) const override; + virtual RID shaped_text_get_parent(RID p_shaped) const override; + + virtual float shaped_text_fit_to_width(RID p_shaped, float p_width, uint8_t /*JustificationFlag*/ p_jst_flags = JUSTIFICATION_WORD_BOUND | JUSTIFICATION_KASHIDA) override; + virtual float shaped_text_tab_align(RID p_shaped, const Vector<float> &p_tab_stops) override; + + virtual bool shaped_text_shape(RID p_shaped) override; + virtual bool shaped_text_update_breaks(RID p_shaped) override; + virtual bool shaped_text_update_justification_ops(RID p_shaped) override; + + virtual bool shaped_text_is_ready(RID p_shaped) const override; + + virtual Vector<Glyph> shaped_text_get_glyphs(RID p_shaped) const override; + + virtual Vector2i shaped_text_get_range(RID p_shaped) const override; + + virtual Vector<Glyph> shaped_text_sort_logical(RID p_shaped) override; + virtual Vector<Vector2i> shaped_text_get_line_breaks_adv(RID p_shaped, const Vector<float> &p_width, int p_start = 0, bool p_once = true, uint8_t /*TextBreakFlag*/ p_break_flags = BREAK_MANDATORY | BREAK_WORD_BOUND) const override; + virtual Vector<Vector2i> shaped_text_get_line_breaks(RID p_shaped, float p_width, int p_start = 0, uint8_t p_break_flags = BREAK_MANDATORY | BREAK_WORD_BOUND) const override; + virtual Vector<Vector2i> shaped_text_get_word_breaks(RID p_shaped) const override; + virtual Array shaped_text_get_objects(RID p_shaped) const override; + virtual Rect2 shaped_text_get_object_rect(RID p_shaped, Variant p_key) const override; + + virtual Size2 shaped_text_get_size(RID p_shaped) const override; + virtual float shaped_text_get_ascent(RID p_shaped) const override; + virtual float shaped_text_get_descent(RID p_shaped) const override; + virtual float shaped_text_get_width(RID p_shaped) const override; + virtual float shaped_text_get_underline_position(RID p_shaped) const override; + virtual float shaped_text_get_underline_thickness(RID p_shaped) const override; + + virtual String format_number(const String &p_string, const String &p_language = "") const override; + virtual String parse_number(const String &p_string, const String &p_language = "") const override; + virtual String percent_sign(const String &p_language = "") const override; + + static TextServer *create_func(Error &r_error, void *p_user_data); + + TextServerGDNative(); + ~TextServerGDNative(); +}; + +#endif // TEXT_SERVER_GDNATIVE_H diff --git a/modules/gdscript/config.py b/modules/gdscript/config.py index 6fc227e7f5..61ce6185a5 100644 --- a/modules/gdscript/config.py +++ b/modules/gdscript/config.py @@ -10,7 +10,6 @@ def get_doc_classes(): return [ "@GDScript", "GDScript", - "GDScriptFunctionState", ] diff --git a/modules/gdscript/doc_classes/GDScriptFunctionState.xml b/modules/gdscript/doc_classes/GDScriptFunctionState.xml deleted file mode 100644 index 5e369b32d9..0000000000 --- a/modules/gdscript/doc_classes/GDScriptFunctionState.xml +++ /dev/null @@ -1,45 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" ?> -<class name="GDScriptFunctionState" inherits="Reference" version="4.0"> - <brief_description> - State of a function call after yielding. - </brief_description> - <description> - FIXME: Outdated docs as of GDScript rewrite in 4.0. - Calling [code]yield[/code] within a function will cause that function to yield and return its current state as an object of this type. The yielded function call can then be resumed later by calling [method resume] on this state object. - </description> - <tutorials> - </tutorials> - <methods> - <method name="is_valid" qualifiers="const"> - <return type="bool"> - </return> - <argument index="0" name="extended_check" type="bool" default="false"> - </argument> - <description> - Check whether the function call may be resumed. This is not the case if the function state was already resumed. - If [code]extended_check[/code] is enabled, it also checks if the associated script and object still exist. The extended check is done in debug mode as part of [method GDScriptFunctionState.resume], but you can use this if you know you may be trying to resume without knowing for sure the object and/or script have survived up to that point. - </description> - </method> - <method name="resume"> - <return type="Variant"> - </return> - <argument index="0" name="arg" type="Variant" default="null"> - </argument> - <description> - Resume execution of the yielded function call. - If handed an argument, return the argument from the [code]yield[/code] call in the yielded function call. You can pass e.g. an [Array] to hand multiple arguments. - This function returns what the resumed function call returns, possibly another function state if yielded again. - </description> - </method> - </methods> - <signals> - <signal name="completed"> - <argument index="0" name="result" type="Variant"> - </argument> - <description> - </description> - </signal> - </signals> - <constants> - </constants> -</class> diff --git a/modules/gdscript/gdscript.cpp b/modules/gdscript/gdscript.cpp index 53602f7a9b..6b74abf15d 100644 --- a/modules/gdscript/gdscript.cpp +++ b/modules/gdscript/gdscript.cpp @@ -628,8 +628,12 @@ Error GDScript::reload(bool p_keep_state) { if (EngineDebugger::is_active()) { GDScriptLanguage::get_singleton()->debug_break_parse(get_path(), parser.get_errors().front()->get().line, "Parser Error: " + parser.get_errors().front()->get().message); } - // TODO: Show all error messages. - _err_print_error("GDScript::reload", path.empty() ? "built-in" : (const char *)path.utf8().get_data(), parser.get_errors().front()->get().line, ("Parse Error: " + parser.get_errors().front()->get().message).utf8().get_data(), ERR_HANDLER_SCRIPT); + + const List<GDScriptParser::ParserError>::Element *e = parser.get_errors().front(); + while (e != nullptr) { + _err_print_error("GDScript::reload", path.empty() ? "built-in" : (const char *)path.utf8().get_data(), e->get().line, ("Parse Error: " + e->get().message).utf8().get_data(), ERR_HANDLER_SCRIPT); + e = e->next(); + } ERR_FAIL_V(ERR_PARSE_ERROR); } diff --git a/modules/gdscript/gdscript_analyzer.cpp b/modules/gdscript/gdscript_analyzer.cpp index 6b23ab1616..aa2fa67ef2 100644 --- a/modules/gdscript/gdscript_analyzer.cpp +++ b/modules/gdscript/gdscript_analyzer.cpp @@ -978,17 +978,19 @@ void GDScriptAnalyzer::resolve_for(GDScriptParser::ForNode *p_for) { if (!call->arguments[i]->is_constant) { all_is_constant = false; - } else { + } else if (all_is_constant) { args.write[i] = call->arguments[i]->reduced_value; } GDScriptParser::DataType arg_type = call->arguments[i]->get_datatype(); - if (arg_type.kind != GDScriptParser::DataType::BUILTIN) { - all_is_constant = false; - push_error(vformat(R"*(Invalid argument for "range()" call. Argument %d should be int or float but "%s" was given.)*", i + 1, arg_type.to_string()), call->arguments[i]); - } else if (arg_type.builtin_type != Variant::INT && arg_type.builtin_type != Variant::FLOAT) { - all_is_constant = false; - push_error(vformat(R"*(Invalid argument for "range()" call. Argument %d should be int or float but "%s" was given.)*", i + 1, arg_type.to_string()), call->arguments[i]); + if (!arg_type.is_variant()) { + if (arg_type.kind != GDScriptParser::DataType::BUILTIN) { + all_is_constant = false; + push_error(vformat(R"*(Invalid argument for "range()" call. Argument %d should be int or float but "%s" was given.)*", i + 1, arg_type.to_string()), call->arguments[i]); + } else if (arg_type.builtin_type != Variant::INT && arg_type.builtin_type != Variant::FLOAT) { + all_is_constant = false; + push_error(vformat(R"*(Invalid argument for "range()" call. Argument %d should be int or float but "%s" was given.)*", i + 1, arg_type.to_string()), call->arguments[i]); + } } } @@ -1011,11 +1013,15 @@ void GDScriptAnalyzer::resolve_for(GDScriptParser::ForNode *p_for) { } } - GDScriptParser::DataType list_type; - list_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; - list_type.kind = GDScriptParser::DataType::BUILTIN; - list_type.builtin_type = Variant::ARRAY; - p_for->list->set_datatype(list_type); + if (p_for->list->is_constant) { + p_for->list->set_datatype(type_from_variant(p_for->list->reduced_value, p_for->list)); + } else { + GDScriptParser::DataType list_type; + list_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; + list_type.kind = GDScriptParser::DataType::BUILTIN; + list_type.builtin_type = Variant::ARRAY; + p_for->list->set_datatype(list_type); + } } } } @@ -1703,7 +1709,27 @@ void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool is_awa call_type.native_type = function_name; // "Object". } - if (all_is_constant) { + bool safe_to_fold = true; + switch (builtin_type) { + // Those are stored by reference so not suited for compile-time construction. + // Because in this case they would be the same reference in all constructed values. + case Variant::OBJECT: + case Variant::PACKED_BYTE_ARRAY: + case Variant::PACKED_INT32_ARRAY: + case Variant::PACKED_INT64_ARRAY: + case Variant::PACKED_FLOAT32_ARRAY: + case Variant::PACKED_FLOAT64_ARRAY: + case Variant::PACKED_STRING_ARRAY: + case Variant::PACKED_VECTOR2_ARRAY: + case Variant::PACKED_VECTOR3_ARRAY: + case Variant::PACKED_COLOR_ARRAY: + safe_to_fold = false; + break; + default: + break; + } + + if (all_is_constant && safe_to_fold) { // Construct here. Vector<const Variant *> args; for (int i = 0; i < p_call->arguments.size(); i++) { @@ -2025,9 +2051,17 @@ void GDScriptAnalyzer::reduce_get_node(GDScriptParser::GetNodeNode *p_get_node) p_get_node->set_datatype(result); } -GDScriptParser::DataType GDScriptAnalyzer::make_global_class_meta_type(const StringName &p_class_name) { +GDScriptParser::DataType GDScriptAnalyzer::make_global_class_meta_type(const StringName &p_class_name, const GDScriptParser::Node *p_source) { Ref<GDScriptParserRef> ref = get_parser_for(ScriptServer::get_global_class_path(p_class_name)); - ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED); + Error err = ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED); + + if (err) { + push_error(vformat(R"(Could not resolve class "%s", because of a parser error.)", p_class_name), p_source); + GDScriptParser::DataType type; + type.type_source = GDScriptParser::DataType::UNDETECTED; + type.kind = GDScriptParser::DataType::VARIANT; + return type; + } GDScriptParser::DataType type; type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; @@ -2299,7 +2333,7 @@ void GDScriptAnalyzer::reduce_identifier(GDScriptParser::IdentifierNode *p_ident } if (ScriptServer::is_global_class(name)) { - p_identifier->set_datatype(make_global_class_meta_type(name)); + p_identifier->set_datatype(make_global_class_meta_type(name, p_identifier)); return; } @@ -2716,7 +2750,7 @@ void GDScriptAnalyzer::reduce_unary_op(GDScriptParser::UnaryOpNode *p_unary_op) mark_node_unsafe(p_unary_op); } else { bool valid = false; - result = get_operation_type(p_unary_op->variant_op, p_unary_op->operand->get_datatype(), p_unary_op->operand->get_datatype(), valid, p_unary_op); + result = get_operation_type(p_unary_op->variant_op, p_unary_op->operand->get_datatype(), valid, p_unary_op); if (!valid) { push_error(vformat(R"(Invalid operand of type "%s" for unary operator "%s".)", p_unary_op->operand->get_datatype().to_string(), Variant::get_operator_name(p_unary_op->variant_op)), p_unary_op->operand); @@ -3082,81 +3116,31 @@ bool GDScriptAnalyzer::is_shadowing(GDScriptParser::IdentifierNode *p_local, con } #endif -GDScriptParser::DataType GDScriptAnalyzer::get_operation_type(Variant::Operator p_operation, const GDScriptParser::DataType &p_a, const GDScriptParser::DataType &p_b, bool &r_valid, const GDScriptParser::Node *p_source) { - // This function creates dummy variant values and apply the operation to those. Less error-prone than keeping a table of valid operations. +GDScriptParser::DataType GDScriptAnalyzer::get_operation_type(Variant::Operator p_operation, const GDScriptParser::DataType &p_a, bool &r_valid, const GDScriptParser::Node *p_source) { + // Unary version. + GDScriptParser::DataType nil_type; + nil_type.builtin_type = Variant::NIL; + return get_operation_type(p_operation, p_a, nil_type, r_valid, p_source); +} +GDScriptParser::DataType GDScriptAnalyzer::get_operation_type(Variant::Operator p_operation, const GDScriptParser::DataType &p_a, const GDScriptParser::DataType &p_b, bool &r_valid, const GDScriptParser::Node *p_source) { GDScriptParser::DataType result; result.kind = GDScriptParser::DataType::VARIANT; Variant::Type a_type = p_a.builtin_type; Variant::Type b_type = p_b.builtin_type; - Variant a; - REF a_ref; - if (a_type == Variant::OBJECT) { - a_ref.instance(); - a = a_ref; - } else { - Callable::CallError err; - Variant::construct(a_type, a, nullptr, 0, err); - if (err.error != Callable::CallError::CALL_OK) { - r_valid = false; - ERR_FAIL_V_MSG(result, vformat("Could not construct value of type %s", Variant::get_type_name(a_type))); - } - } - Variant b; - REF b_ref; - if (b_type == Variant::OBJECT) { - b_ref.instance(); - b = b_ref; - } else { - Callable::CallError err; - Variant::construct(b_type, b, nullptr, 0, err); - if (err.error != Callable::CallError::CALL_OK) { - r_valid = false; - ERR_FAIL_V_MSG(result, vformat("Could not construct value of type %s", Variant::get_type_name(b_type))); - } - } - - // Avoid division by zero. - switch (b_type) { - case Variant::INT: - b = 1; - break; - case Variant::FLOAT: - b = 1.0; - break; - case Variant::VECTOR2: - b = Vector2(1.0, 1.0); - break; - case Variant::VECTOR2I: - b = Vector2i(1, 1); - break; - case Variant::VECTOR3: - b = Vector3(1.0, 1.0, 1.0); - break; - case Variant::VECTOR3I: - b = Vector3i(1, 1, 1); - break; - case Variant::COLOR: - b = Color(1.0, 1.0, 1.0, 1.0); - break; - default: - // No change needed. - break; - } + Variant::ValidatedOperatorEvaluator op_eval = Variant::get_validated_operator_evaluator(p_operation, a_type, b_type); - // Avoid error in formatting operator (%) where it doesn't find a placeholder. - if (a_type == Variant::STRING && b_type != Variant::ARRAY) { - a = String("%s"); + if (op_eval == nullptr) { + r_valid = false; + return result; } - Variant ret; - Variant::evaluate(p_operation, a, b, ret, r_valid); + r_valid = true; - if (r_valid) { - return type_from_variant(ret, p_source); - } + result.kind = GDScriptParser::DataType::BUILTIN; + result.builtin_type = Variant::get_operator_return_type(p_operation, a_type, b_type); return result; } @@ -3358,7 +3342,6 @@ Error GDScriptAnalyzer::resolve_program() { } depended_parsers[E->get()]->raise_status(GDScriptParserRef::FULLY_SOLVED); } - depended_parsers.clear(); return parser->errors.empty() ? OK : ERR_PARSE_ERROR; } diff --git a/modules/gdscript/gdscript_analyzer.h b/modules/gdscript/gdscript_analyzer.h index 0a952cc621..9925167856 100644 --- a/modules/gdscript/gdscript_analyzer.h +++ b/modules/gdscript/gdscript_analyzer.h @@ -96,12 +96,13 @@ class GDScriptAnalyzer { GDScriptParser::DataType type_from_variant(const Variant &p_value, const GDScriptParser::Node *p_source); GDScriptParser::DataType type_from_metatype(const GDScriptParser::DataType &p_meta_type) const; GDScriptParser::DataType type_from_property(const PropertyInfo &p_property) const; - GDScriptParser::DataType make_global_class_meta_type(const StringName &p_class_name); + GDScriptParser::DataType make_global_class_meta_type(const StringName &p_class_name, const GDScriptParser::Node *p_source); bool get_function_signature(GDScriptParser::Node *p_source, GDScriptParser::DataType base_type, const StringName &p_function, GDScriptParser::DataType &r_return_type, List<GDScriptParser::DataType> &r_par_types, int &r_default_arg_count, bool &r_static, bool &r_vararg); bool function_signature_from_info(const MethodInfo &p_info, GDScriptParser::DataType &r_return_type, List<GDScriptParser::DataType> &r_par_types, int &r_default_arg_count, bool &r_static, bool &r_vararg); bool validate_call_arg(const List<GDScriptParser::DataType> &p_par_types, int p_default_args_count, bool p_is_vararg, const GDScriptParser::CallNode *p_call); bool validate_call_arg(const MethodInfo &p_method, const GDScriptParser::CallNode *p_call); GDScriptParser::DataType get_operation_type(Variant::Operator p_operation, const GDScriptParser::DataType &p_a, const GDScriptParser::DataType &p_b, bool &r_valid, const GDScriptParser::Node *p_source); + GDScriptParser::DataType get_operation_type(Variant::Operator p_operation, const GDScriptParser::DataType &p_a, bool &r_valid, const GDScriptParser::Node *p_source); bool is_type_compatible(const GDScriptParser::DataType &p_target, const GDScriptParser::DataType &p_source, bool p_allow_implicit_conversion = false) const; void push_error(const String &p_message, const GDScriptParser::Node *p_origin); void mark_node_unsafe(const GDScriptParser::Node *p_node); diff --git a/modules/gdscript/gdscript_byte_codegen.cpp b/modules/gdscript/gdscript_byte_codegen.cpp index 95c0068b20..d89b89c8b9 100644 --- a/modules/gdscript/gdscript_byte_codegen.cpp +++ b/modules/gdscript/gdscript_byte_codegen.cpp @@ -73,11 +73,22 @@ uint32_t GDScriptByteCodeGenerator::add_or_get_name(const StringName &p_name) { uint32_t GDScriptByteCodeGenerator::add_temporary() { current_temporaries++; - return increase_stack(); + int idx = increase_stack(); +#ifdef DEBUG_ENABLED + temp_stack.push_back(idx); +#endif + return idx; } void GDScriptByteCodeGenerator::pop_temporary() { + ERR_FAIL_COND(current_temporaries == 0); current_stack_size--; +#ifdef DEBUG_ENABLED + if (temp_stack.back()->get() != current_stack_size) { + ERR_PRINT("Mismatched popping of temporary value"); + } + temp_stack.pop_back(); +#endif current_temporaries--; } @@ -112,7 +123,12 @@ void GDScriptByteCodeGenerator::write_start(GDScript *p_script, const StringName } GDScriptFunction *GDScriptByteCodeGenerator::write_end() { - append(GDScriptFunction::OPCODE_END); +#ifdef DEBUG_ENABLED + if (current_temporaries != 0) { + ERR_PRINT("Non-zero temporary variables at end of function: " + itos(current_temporaries)); + } +#endif + append(GDScriptFunction::OPCODE_END, 0); if (constant_map.size()) { function->_constant_count = constant_map.size(); @@ -159,11 +175,132 @@ GDScriptFunction *GDScriptByteCodeGenerator::write_end() { function->_default_arg_ptr = nullptr; } + if (operator_func_map.size()) { + function->operator_funcs.resize(operator_func_map.size()); + function->_operator_funcs_count = function->operator_funcs.size(); + function->_operator_funcs_ptr = function->operator_funcs.ptr(); + for (const Map<Variant::ValidatedOperatorEvaluator, int>::Element *E = operator_func_map.front(); E; E = E->next()) { + function->operator_funcs.write[E->get()] = E->key(); + } + } else { + function->_operator_funcs_count = 0; + function->_operator_funcs_ptr = nullptr; + } + + if (setters_map.size()) { + function->setters.resize(setters_map.size()); + function->_setters_count = function->setters.size(); + function->_setters_ptr = function->setters.ptr(); + for (const Map<Variant::ValidatedSetter, int>::Element *E = setters_map.front(); E; E = E->next()) { + function->setters.write[E->get()] = E->key(); + } + } else { + function->_setters_count = 0; + function->_setters_ptr = nullptr; + } + + if (getters_map.size()) { + function->getters.resize(getters_map.size()); + function->_getters_count = function->getters.size(); + function->_getters_ptr = function->getters.ptr(); + for (const Map<Variant::ValidatedGetter, int>::Element *E = getters_map.front(); E; E = E->next()) { + function->getters.write[E->get()] = E->key(); + } + } else { + function->_getters_count = 0; + function->_getters_ptr = nullptr; + } + + if (keyed_setters_map.size()) { + function->keyed_setters.resize(keyed_setters_map.size()); + function->_keyed_setters_count = function->keyed_setters.size(); + function->_keyed_setters_ptr = function->keyed_setters.ptr(); + for (const Map<Variant::ValidatedKeyedSetter, int>::Element *E = keyed_setters_map.front(); E; E = E->next()) { + function->keyed_setters.write[E->get()] = E->key(); + } + } else { + function->_keyed_setters_count = 0; + function->_keyed_setters_ptr = nullptr; + } + + if (keyed_getters_map.size()) { + function->keyed_getters.resize(keyed_getters_map.size()); + function->_keyed_getters_count = function->keyed_getters.size(); + function->_keyed_getters_ptr = function->keyed_getters.ptr(); + for (const Map<Variant::ValidatedKeyedGetter, int>::Element *E = keyed_getters_map.front(); E; E = E->next()) { + function->keyed_getters.write[E->get()] = E->key(); + } + } else { + function->_keyed_getters_count = 0; + function->_keyed_getters_ptr = nullptr; + } + + if (indexed_setters_map.size()) { + function->indexed_setters.resize(indexed_setters_map.size()); + function->_indexed_setters_count = function->indexed_setters.size(); + function->_indexed_setters_ptr = function->indexed_setters.ptr(); + for (const Map<Variant::ValidatedIndexedSetter, int>::Element *E = indexed_setters_map.front(); E; E = E->next()) { + function->indexed_setters.write[E->get()] = E->key(); + } + } else { + function->_indexed_setters_count = 0; + function->_indexed_setters_ptr = nullptr; + } + + if (indexed_getters_map.size()) { + function->indexed_getters.resize(indexed_getters_map.size()); + function->_indexed_getters_count = function->indexed_getters.size(); + function->_indexed_getters_ptr = function->indexed_getters.ptr(); + for (const Map<Variant::ValidatedIndexedGetter, int>::Element *E = indexed_getters_map.front(); E; E = E->next()) { + function->indexed_getters.write[E->get()] = E->key(); + } + } else { + function->_indexed_getters_count = 0; + function->_indexed_getters_ptr = nullptr; + } + + if (builtin_method_map.size()) { + function->builtin_methods.resize(builtin_method_map.size()); + function->_builtin_methods_ptr = function->builtin_methods.ptr(); + function->_builtin_methods_count = builtin_method_map.size(); + for (const Map<Variant::ValidatedBuiltInMethod, int>::Element *E = builtin_method_map.front(); E; E = E->next()) { + function->builtin_methods.write[E->get()] = E->key(); + } + } else { + function->_builtin_methods_ptr = nullptr; + function->_builtin_methods_count = 0; + } + + if (constructors_map.size()) { + function->constructors.resize(constructors_map.size()); + function->_constructors_ptr = function->constructors.ptr(); + function->_constructors_count = constructors_map.size(); + for (const Map<Variant::ValidatedConstructor, int>::Element *E = constructors_map.front(); E; E = E->next()) { + function->constructors.write[E->get()] = E->key(); + } + } else { + function->_constructors_ptr = nullptr; + function->_constructors_count = 0; + } + + if (method_bind_map.size()) { + function->methods.resize(method_bind_map.size()); + function->_methods_ptr = function->methods.ptrw(); + function->_methods_count = method_bind_map.size(); + for (const Map<MethodBind *, int>::Element *E = method_bind_map.front(); E; E = E->next()) { + function->methods.write[E->get()] = E->key(); + } + } else { + function->_methods_ptr = nullptr; + function->_methods_count = 0; + } + if (debug_stack) { function->stack_debug = stack_debug; } function->_stack_size = stack_max; - function->_call_size = call_max; + function->_instruction_args_size = instr_args_max; + function->_ptrcall_args_size = ptrcall_max; ended = true; return function; @@ -179,37 +316,77 @@ void GDScriptByteCodeGenerator::set_initial_line(int p_line) { function->_initial_line = p_line; } -void GDScriptByteCodeGenerator::write_operator(const Address &p_target, Variant::Operator p_operator, const Address &p_left_operand, const Address &p_right_operand) { - append(GDScriptFunction::OPCODE_OPERATOR); +#define HAS_BUILTIN_TYPE(m_var) \ + (m_var.type.has_type && m_var.type.kind == GDScriptDataType::BUILTIN) + +#define IS_BUILTIN_TYPE(m_var, m_type) \ + (m_var.type.has_type && m_var.type.kind == GDScriptDataType::BUILTIN && m_var.type.builtin_type == m_type) + +void GDScriptByteCodeGenerator::write_unary_operator(const Address &p_target, Variant::Operator p_operator, const Address &p_left_operand) { + if (HAS_BUILTIN_TYPE(p_left_operand)) { + // Gather specific operator. + Variant::ValidatedOperatorEvaluator op_func = Variant::get_validated_operator_evaluator(p_operator, p_left_operand.type.builtin_type, Variant::NIL); + + append(GDScriptFunction::OPCODE_OPERATOR_VALIDATED, 3); + append(p_left_operand); + append(Address()); + append(p_target); + append(op_func); + return; + } + + // No specific types, perform variant evaluation. + append(GDScriptFunction::OPCODE_OPERATOR, 3); + append(p_left_operand); + append(Address()); + append(p_target); append(p_operator); +} + +void GDScriptByteCodeGenerator::write_binary_operator(const Address &p_target, Variant::Operator p_operator, const Address &p_left_operand, const Address &p_right_operand) { + if (HAS_BUILTIN_TYPE(p_left_operand) && HAS_BUILTIN_TYPE(p_right_operand)) { + // Gather specific operator. + Variant::ValidatedOperatorEvaluator op_func = Variant::get_validated_operator_evaluator(p_operator, p_left_operand.type.builtin_type, p_right_operand.type.builtin_type); + + append(GDScriptFunction::OPCODE_OPERATOR_VALIDATED, 3); + append(p_left_operand); + append(p_right_operand); + append(p_target); + append(op_func); + return; + } + + // No specific types, perform variant evaluation. + append(GDScriptFunction::OPCODE_OPERATOR, 3); append(p_left_operand); append(p_right_operand); append(p_target); + append(p_operator); } void GDScriptByteCodeGenerator::write_type_test(const Address &p_target, const Address &p_source, const Address &p_type) { - append(GDScriptFunction::OPCODE_EXTENDS_TEST); + append(GDScriptFunction::OPCODE_EXTENDS_TEST, 3); append(p_source); append(p_type); append(p_target); } void GDScriptByteCodeGenerator::write_type_test_builtin(const Address &p_target, const Address &p_source, Variant::Type p_type) { - append(GDScriptFunction::OPCODE_IS_BUILTIN); + append(GDScriptFunction::OPCODE_IS_BUILTIN, 3); append(p_source); - append(p_type); append(p_target); + append(p_type); } void GDScriptByteCodeGenerator::write_and_left_operand(const Address &p_left_operand) { - append(GDScriptFunction::OPCODE_JUMP_IF_NOT); + append(GDScriptFunction::OPCODE_JUMP_IF_NOT, 1); append(p_left_operand); logic_op_jump_pos1.push_back(opcodes.size()); append(0); // Jump target, will be patched. } void GDScriptByteCodeGenerator::write_and_right_operand(const Address &p_right_operand) { - append(GDScriptFunction::OPCODE_JUMP_IF_NOT); + append(GDScriptFunction::OPCODE_JUMP_IF_NOT, 1); append(p_right_operand); logic_op_jump_pos2.push_back(opcodes.size()); append(0); // Jump target, will be patched. @@ -217,29 +394,29 @@ void GDScriptByteCodeGenerator::write_and_right_operand(const Address &p_right_o void GDScriptByteCodeGenerator::write_end_and(const Address &p_target) { // If here means both operands are true. - append(GDScriptFunction::OPCODE_ASSIGN_TRUE); + append(GDScriptFunction::OPCODE_ASSIGN_TRUE, 1); append(p_target); // Jump away from the fail condition. - append(GDScriptFunction::OPCODE_JUMP); + append(GDScriptFunction::OPCODE_JUMP, 0); append(opcodes.size() + 3); // Here it means one of operands is false. patch_jump(logic_op_jump_pos1.back()->get()); patch_jump(logic_op_jump_pos2.back()->get()); logic_op_jump_pos1.pop_back(); logic_op_jump_pos2.pop_back(); - append(GDScriptFunction::OPCODE_ASSIGN_FALSE); + append(GDScriptFunction::OPCODE_ASSIGN_FALSE, 0); append(p_target); } void GDScriptByteCodeGenerator::write_or_left_operand(const Address &p_left_operand) { - append(GDScriptFunction::OPCODE_JUMP_IF); + append(GDScriptFunction::OPCODE_JUMP_IF, 1); append(p_left_operand); logic_op_jump_pos1.push_back(opcodes.size()); append(0); // Jump target, will be patched. } void GDScriptByteCodeGenerator::write_or_right_operand(const Address &p_right_operand) { - append(GDScriptFunction::OPCODE_JUMP_IF); + append(GDScriptFunction::OPCODE_JUMP_IF, 1); append(p_right_operand); logic_op_jump_pos2.push_back(opcodes.size()); append(0); // Jump target, will be patched. @@ -247,17 +424,17 @@ void GDScriptByteCodeGenerator::write_or_right_operand(const Address &p_right_op void GDScriptByteCodeGenerator::write_end_or(const Address &p_target) { // If here means both operands are false. - append(GDScriptFunction::OPCODE_ASSIGN_FALSE); + append(GDScriptFunction::OPCODE_ASSIGN_FALSE, 1); append(p_target); // Jump away from the success condition. - append(GDScriptFunction::OPCODE_JUMP); + append(GDScriptFunction::OPCODE_JUMP, 0); append(opcodes.size() + 3); // Here it means one of operands is false. patch_jump(logic_op_jump_pos1.back()->get()); patch_jump(logic_op_jump_pos2.back()->get()); logic_op_jump_pos1.pop_back(); logic_op_jump_pos2.pop_back(); - append(GDScriptFunction::OPCODE_ASSIGN_TRUE); + append(GDScriptFunction::OPCODE_ASSIGN_TRUE, 1); append(p_target); } @@ -266,18 +443,18 @@ void GDScriptByteCodeGenerator::write_start_ternary(const Address &p_target) { } void GDScriptByteCodeGenerator::write_ternary_condition(const Address &p_condition) { - append(GDScriptFunction::OPCODE_JUMP_IF_NOT); + append(GDScriptFunction::OPCODE_JUMP_IF_NOT, 1); append(p_condition); ternary_jump_fail_pos.push_back(opcodes.size()); append(0); // Jump target, will be patched. } void GDScriptByteCodeGenerator::write_ternary_true_expr(const Address &p_expr) { - append(GDScriptFunction::OPCODE_ASSIGN); + append(GDScriptFunction::OPCODE_ASSIGN, 2); append(ternary_result.back()->get()); append(p_expr); // Jump away from the false path. - append(GDScriptFunction::OPCODE_JUMP); + append(GDScriptFunction::OPCODE_JUMP, 0); ternary_jump_skip_pos.push_back(opcodes.size()); append(0); // Fail must jump here. @@ -286,7 +463,7 @@ void GDScriptByteCodeGenerator::write_ternary_true_expr(const Address &p_expr) { } void GDScriptByteCodeGenerator::write_ternary_false_expr(const Address &p_expr) { - append(GDScriptFunction::OPCODE_ASSIGN); + append(GDScriptFunction::OPCODE_ASSIGN, 2); append(ternary_result.back()->get()); append(p_expr); } @@ -297,43 +474,100 @@ void GDScriptByteCodeGenerator::write_end_ternary() { } void GDScriptByteCodeGenerator::write_set(const Address &p_target, const Address &p_index, const Address &p_source) { - append(GDScriptFunction::OPCODE_SET); + if (HAS_BUILTIN_TYPE(p_target)) { + if (IS_BUILTIN_TYPE(p_index, Variant::INT) && Variant::get_member_validated_indexed_setter(p_target.type.builtin_type)) { + // Use indexed setter instead. + Variant::ValidatedIndexedSetter setter = Variant::get_member_validated_indexed_setter(p_target.type.builtin_type); + append(GDScriptFunction::OPCODE_SET_INDEXED_VALIDATED, 3); + append(p_target); + append(p_index); + append(p_source); + append(setter); + return; + } else if (Variant::get_member_validated_keyed_setter(p_target.type.builtin_type)) { + Variant::ValidatedKeyedSetter setter = Variant::get_member_validated_keyed_setter(p_target.type.builtin_type); + append(GDScriptFunction::OPCODE_SET_KEYED_VALIDATED, 3); + append(p_target); + append(p_index); + append(p_source); + append(setter); + return; + } + } + + append(GDScriptFunction::OPCODE_SET_KEYED, 3); append(p_target); append(p_index); append(p_source); } void GDScriptByteCodeGenerator::write_get(const Address &p_target, const Address &p_index, const Address &p_source) { - append(GDScriptFunction::OPCODE_GET); + if (HAS_BUILTIN_TYPE(p_source)) { + if (IS_BUILTIN_TYPE(p_index, Variant::INT) && Variant::get_member_validated_indexed_getter(p_source.type.builtin_type)) { + // Use indexed getter instead. + Variant::ValidatedIndexedGetter getter = Variant::get_member_validated_indexed_getter(p_source.type.builtin_type); + append(GDScriptFunction::OPCODE_GET_INDEXED_VALIDATED, 3); + append(p_source); + append(p_index); + append(p_target); + append(getter); + return; + } else if (Variant::get_member_validated_keyed_getter(p_source.type.builtin_type)) { + Variant::ValidatedKeyedGetter getter = Variant::get_member_validated_keyed_getter(p_source.type.builtin_type); + append(GDScriptFunction::OPCODE_GET_KEYED_VALIDATED, 3); + append(p_source); + append(p_index); + append(p_target); + append(getter); + return; + } + } + append(GDScriptFunction::OPCODE_GET_KEYED, 3); append(p_source); append(p_index); append(p_target); } void GDScriptByteCodeGenerator::write_set_named(const Address &p_target, const StringName &p_name, const Address &p_source) { - append(GDScriptFunction::OPCODE_SET_NAMED); + if (HAS_BUILTIN_TYPE(p_target) && Variant::get_member_validated_setter(p_target.type.builtin_type, p_name)) { + Variant::ValidatedSetter setter = Variant::get_member_validated_setter(p_target.type.builtin_type, p_name); + append(GDScriptFunction::OPCODE_SET_NAMED_VALIDATED, 2); + append(p_target); + append(p_source); + append(setter); + return; + } + append(GDScriptFunction::OPCODE_SET_NAMED, 2); append(p_target); - append(p_name); append(p_source); + append(p_name); } void GDScriptByteCodeGenerator::write_get_named(const Address &p_target, const StringName &p_name, const Address &p_source) { - append(GDScriptFunction::OPCODE_GET_NAMED); + if (HAS_BUILTIN_TYPE(p_source) && Variant::get_member_validated_getter(p_source.type.builtin_type, p_name)) { + Variant::ValidatedGetter getter = Variant::get_member_validated_getter(p_source.type.builtin_type, p_name); + append(GDScriptFunction::OPCODE_GET_NAMED_VALIDATED, 2); + append(p_source); + append(p_target); + append(getter); + return; + } + append(GDScriptFunction::OPCODE_GET_NAMED, 2); append(p_source); - append(p_name); append(p_target); + append(p_name); } void GDScriptByteCodeGenerator::write_set_member(const Address &p_value, const StringName &p_name) { - append(GDScriptFunction::OPCODE_SET_MEMBER); - append(p_name); + append(GDScriptFunction::OPCODE_SET_MEMBER, 1); append(p_value); + append(p_name); } void GDScriptByteCodeGenerator::write_get_member(const Address &p_target, const StringName &p_name) { - append(GDScriptFunction::OPCODE_GET_MEMBER); - append(p_name); + append(GDScriptFunction::OPCODE_GET_MEMBER, 1); append(p_target); + append(p_name); } void GDScriptByteCodeGenerator::write_assign(const Address &p_target, const Address &p_source) { @@ -341,34 +575,35 @@ void GDScriptByteCodeGenerator::write_assign(const Address &p_target, const Addr // Typed assignment. switch (p_target.type.kind) { case GDScriptDataType::BUILTIN: { - append(GDScriptFunction::OPCODE_ASSIGN_TYPED_BUILTIN); - append(p_target.type.builtin_type); + append(GDScriptFunction::OPCODE_ASSIGN_TYPED_BUILTIN, 2); append(p_target); append(p_source); + append(p_target.type.builtin_type); } break; case GDScriptDataType::NATIVE: { int class_idx = GDScriptLanguage::get_singleton()->get_global_map()[p_target.type.native_type]; class_idx |= (GDScriptFunction::ADDR_TYPE_GLOBAL << GDScriptFunction::ADDR_BITS); - append(GDScriptFunction::OPCODE_ASSIGN_TYPED_NATIVE); - append(class_idx); + append(GDScriptFunction::OPCODE_ASSIGN_TYPED_NATIVE, 3); append(p_target); append(p_source); + append(class_idx); } break; case GDScriptDataType::SCRIPT: case GDScriptDataType::GDSCRIPT: { Variant script = p_target.type.script_type; int idx = get_constant_pos(script); + idx |= (GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT << GDScriptFunction::ADDR_BITS); - append(GDScriptFunction::OPCODE_ASSIGN_TYPED_SCRIPT); - append(idx); + append(GDScriptFunction::OPCODE_ASSIGN_TYPED_SCRIPT, 3); append(p_target); append(p_source); + append(idx); } break; default: { ERR_PRINT("Compiler bug: unresolved assign."); // Shouldn't get here, but fail-safe to a regular assignment - append(GDScriptFunction::OPCODE_ASSIGN); + append(GDScriptFunction::OPCODE_ASSIGN, 2); append(p_target); append(p_source); } @@ -376,13 +611,13 @@ void GDScriptByteCodeGenerator::write_assign(const Address &p_target, const Addr } else { if (p_target.type.kind == GDScriptDataType::BUILTIN && p_source.type.kind == GDScriptDataType::BUILTIN && p_target.type.builtin_type != p_source.type.builtin_type) { // Need conversion.. - append(GDScriptFunction::OPCODE_ASSIGN_TYPED_BUILTIN); - append(p_target.type.builtin_type); + append(GDScriptFunction::OPCODE_ASSIGN_TYPED_BUILTIN, 2); append(p_target); append(p_source); + append(p_target.type.builtin_type); } else { // Either untyped assignment or already type-checked by the parser - append(GDScriptFunction::OPCODE_ASSIGN); + append(GDScriptFunction::OPCODE_ASSIGN, 2); append(p_target); append(p_source); } @@ -390,12 +625,12 @@ void GDScriptByteCodeGenerator::write_assign(const Address &p_target, const Addr } void GDScriptByteCodeGenerator::write_assign_true(const Address &p_target) { - append(GDScriptFunction::OPCODE_ASSIGN_TRUE); + append(GDScriptFunction::OPCODE_ASSIGN_TRUE, 1); append(p_target); } void GDScriptByteCodeGenerator::write_assign_false(const Address &p_target) { - append(GDScriptFunction::OPCODE_ASSIGN_FALSE); + append(GDScriptFunction::OPCODE_ASSIGN_FALSE, 1); append(p_target); } @@ -405,24 +640,27 @@ void GDScriptByteCodeGenerator::write_assign_default_parameter(const Address &p_ } void GDScriptByteCodeGenerator::write_cast(const Address &p_target, const Address &p_source, const GDScriptDataType &p_type) { + int index = 0; + switch (p_type.kind) { case GDScriptDataType::BUILTIN: { - append(GDScriptFunction::OPCODE_CAST_TO_BUILTIN); - append(p_type.builtin_type); + append(GDScriptFunction::OPCODE_CAST_TO_BUILTIN, 2); + index = p_type.builtin_type; } break; case GDScriptDataType::NATIVE: { int class_idx = GDScriptLanguage::get_singleton()->get_global_map()[p_type.native_type]; class_idx |= (GDScriptFunction::ADDR_TYPE_GLOBAL << GDScriptFunction::ADDR_BITS); - append(GDScriptFunction::OPCODE_CAST_TO_NATIVE); - append(class_idx); + append(GDScriptFunction::OPCODE_CAST_TO_NATIVE, 3); + index = class_idx; } break; case GDScriptDataType::SCRIPT: case GDScriptDataType::GDSCRIPT: { Variant script = p_type.script_type; int idx = get_constant_pos(script); + idx |= (GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT << GDScriptFunction::ADDR_BITS); - append(GDScriptFunction::OPCODE_CAST_TO_SCRIPT); - append(idx); + append(GDScriptFunction::OPCODE_CAST_TO_SCRIPT, 3); + index = idx; } break; default: { return; @@ -431,147 +669,272 @@ void GDScriptByteCodeGenerator::write_cast(const Address &p_target, const Addres append(p_source); append(p_target); + append(index); } void GDScriptByteCodeGenerator::write_call(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) { - append(p_target.mode == Address::NIL ? GDScriptFunction::OPCODE_CALL : GDScriptFunction::OPCODE_CALL_RETURN); - append(p_arguments.size()); - append(p_base); - append(p_function_name); + append(p_target.mode == Address::NIL ? GDScriptFunction::OPCODE_CALL : GDScriptFunction::OPCODE_CALL_RETURN, 2 + p_arguments.size()); for (int i = 0; i < p_arguments.size(); i++) { append(p_arguments[i]); } + append(p_base); append(p_target); - alloc_call(p_arguments.size()); + append(p_arguments.size()); + append(p_function_name); } void GDScriptByteCodeGenerator::write_super_call(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) { - append(GDScriptFunction::OPCODE_CALL_SELF_BASE); - append(p_function_name); - append(p_arguments.size()); + append(GDScriptFunction::OPCODE_CALL_SELF_BASE, 1 + p_arguments.size()); for (int i = 0; i < p_arguments.size(); i++) { append(p_arguments[i]); } append(p_target); - alloc_call(p_arguments.size()); + append(p_arguments.size()); + append(p_function_name); } void GDScriptByteCodeGenerator::write_call_async(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) { - append(GDScriptFunction::OPCODE_CALL_ASYNC); - append(p_arguments.size()); - append(p_base); - append(p_function_name); + append(GDScriptFunction::OPCODE_CALL_ASYNC, 2 + p_arguments.size()); for (int i = 0; i < p_arguments.size(); i++) { append(p_arguments[i]); } + append(p_base); append(p_target); - alloc_call(p_arguments.size()); + append(p_arguments.size()); + append(p_function_name); } void GDScriptByteCodeGenerator::write_call_builtin(const Address &p_target, GDScriptFunctions::Function p_function, const Vector<Address> &p_arguments) { - append(GDScriptFunction::OPCODE_CALL_BUILT_IN); - append(p_function); - append(p_arguments.size()); + append(GDScriptFunction::OPCODE_CALL_BUILT_IN, 1 + p_arguments.size()); for (int i = 0; i < p_arguments.size(); i++) { append(p_arguments[i]); } append(p_target); - alloc_call(p_arguments.size()); + append(p_arguments.size()); + append(p_function); } -void GDScriptByteCodeGenerator::write_call_method_bind(const Address &p_target, const Address &p_base, const MethodBind *p_method, const Vector<Address> &p_arguments) { - append(p_target.mode == Address::NIL ? GDScriptFunction::OPCODE_CALL : GDScriptFunction::OPCODE_CALL_RETURN); - append(p_arguments.size()); - append(p_base); - append(p_method->get_name()); +void GDScriptByteCodeGenerator::write_call_builtin_type(const Address &p_target, const Address &p_base, Variant::Type p_type, const StringName &p_method, const Vector<Address> &p_arguments) { + bool is_validated = false; + + // Check if all types are correct. + if (Variant::is_builtin_method_vararg(p_type, p_method)) { + is_validated = true; // Vararg works fine with any argument, since they can be any type. + } else if (p_arguments.size() == Variant::get_builtin_method_argument_count(p_type, p_method)) { + bool all_types_exact = true; + for (int i = 0; i < p_arguments.size(); i++) { + if (!IS_BUILTIN_TYPE(p_arguments[i], Variant::get_builtin_method_argument_type(p_type, p_method, i))) { + all_types_exact = false; + break; + } + } + + is_validated = all_types_exact; + } + + if (!is_validated) { + // Perform regular call. + write_call(p_target, p_base, p_method, p_arguments); + return; + } + + append(GDScriptFunction::OPCODE_CALL_BUILTIN_TYPE_VALIDATED, 2 + p_arguments.size()); + for (int i = 0; i < p_arguments.size(); i++) { append(p_arguments[i]); } + append(p_base); append(p_target); - alloc_call(p_arguments.size()); + append(p_arguments.size()); + append(Variant::get_validated_builtin_method(p_type, p_method)); } -void GDScriptByteCodeGenerator::write_call_ptrcall(const Address &p_target, const Address &p_base, const MethodBind *p_method, const Vector<Address> &p_arguments) { - append(p_target.mode == Address::NIL ? GDScriptFunction::OPCODE_CALL : GDScriptFunction::OPCODE_CALL_RETURN); - append(p_arguments.size()); +void GDScriptByteCodeGenerator::write_call_method_bind(const Address &p_target, const Address &p_base, MethodBind *p_method, const Vector<Address> &p_arguments) { + append(p_target.mode == Address::NIL ? GDScriptFunction::OPCODE_CALL_METHOD_BIND : GDScriptFunction::OPCODE_CALL_METHOD_BIND_RET, 2 + p_arguments.size()); + for (int i = 0; i < p_arguments.size(); i++) { + append(p_arguments[i]); + } append(p_base); - append(p_method->get_name()); + append(p_target); + append(p_arguments.size()); + append(p_method); +} + +void GDScriptByteCodeGenerator::write_call_ptrcall(const Address &p_target, const Address &p_base, MethodBind *p_method, const Vector<Address> &p_arguments) { +#define CASE_TYPE(m_type) \ + case Variant::m_type: \ + append(GDScriptFunction::OPCODE_CALL_PTRCALL_##m_type, 2 + p_arguments.size()); \ + break + + bool is_ptrcall = true; + + if (p_method->has_return()) { + MethodInfo info; + ClassDB::get_method_info(p_method->get_instance_class(), p_method->get_name(), &info); + switch (info.return_val.type) { + CASE_TYPE(BOOL); + CASE_TYPE(INT); + CASE_TYPE(FLOAT); + CASE_TYPE(STRING); + CASE_TYPE(VECTOR2); + CASE_TYPE(VECTOR2I); + CASE_TYPE(RECT2); + CASE_TYPE(RECT2I); + CASE_TYPE(VECTOR3); + CASE_TYPE(VECTOR3I); + CASE_TYPE(TRANSFORM2D); + CASE_TYPE(PLANE); + CASE_TYPE(AABB); + CASE_TYPE(BASIS); + CASE_TYPE(TRANSFORM); + CASE_TYPE(COLOR); + CASE_TYPE(STRING_NAME); + CASE_TYPE(NODE_PATH); + CASE_TYPE(RID); + CASE_TYPE(QUAT); + CASE_TYPE(OBJECT); + CASE_TYPE(CALLABLE); + CASE_TYPE(SIGNAL); + CASE_TYPE(DICTIONARY); + CASE_TYPE(ARRAY); + CASE_TYPE(PACKED_BYTE_ARRAY); + CASE_TYPE(PACKED_INT32_ARRAY); + CASE_TYPE(PACKED_INT64_ARRAY); + CASE_TYPE(PACKED_FLOAT32_ARRAY); + CASE_TYPE(PACKED_FLOAT64_ARRAY); + CASE_TYPE(PACKED_STRING_ARRAY); + CASE_TYPE(PACKED_VECTOR2_ARRAY); + CASE_TYPE(PACKED_VECTOR3_ARRAY); + CASE_TYPE(PACKED_COLOR_ARRAY); + default: + append(p_target.mode == Address::NIL ? GDScriptFunction::OPCODE_CALL_METHOD_BIND : GDScriptFunction::OPCODE_CALL_METHOD_BIND_RET, 2 + p_arguments.size()); + is_ptrcall = false; + break; + } + } else { + append(GDScriptFunction::OPCODE_CALL_PTRCALL_NO_RETURN, 2 + p_arguments.size()); + } + for (int i = 0; i < p_arguments.size(); i++) { append(p_arguments[i]); } + append(p_base); append(p_target); - alloc_call(p_arguments.size()); + append(p_arguments.size()); + append(p_method); + if (is_ptrcall) { + alloc_ptrcall(p_arguments.size()); + } + +#undef CASE_TYPE } void GDScriptByteCodeGenerator::write_call_self(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) { - append(p_target.mode == Address::NIL ? GDScriptFunction::OPCODE_CALL : GDScriptFunction::OPCODE_CALL_RETURN); - append(p_arguments.size()); - append(GDScriptFunction::ADDR_TYPE_SELF << GDScriptFunction::ADDR_BITS); - append(p_function_name); + append(p_target.mode == Address::NIL ? GDScriptFunction::OPCODE_CALL : GDScriptFunction::OPCODE_CALL_RETURN, 2 + p_arguments.size()); for (int i = 0; i < p_arguments.size(); i++) { append(p_arguments[i]); } + append(GDScriptFunction::ADDR_TYPE_SELF << GDScriptFunction::ADDR_BITS); append(p_target); - alloc_call(p_arguments.size()); + append(p_arguments.size()); + append(p_function_name); } void GDScriptByteCodeGenerator::write_call_script_function(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) { - append(p_target.mode == Address::NIL ? GDScriptFunction::OPCODE_CALL : GDScriptFunction::OPCODE_CALL_RETURN); - append(p_arguments.size()); - append(p_base); - append(p_function_name); + append(p_target.mode == Address::NIL ? GDScriptFunction::OPCODE_CALL : GDScriptFunction::OPCODE_CALL_RETURN, 2 + p_arguments.size()); for (int i = 0; i < p_arguments.size(); i++) { append(p_arguments[i]); } + append(p_base); append(p_target); - alloc_call(p_arguments.size()); + append(p_arguments.size()); + append(p_function_name); } void GDScriptByteCodeGenerator::write_construct(const Address &p_target, Variant::Type p_type, const Vector<Address> &p_arguments) { - append(GDScriptFunction::OPCODE_CONSTRUCT); - append(p_type); - append(p_arguments.size()); + // Try to find an appropriate constructor. + bool all_have_type = true; + Vector<Variant::Type> arg_types; + for (int i = 0; i < p_arguments.size(); i++) { + if (!HAS_BUILTIN_TYPE(p_arguments[i])) { + all_have_type = false; + break; + } + arg_types.push_back(p_arguments[i].type.builtin_type); + } + if (all_have_type) { + int valid_constructor = -1; + for (int i = 0; i < Variant::get_constructor_count(p_type); i++) { + if (Variant::get_constructor_argument_count(p_type, i) != p_arguments.size()) { + continue; + } + int types_correct = true; + for (int j = 0; j < arg_types.size(); j++) { + if (arg_types[j] != Variant::get_constructor_argument_type(p_type, i, j)) { + types_correct = false; + break; + } + } + if (types_correct) { + valid_constructor = i; + break; + } + } + if (valid_constructor >= 0) { + append(GDScriptFunction::OPCODE_CONSTRUCT_VALIDATED, 1 + p_arguments.size()); + for (int i = 0; i < p_arguments.size(); i++) { + append(p_arguments[i]); + } + append(p_target); + append(p_arguments.size()); + append(Variant::get_validated_constructor(p_type, valid_constructor)); + return; + } + } + + append(GDScriptFunction::OPCODE_CONSTRUCT, 1 + p_arguments.size()); for (int i = 0; i < p_arguments.size(); i++) { append(p_arguments[i]); } append(p_target); - alloc_call(p_arguments.size()); + append(p_arguments.size()); + append(p_type); } void GDScriptByteCodeGenerator::write_construct_array(const Address &p_target, const Vector<Address> &p_arguments) { - append(GDScriptFunction::OPCODE_CONSTRUCT_ARRAY); - append(p_arguments.size()); + append(GDScriptFunction::OPCODE_CONSTRUCT_ARRAY, 1 + p_arguments.size()); for (int i = 0; i < p_arguments.size(); i++) { append(p_arguments[i]); } append(p_target); + append(p_arguments.size()); } void GDScriptByteCodeGenerator::write_construct_dictionary(const Address &p_target, const Vector<Address> &p_arguments) { - append(GDScriptFunction::OPCODE_CONSTRUCT_DICTIONARY); - append(p_arguments.size() / 2); // This is number of key-value pairs, so only half of actual arguments. + append(GDScriptFunction::OPCODE_CONSTRUCT_DICTIONARY, 1 + p_arguments.size()); for (int i = 0; i < p_arguments.size(); i++) { append(p_arguments[i]); } append(p_target); + append(p_arguments.size() / 2); // This is number of key-value pairs, so only half of actual arguments. } void GDScriptByteCodeGenerator::write_await(const Address &p_target, const Address &p_operand) { - append(GDScriptFunction::OPCODE_AWAIT); + append(GDScriptFunction::OPCODE_AWAIT, 1); append(p_operand); - append(GDScriptFunction::OPCODE_AWAIT_RESUME); + append(GDScriptFunction::OPCODE_AWAIT_RESUME, 1); append(p_target); } void GDScriptByteCodeGenerator::write_if(const Address &p_condition) { - append(GDScriptFunction::OPCODE_JUMP_IF_NOT); + append(GDScriptFunction::OPCODE_JUMP_IF_NOT, 1); append(p_condition); if_jmp_addrs.push_back(opcodes.size()); append(0); // Jump destination, will be patched. } void GDScriptByteCodeGenerator::write_else() { - append(GDScriptFunction::OPCODE_JUMP); // Jump from true if block; + append(GDScriptFunction::OPCODE_JUMP, 0); // Jump from true if block; int else_jmp_addr = opcodes.size(); append(0); // Jump destination, will be patched. @@ -585,41 +948,144 @@ void GDScriptByteCodeGenerator::write_endif() { if_jmp_addrs.pop_back(); } -void GDScriptByteCodeGenerator::write_for(const Address &p_variable, const Address &p_list) { - int counter_pos = add_temporary() | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS); - int container_pos = add_temporary() | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS); +void GDScriptByteCodeGenerator::start_for(const GDScriptDataType &p_iterator_type, const GDScriptDataType &p_list_type) { + Address counter(Address::LOCAL_VARIABLE, add_local("@counter_pos", p_iterator_type), p_iterator_type); + Address container(Address::LOCAL_VARIABLE, add_local("@container_pos", p_list_type), p_list_type); - current_breaks_to_patch.push_back(List<int>()); + // Store state. + for_counter_variables.push_back(counter); + for_container_variables.push_back(container); +} + +void GDScriptByteCodeGenerator::write_for_assignment(const Address &p_variable, const Address &p_list) { + const Address &container = for_container_variables.back()->get(); // Assign container. - append(GDScriptFunction::OPCODE_ASSIGN); - append(container_pos); + append(GDScriptFunction::OPCODE_ASSIGN, 2); + append(container); append(p_list); + for_iterator_variables.push_back(p_variable); +} + +void GDScriptByteCodeGenerator::write_for() { + const Address &iterator = for_iterator_variables.back()->get(); + const Address &counter = for_counter_variables.back()->get(); + const Address &container = for_container_variables.back()->get(); + + current_breaks_to_patch.push_back(List<int>()); + + GDScriptFunction::Opcode begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN; + GDScriptFunction::Opcode iterate_opcode = GDScriptFunction::OPCODE_ITERATE; + + if (container.type.has_type) { + if (container.type.kind == GDScriptDataType::BUILTIN) { + switch (container.type.builtin_type) { + case Variant::INT: + begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_INT; + iterate_opcode = GDScriptFunction::OPCODE_ITERATE_INT; + break; + case Variant::FLOAT: + begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_FLOAT; + iterate_opcode = GDScriptFunction::OPCODE_ITERATE_FLOAT; + break; + case Variant::VECTOR2: + begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_VECTOR2; + iterate_opcode = GDScriptFunction::OPCODE_ITERATE_VECTOR2; + break; + case Variant::VECTOR2I: + begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_VECTOR2I; + iterate_opcode = GDScriptFunction::OPCODE_ITERATE_VECTOR2I; + break; + case Variant::VECTOR3: + begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_VECTOR3; + iterate_opcode = GDScriptFunction::OPCODE_ITERATE_VECTOR3; + break; + case Variant::VECTOR3I: + begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_VECTOR3I; + iterate_opcode = GDScriptFunction::OPCODE_ITERATE_VECTOR3I; + break; + case Variant::STRING: + begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_STRING; + iterate_opcode = GDScriptFunction::OPCODE_ITERATE_STRING; + break; + case Variant::DICTIONARY: + begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_DICTIONARY; + iterate_opcode = GDScriptFunction::OPCODE_ITERATE_DICTIONARY; + break; + case Variant::ARRAY: + begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_ARRAY; + iterate_opcode = GDScriptFunction::OPCODE_ITERATE_ARRAY; + break; + case Variant::PACKED_BYTE_ARRAY: + begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_PACKED_BYTE_ARRAY; + iterate_opcode = GDScriptFunction::OPCODE_ITERATE_PACKED_BYTE_ARRAY; + break; + case Variant::PACKED_INT32_ARRAY: + begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_PACKED_INT32_ARRAY; + iterate_opcode = GDScriptFunction::OPCODE_ITERATE_PACKED_INT32_ARRAY; + break; + case Variant::PACKED_INT64_ARRAY: + begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_PACKED_INT64_ARRAY; + iterate_opcode = GDScriptFunction::OPCODE_ITERATE_PACKED_INT64_ARRAY; + break; + case Variant::PACKED_FLOAT32_ARRAY: + begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_PACKED_FLOAT32_ARRAY; + iterate_opcode = GDScriptFunction::OPCODE_ITERATE_PACKED_FLOAT32_ARRAY; + break; + case Variant::PACKED_FLOAT64_ARRAY: + begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_PACKED_FLOAT64_ARRAY; + iterate_opcode = GDScriptFunction::OPCODE_ITERATE_PACKED_FLOAT64_ARRAY; + break; + case Variant::PACKED_STRING_ARRAY: + begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_PACKED_STRING_ARRAY; + iterate_opcode = GDScriptFunction::OPCODE_ITERATE_PACKED_STRING_ARRAY; + break; + case Variant::PACKED_VECTOR2_ARRAY: + begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_PACKED_VECTOR2_ARRAY; + iterate_opcode = GDScriptFunction::OPCODE_ITERATE_PACKED_VECTOR2_ARRAY; + break; + case Variant::PACKED_VECTOR3_ARRAY: + begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_PACKED_VECTOR3_ARRAY; + iterate_opcode = GDScriptFunction::OPCODE_ITERATE_PACKED_VECTOR3_ARRAY; + break; + case Variant::PACKED_COLOR_ARRAY: + begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_PACKED_COLOR_ARRAY; + iterate_opcode = GDScriptFunction::OPCODE_ITERATE_PACKED_COLOR_ARRAY; + break; + default: + break; + } + } else { + begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_OBJECT; + iterate_opcode = GDScriptFunction::OPCODE_ITERATE_OBJECT; + } + } + // Begin loop. - append(GDScriptFunction::OPCODE_ITERATE_BEGIN); - append(counter_pos); - append(container_pos); + append(begin_opcode, 3); + append(counter); + append(container); + append(iterator); for_jmp_addrs.push_back(opcodes.size()); append(0); // End of loop address, will be patched. - append(p_variable); - append(GDScriptFunction::OPCODE_JUMP); + append(GDScriptFunction::OPCODE_JUMP, 0); append(opcodes.size() + 6); // Skip over 'continue' code. // Next iteration. int continue_addr = opcodes.size(); continue_addrs.push_back(continue_addr); - append(GDScriptFunction::OPCODE_ITERATE); - append(counter_pos); - append(container_pos); + append(iterate_opcode, 3); + append(counter); + append(container); + append(iterator); for_jmp_addrs.push_back(opcodes.size()); append(0); // Jump destination, will be patched. - append(p_variable); } void GDScriptByteCodeGenerator::write_endfor() { // Jump back to loop check. - append(GDScriptFunction::OPCODE_JUMP); + append(GDScriptFunction::OPCODE_JUMP, 0); append(continue_addrs.back()->get()); continue_addrs.pop_back(); @@ -635,9 +1101,10 @@ void GDScriptByteCodeGenerator::write_endfor() { } current_breaks_to_patch.pop_back(); - // Remove loop temporaries. - pop_temporary(); - pop_temporary(); + // Pop state. + for_iterator_variables.pop_back(); + for_counter_variables.pop_back(); + for_container_variables.pop_back(); } void GDScriptByteCodeGenerator::start_while_condition() { @@ -647,7 +1114,7 @@ void GDScriptByteCodeGenerator::start_while_condition() { void GDScriptByteCodeGenerator::write_while(const Address &p_condition) { // Condition check. - append(GDScriptFunction::OPCODE_JUMP_IF_NOT); + append(GDScriptFunction::OPCODE_JUMP_IF_NOT, 1); append(p_condition); while_jmp_addrs.push_back(opcodes.size()); append(0); // End of loop address, will be patched. @@ -655,7 +1122,7 @@ void GDScriptByteCodeGenerator::write_while(const Address &p_condition) { void GDScriptByteCodeGenerator::write_endwhile() { // Jump back to loop check. - append(GDScriptFunction::OPCODE_JUMP); + append(GDScriptFunction::OPCODE_JUMP, 0); append(continue_addrs.back()->get()); continue_addrs.pop_back(); @@ -693,39 +1160,39 @@ void GDScriptByteCodeGenerator::end_match() { } void GDScriptByteCodeGenerator::write_break() { - append(GDScriptFunction::OPCODE_JUMP); + append(GDScriptFunction::OPCODE_JUMP, 0); current_breaks_to_patch.back()->get().push_back(opcodes.size()); append(0); } void GDScriptByteCodeGenerator::write_continue() { - append(GDScriptFunction::OPCODE_JUMP); + append(GDScriptFunction::OPCODE_JUMP, 0); append(continue_addrs.back()->get()); } void GDScriptByteCodeGenerator::write_continue_match() { - append(GDScriptFunction::OPCODE_JUMP); + append(GDScriptFunction::OPCODE_JUMP, 0); match_continues_to_patch.back()->get().push_back(opcodes.size()); append(0); } void GDScriptByteCodeGenerator::write_breakpoint() { - append(GDScriptFunction::OPCODE_BREAKPOINT); + append(GDScriptFunction::OPCODE_BREAKPOINT, 0); } void GDScriptByteCodeGenerator::write_newline(int p_line) { - append(GDScriptFunction::OPCODE_LINE); + append(GDScriptFunction::OPCODE_LINE, 0); append(p_line); current_line = p_line; } void GDScriptByteCodeGenerator::write_return(const Address &p_return_value) { - append(GDScriptFunction::OPCODE_RETURN); + append(GDScriptFunction::OPCODE_RETURN, 1); append(p_return_value); } void GDScriptByteCodeGenerator::write_assert(const Address &p_test, const Address &p_message) { - append(GDScriptFunction::OPCODE_ASSERT); + append(GDScriptFunction::OPCODE_ASSERT, 2); append(p_test); append(p_message); } diff --git a/modules/gdscript/gdscript_byte_codegen.h b/modules/gdscript/gdscript_byte_codegen.h index f3a333c4d7..5cbd12a0ba 100644 --- a/modules/gdscript/gdscript_byte_codegen.h +++ b/modules/gdscript/gdscript_byte_codegen.h @@ -33,6 +33,8 @@ #include "gdscript_codegen.h" +#include "gdscript_function.h" + class GDScriptByteCodeGenerator : public GDScriptCodeGenerator { bool ended = false; GDScriptFunction *function = nullptr; @@ -41,6 +43,7 @@ class GDScriptByteCodeGenerator : public GDScriptCodeGenerator { Vector<int> opcodes; List<Map<StringName, int>> stack_id_stack; Map<StringName, int> stack_identifiers; + List<int> stack_identifiers_counts; Map<StringName, int> local_constants; List<GDScriptFunction::StackDebug> stack_debug; @@ -49,18 +52,38 @@ class GDScriptByteCodeGenerator : public GDScriptCodeGenerator { int current_stack_size = 0; int current_temporaries = 0; + int current_locals = 0; + int current_line = 0; + int stack_max = 0; + int instr_args_max = 0; + int ptrcall_max = 0; + +#ifdef DEBUG_ENABLED + List<int> temp_stack; +#endif HashMap<Variant, int, VariantHasher, VariantComparator> constant_map; Map<StringName, int> name_map; #ifdef TOOLS_ENABLED Vector<StringName> named_globals; #endif - int current_line = 0; - int stack_max = 0; - int call_max = 0; - - List<int> if_jmp_addrs; // List since this can be nested. + Map<Variant::ValidatedOperatorEvaluator, int> operator_func_map; + Map<Variant::ValidatedSetter, int> setters_map; + Map<Variant::ValidatedGetter, int> getters_map; + Map<Variant::ValidatedKeyedSetter, int> keyed_setters_map; + Map<Variant::ValidatedKeyedGetter, int> keyed_getters_map; + Map<Variant::ValidatedIndexedSetter, int> indexed_setters_map; + Map<Variant::ValidatedIndexedGetter, int> indexed_getters_map; + Map<Variant::ValidatedBuiltInMethod, int> builtin_method_map; + Map<Variant::ValidatedConstructor, int> constructors_map; + Map<MethodBind *, int> method_bind_map; + + // Lists since these can be nested. + List<int> if_jmp_addrs; List<int> for_jmp_addrs; + List<Address> for_iterator_variables; + List<Address> for_counter_variables; + List<Address> for_container_variables; List<int> while_jmp_addrs; List<int> continue_addrs; @@ -76,6 +99,7 @@ class GDScriptByteCodeGenerator : public GDScriptCodeGenerator { List<List<int>> match_continues_to_patch; void add_stack_identifier(const StringName &p_id, int p_stackpos) { + current_locals++; stack_identifiers[p_id] = p_stackpos; if (debug_stack) { block_identifiers[p_id] = p_stackpos; @@ -89,17 +113,26 @@ class GDScriptByteCodeGenerator : public GDScriptCodeGenerator { } void push_stack_identifiers() { + stack_identifiers_counts.push_back(current_locals); stack_id_stack.push_back(stack_identifiers); if (debug_stack) { - block_identifier_stack.push_back(block_identifiers); + Map<StringName, int> block_ids(block_identifiers); + block_identifier_stack.push_back(block_ids); block_identifiers.clear(); } } void pop_stack_identifiers() { + current_locals = stack_identifiers_counts.back()->get(); + stack_identifiers_counts.pop_back(); stack_identifiers = stack_id_stack.back()->get(); - current_stack_size = stack_identifiers.size() + current_temporaries; stack_id_stack.pop_back(); +#ifdef DEBUG_ENABLED + if (current_temporaries != 0) { + ERR_PRINT("Leaving block with non-zero temporary variables: " + itos(current_temporaries)); + } +#endif + current_stack_size = current_locals; if (debug_stack) { for (Map<StringName, int>::Element *E = block_identifiers.front(); E; E = E->next()) { @@ -134,22 +167,105 @@ class GDScriptByteCodeGenerator : public GDScriptCodeGenerator { return pos; } + int get_operation_pos(const Variant::ValidatedOperatorEvaluator p_operation) { + if (operator_func_map.has(p_operation)) + return operator_func_map[p_operation]; + int pos = operator_func_map.size(); + operator_func_map[p_operation] = pos; + return pos; + } + + int get_setter_pos(const Variant::ValidatedSetter p_setter) { + if (setters_map.has(p_setter)) + return setters_map[p_setter]; + int pos = setters_map.size(); + setters_map[p_setter] = pos; + return pos; + } + + int get_getter_pos(const Variant::ValidatedGetter p_getter) { + if (getters_map.has(p_getter)) + return getters_map[p_getter]; + int pos = getters_map.size(); + getters_map[p_getter] = pos; + return pos; + } + + int get_keyed_setter_pos(const Variant::ValidatedKeyedSetter p_keyed_setter) { + if (keyed_setters_map.has(p_keyed_setter)) + return keyed_setters_map[p_keyed_setter]; + int pos = keyed_setters_map.size(); + keyed_setters_map[p_keyed_setter] = pos; + return pos; + } + + int get_keyed_getter_pos(const Variant::ValidatedKeyedGetter p_keyed_getter) { + if (keyed_getters_map.has(p_keyed_getter)) + return keyed_getters_map[p_keyed_getter]; + int pos = keyed_getters_map.size(); + keyed_getters_map[p_keyed_getter] = pos; + return pos; + } + + int get_indexed_setter_pos(const Variant::ValidatedIndexedSetter p_indexed_setter) { + if (indexed_setters_map.has(p_indexed_setter)) + return indexed_setters_map[p_indexed_setter]; + int pos = indexed_setters_map.size(); + indexed_setters_map[p_indexed_setter] = pos; + return pos; + } + + int get_indexed_getter_pos(const Variant::ValidatedIndexedGetter p_indexed_getter) { + if (indexed_getters_map.has(p_indexed_getter)) + return indexed_getters_map[p_indexed_getter]; + int pos = indexed_getters_map.size(); + indexed_getters_map[p_indexed_getter] = pos; + return pos; + } + + int get_builtin_method_pos(const Variant::ValidatedBuiltInMethod p_method) { + if (builtin_method_map.has(p_method)) { + return builtin_method_map[p_method]; + } + int pos = builtin_method_map.size(); + builtin_method_map[p_method] = pos; + return pos; + } + + int get_constructor_pos(const Variant::ValidatedConstructor p_constructor) { + if (constructors_map.has(p_constructor)) { + return constructors_map[p_constructor]; + } + int pos = constructors_map.size(); + constructors_map[p_constructor] = pos; + return pos; + } + + int get_method_bind_pos(MethodBind *p_method) { + if (method_bind_map.has(p_method)) { + return method_bind_map[p_method]; + } + int pos = method_bind_map.size(); + method_bind_map[p_method] = pos; + return pos; + } + void alloc_stack(int p_level) { if (p_level >= stack_max) stack_max = p_level + 1; } - void alloc_call(int p_params) { - if (p_params >= call_max) - call_max = p_params; - } - int increase_stack() { int top = current_stack_size++; alloc_stack(current_stack_size); return top; } + void alloc_ptrcall(int p_params) { + if (p_params >= ptrcall_max) + ptrcall_max = p_params; + } + int address_of(const Address &p_address) { switch (p_address.mode) { case Address::SELF: @@ -177,8 +293,13 @@ class GDScriptByteCodeGenerator : public GDScriptCodeGenerator { return -1; // Unreachable. } - void append(int code) { - opcodes.push_back(code); + void append(GDScriptFunction::Opcode p_code, int p_argument_count) { + opcodes.push_back((p_code & GDScriptFunction::INSTR_MASK) | (p_argument_count << GDScriptFunction::INSTR_BITS)); + instr_args_max = MAX(instr_args_max, p_argument_count); + } + + void append(int p_code) { + opcodes.push_back(p_code); } void append(const Address &p_address) { @@ -189,6 +310,46 @@ class GDScriptByteCodeGenerator : public GDScriptCodeGenerator { opcodes.push_back(get_name_map_pos(p_name)); } + void append(const Variant::ValidatedOperatorEvaluator p_operation) { + opcodes.push_back(get_operation_pos(p_operation)); + } + + void append(const Variant::ValidatedSetter p_setter) { + opcodes.push_back(get_setter_pos(p_setter)); + } + + void append(const Variant::ValidatedGetter p_getter) { + opcodes.push_back(get_getter_pos(p_getter)); + } + + void append(const Variant::ValidatedKeyedSetter p_keyed_setter) { + opcodes.push_back(get_keyed_setter_pos(p_keyed_setter)); + } + + void append(const Variant::ValidatedKeyedGetter p_keyed_getter) { + opcodes.push_back(get_keyed_getter_pos(p_keyed_getter)); + } + + void append(const Variant::ValidatedIndexedSetter p_indexed_setter) { + opcodes.push_back(get_indexed_setter_pos(p_indexed_setter)); + } + + void append(const Variant::ValidatedIndexedGetter p_indexed_getter) { + opcodes.push_back(get_indexed_getter_pos(p_indexed_getter)); + } + + void append(const Variant::ValidatedBuiltInMethod p_method) { + opcodes.push_back(get_builtin_method_pos(p_method)); + } + + void append(const Variant::ValidatedConstructor p_constructor) { + opcodes.push_back(get_constructor_pos(p_constructor)); + } + + void append(MethodBind *p_method) { + opcodes.push_back(get_method_bind_pos(p_method)); + } + void patch_jump(int p_address) { opcodes.write[p_address] = opcodes.size(); } @@ -216,7 +377,8 @@ public: #endif virtual void set_initial_line(int p_line) override; - virtual void write_operator(const Address &p_target, Variant::Operator p_operator, const Address &p_left_operand, const Address &p_right_operand) override; + virtual void write_unary_operator(const Address &p_target, Variant::Operator p_operator, const Address &p_left_operand) override; + virtual void write_binary_operator(const Address &p_target, Variant::Operator p_operator, const Address &p_left_operand, const Address &p_right_operand) override; virtual void write_type_test(const Address &p_target, const Address &p_source, const Address &p_type) override; virtual void write_type_test_builtin(const Address &p_target, const Address &p_source, Variant::Type p_type) override; virtual void write_and_left_operand(const Address &p_left_operand) override; @@ -245,8 +407,9 @@ public: virtual void write_super_call(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) override; virtual void write_call_async(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) override; virtual void write_call_builtin(const Address &p_target, GDScriptFunctions::Function p_function, const Vector<Address> &p_arguments) override; - virtual void write_call_method_bind(const Address &p_target, const Address &p_base, const MethodBind *p_method, const Vector<Address> &p_arguments) override; - virtual void write_call_ptrcall(const Address &p_target, const Address &p_base, const MethodBind *p_method, const Vector<Address> &p_arguments) override; + virtual void write_call_builtin_type(const Address &p_target, const Address &p_base, Variant::Type p_type, const StringName &p_method, const Vector<Address> &p_arguments) override; + virtual void write_call_method_bind(const Address &p_target, const Address &p_base, MethodBind *p_method, const Vector<Address> &p_arguments) override; + virtual void write_call_ptrcall(const Address &p_target, const Address &p_base, MethodBind *p_method, const Vector<Address> &p_arguments) override; virtual void write_call_self(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) override; virtual void write_call_script_function(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) override; virtual void write_construct(const Address &p_target, Variant::Type p_type, const Vector<Address> &p_arguments) override; @@ -256,7 +419,9 @@ public: virtual void write_if(const Address &p_condition) override; virtual void write_else() override; virtual void write_endif() override; - virtual void write_for(const Address &p_variable, const Address &p_list) override; + virtual void start_for(const GDScriptDataType &p_iterator_type, const GDScriptDataType &p_list_type) override; + virtual void write_for_assignment(const Address &p_variable, const Address &p_list) override; + virtual void write_for() override; virtual void write_endfor() override; virtual void start_while_condition() override; virtual void write_while(const Address &p_condition) override; diff --git a/modules/gdscript/gdscript_codegen.h b/modules/gdscript/gdscript_codegen.h index 76931ef0b5..559f9b8406 100644 --- a/modules/gdscript/gdscript_codegen.h +++ b/modules/gdscript/gdscript_codegen.h @@ -98,7 +98,8 @@ public: // virtual void alloc_stack(int p_level) = 0; // Is this needed? // virtual void alloc_call(int p_arg_count) = 0; // This might be automatic from other functions. - virtual void write_operator(const Address &p_target, Variant::Operator p_operator, const Address &p_left_operand, const Address &p_right_operand) = 0; + virtual void write_unary_operator(const Address &p_target, Variant::Operator p_operator, const Address &p_left_operand) = 0; + virtual void write_binary_operator(const Address &p_target, Variant::Operator p_operator, const Address &p_left_operand, const Address &p_right_operand) = 0; virtual void write_type_test(const Address &p_target, const Address &p_source, const Address &p_type) = 0; virtual void write_type_test_builtin(const Address &p_target, const Address &p_source, Variant::Type p_type) = 0; virtual void write_and_left_operand(const Address &p_left_operand) = 0; @@ -127,8 +128,9 @@ public: virtual void write_super_call(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) = 0; virtual void write_call_async(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) = 0; virtual void write_call_builtin(const Address &p_target, GDScriptFunctions::Function p_function, const Vector<Address> &p_arguments) = 0; - virtual void write_call_method_bind(const Address &p_target, const Address &p_base, const MethodBind *p_method, const Vector<Address> &p_arguments) = 0; - virtual void write_call_ptrcall(const Address &p_target, const Address &p_base, const MethodBind *p_method, const Vector<Address> &p_arguments) = 0; + virtual void write_call_builtin_type(const Address &p_target, const Address &p_base, Variant::Type p_type, const StringName &p_method, const Vector<Address> &p_arguments) = 0; + virtual void write_call_method_bind(const Address &p_target, const Address &p_base, MethodBind *p_method, const Vector<Address> &p_arguments) = 0; + virtual void write_call_ptrcall(const Address &p_target, const Address &p_base, MethodBind *p_method, const Vector<Address> &p_arguments) = 0; virtual void write_call_self(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) = 0; virtual void write_call_script_function(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) = 0; virtual void write_construct(const Address &p_target, Variant::Type p_type, const Vector<Address> &p_arguments) = 0; @@ -139,7 +141,9 @@ public: // virtual void write_elseif(const Address &p_condition) = 0; This kind of makes things more difficult for no real benefit. virtual void write_else() = 0; virtual void write_endif() = 0; - virtual void write_for(const Address &p_variable, const Address &p_list) = 0; + virtual void start_for(const GDScriptDataType &p_iterator_type, const GDScriptDataType &p_list_type) = 0; + virtual void write_for_assignment(const Address &p_variable, const Address &p_list) = 0; + virtual void write_for() = 0; virtual void write_endfor() = 0; virtual void start_while_condition() = 0; // Used to allow a jump to the expression evaluation. virtual void write_while(const Address &p_condition) = 0; diff --git a/modules/gdscript/gdscript_compiler.cpp b/modules/gdscript/gdscript_compiler.cpp index f75b3afa88..9c0528404b 100644 --- a/modules/gdscript/gdscript_compiler.cpp +++ b/modules/gdscript/gdscript_compiler.cpp @@ -158,6 +158,48 @@ GDScriptDataType GDScriptCompiler::_gdtype_from_datatype(const GDScriptParser::D return result; } +static bool _is_exact_type(const PropertyInfo &p_par_type, const GDScriptDataType &p_arg_type) { + if (!p_arg_type.has_type) { + return false; + } + if (p_par_type.type == Variant::NIL) { + return false; + } + if (p_par_type.type == Variant::OBJECT) { + if (p_arg_type.kind == GDScriptDataType::BUILTIN) { + return false; + } + StringName class_name; + if (p_arg_type.kind == GDScriptDataType::NATIVE) { + class_name = p_arg_type.native_type; + } else { + class_name = p_arg_type.native_type == StringName() ? p_arg_type.script_type->get_instance_base_type() : p_arg_type.native_type; + } + return p_par_type.class_name == class_name || ClassDB::is_parent_class(class_name, p_par_type.class_name); + } else { + if (p_arg_type.kind != GDScriptDataType::BUILTIN) { + return false; + } + return p_par_type.type == p_arg_type.builtin_type; + } +} + +static bool _have_exact_arguments(const MethodBind *p_method, const Vector<GDScriptCodeGenerator::Address> &p_arguments) { + if (p_method->get_argument_count() != p_arguments.size()) { + // ptrcall won't work with default arguments. + return false; + } + MethodInfo info; + ClassDB::get_method_info(p_method->get_instance_class(), p_method->get_name(), &info); + for (int i = 0; i < p_arguments.size(); i++) { + const PropertyInfo &prop = info.arguments[i]; + if (!_is_exact_type(prop, p_arguments[i].type)) { + return false; + } + } + return true; +} + GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &codegen, Error &r_error, const GDScriptParser::ExpressionNode *p_expression, bool p_root, bool p_initializer, const GDScriptCodeGenerator::Address &p_index_addr) { if (p_expression->is_constant) { return codegen.add_constant(p_expression->reduced_value); @@ -395,7 +437,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code gen->pop_temporary(); } - return source; + return result; } break; case GDScriptParser::Node::CALL: { const GDScriptParser::CallNode *call = static_cast<const GDScriptParser::CallNode *>(p_expression); @@ -430,7 +472,20 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code } else { if (callee->type == GDScriptParser::Node::IDENTIFIER) { // Self function call. - if ((codegen.function_node && codegen.function_node->is_static) || call->function_name == "new") { + if (ClassDB::has_method(codegen.script->native->get_name(), call->function_name)) { + // Native method, use faster path. + GDScriptCodeGenerator::Address self; + self.mode = GDScriptCodeGenerator::Address::SELF; + MethodBind *method = ClassDB::get_method(codegen.script->native->get_name(), call->function_name); + + if (_have_exact_arguments(method, arguments)) { + // Exact arguments, use ptrcall. + gen->write_call_ptrcall(result, self, method, arguments); + } else { + // Not exact arguments, but still can use method bind call. + gen->write_call_method_bind(result, self, method, arguments); + } + } else if ((codegen.function_node && codegen.function_node->is_static) || call->function_name == "new") { GDScriptCodeGenerator::Address self; self.mode = GDScriptCodeGenerator::Address::CLASS; gen->write_call(result, self, call->function_name, arguments); @@ -447,6 +502,28 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code } if (within_await) { gen->write_call_async(result, base, call->function_name, arguments); + } else if (base.type.has_type && base.type.kind != GDScriptDataType::BUILTIN) { + // Native method, use faster path. + StringName class_name; + if (base.type.kind == GDScriptDataType::NATIVE) { + class_name = base.type.native_type; + } else { + class_name = base.type.native_type == StringName() ? base.type.script_type->get_instance_base_type() : base.type.native_type; + } + if (ClassDB::class_exists(class_name) && ClassDB::has_method(class_name, call->function_name)) { + MethodBind *method = ClassDB::get_method(class_name, call->function_name); + if (_have_exact_arguments(method, arguments)) { + // Exact arguments, use ptrcall. + gen->write_call_ptrcall(result, base, method, arguments); + } else { + // Not exact arguments, but still can use method bind call. + gen->write_call_method_bind(result, base, method, arguments); + } + } else { + gen->write_call(result, base, call->function_name, arguments); + } + } else if (base.type.has_type && base.type.kind == GDScriptDataType::BUILTIN) { + gen->write_call_builtin_type(result, base, base.type.builtin_type, call->function_name, arguments); } else { gen->write_call(result, base, call->function_name, arguments); } @@ -493,7 +570,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(get_node->get_datatype())); MethodBind *get_node_method = ClassDB::get_method("Node", "get_node"); - gen->write_call_method_bind(result, GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::SELF), get_node_method, args); + gen->write_call_ptrcall(result, GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::SELF), get_node_method, args); return result; } break; @@ -600,7 +677,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code return GDScriptCodeGenerator::Address(); } - gen->write_operator(result, unary->variant_op, operand, GDScriptCodeGenerator::Address()); + gen->write_unary_operator(result, unary->variant_op, operand); if (operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) { gen->pop_temporary(); @@ -668,7 +745,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code GDScriptCodeGenerator::Address left_operand = _parse_expression(codegen, r_error, binary->left_operand); GDScriptCodeGenerator::Address right_operand = _parse_expression(codegen, r_error, binary->right_operand); - gen->write_operator(result, binary->variant_op, left_operand, right_operand); + gen->write_binary_operator(result, binary->variant_op, left_operand, right_operand); if (right_operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) { gen->pop_temporary(); @@ -831,7 +908,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code } else { gen->write_get(value, key, prev_base); } - gen->write_operator(value, assignment->variant_op, value, assigned); + gen->write_binary_operator(value, assignment->variant_op, value, assigned); if (assigned.mode == GDScriptCodeGenerator::Address::TEMPORARY) { gen->pop_temporary(); } @@ -889,7 +966,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code if (assignment->operation != GDScriptParser::AssignmentNode::OP_NONE) { GDScriptCodeGenerator::Address member = codegen.add_temporary(); gen->write_get_member(member, name); - gen->write_operator(assigned, assignment->variant_op, member, assigned); + gen->write_binary_operator(assigned, assignment->variant_op, member, assigned); gen->pop_temporary(); } @@ -939,7 +1016,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code if (assignment->operation != GDScriptParser::AssignmentNode::OP_NONE) { // Perform operation. op_result = codegen.add_temporary(); - gen->write_operator(op_result, assignment->variant_op, target, assigned); + gen->write_binary_operator(op_result, assignment->variant_op, target, assigned); } else { op_result = assigned; assigned = GDScriptCodeGenerator::Address(); @@ -995,7 +1072,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_match_pattern(CodeGen &c // Check type equality. GDScriptCodeGenerator::Address type_equality_addr = codegen.add_temporary(equality_type); - codegen.generator->write_operator(type_equality_addr, Variant::OP_EQUAL, p_type_addr, literal_type_addr); + codegen.generator->write_binary_operator(type_equality_addr, Variant::OP_EQUAL, p_type_addr, literal_type_addr); codegen.generator->write_and_left_operand(type_equality_addr); // Get literal. @@ -1006,7 +1083,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_match_pattern(CodeGen &c // Check value equality. GDScriptCodeGenerator::Address equality_addr = codegen.add_temporary(equality_type); - codegen.generator->write_operator(equality_addr, Variant::OP_EQUAL, p_value_addr, literal_addr); + codegen.generator->write_binary_operator(equality_addr, Variant::OP_EQUAL, p_value_addr, literal_addr); codegen.generator->write_and_right_operand(equality_addr); // AND both together (reuse temporary location). @@ -1058,11 +1135,11 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_match_pattern(CodeGen &c codegen.generator->write_call_builtin(result_addr, GDScriptFunctions::TYPE_OF, typeof_args); // Check type equality. - codegen.generator->write_operator(result_addr, Variant::OP_EQUAL, p_type_addr, result_addr); + codegen.generator->write_binary_operator(result_addr, Variant::OP_EQUAL, p_type_addr, result_addr); codegen.generator->write_and_left_operand(result_addr); // Check value equality. - codegen.generator->write_operator(result_addr, Variant::OP_EQUAL, p_value_addr, expr_addr); + codegen.generator->write_binary_operator(result_addr, Variant::OP_EQUAL, p_value_addr, expr_addr); codegen.generator->write_and_right_operand(equality_test_addr); // AND both type and value equality. @@ -1108,7 +1185,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_match_pattern(CodeGen &c // Check type equality. GDScriptCodeGenerator::Address result_addr = codegen.add_temporary(temp_type); - codegen.generator->write_operator(result_addr, Variant::OP_EQUAL, p_type_addr, array_type_addr); + codegen.generator->write_binary_operator(result_addr, Variant::OP_EQUAL, p_type_addr, array_type_addr); codegen.generator->write_and_left_operand(result_addr); // Store pattern length in constant map. @@ -1124,7 +1201,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_match_pattern(CodeGen &c // Test length compatibility. temp_type.builtin_type = Variant::BOOL; GDScriptCodeGenerator::Address length_compat_addr = codegen.add_temporary(temp_type); - codegen.generator->write_operator(length_compat_addr, p_pattern->rest_used ? Variant::OP_GREATER_EQUAL : Variant::OP_EQUAL, value_length_addr, array_length_addr); + codegen.generator->write_binary_operator(length_compat_addr, p_pattern->rest_used ? Variant::OP_GREATER_EQUAL : Variant::OP_EQUAL, value_length_addr, array_length_addr); codegen.generator->write_and_right_operand(length_compat_addr); // AND type and length check. @@ -1207,7 +1284,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_match_pattern(CodeGen &c // Check type equality. GDScriptCodeGenerator::Address result_addr = codegen.add_temporary(temp_type); - codegen.generator->write_operator(result_addr, Variant::OP_EQUAL, p_type_addr, dict_type_addr); + codegen.generator->write_binary_operator(result_addr, Variant::OP_EQUAL, p_type_addr, dict_type_addr); codegen.generator->write_and_left_operand(result_addr); // Store pattern length in constant map. @@ -1223,7 +1300,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_match_pattern(CodeGen &c // Test length compatibility. temp_type.builtin_type = Variant::BOOL; GDScriptCodeGenerator::Address length_compat_addr = codegen.add_temporary(temp_type); - codegen.generator->write_operator(length_compat_addr, p_pattern->rest_used ? Variant::OP_GREATER_EQUAL : Variant::OP_EQUAL, value_length_addr, dict_length_addr); + codegen.generator->write_binary_operator(length_compat_addr, p_pattern->rest_used ? Variant::OP_GREATER_EQUAL : Variant::OP_EQUAL, value_length_addr, dict_length_addr); codegen.generator->write_and_right_operand(length_compat_addr); // AND type and length check. @@ -1397,13 +1474,27 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui codegen.start_block(); // Evaluate the match expression. + GDScriptCodeGenerator::Address value_local = codegen.add_local("@match_value", _gdtype_from_datatype(match->test->get_datatype())); GDScriptCodeGenerator::Address value = _parse_expression(codegen, error, match->test); if (error) { return error; } + // Assign to local. + // TODO: This can be improved by passing the target to parse_expression(). + gen->write_assign(value_local, value); + + if (value.mode == GDScriptCodeGenerator::Address::TEMPORARY) { + codegen.generator->pop_temporary(); + } + // Then, let's save the type of the value in the stack too, so we can reuse for later comparisons. - GDScriptCodeGenerator::Address type = codegen.add_temporary(); + GDScriptDataType typeof_type; + typeof_type.has_type = true; + typeof_type.kind = GDScriptDataType::BUILTIN; + typeof_type.builtin_type = Variant::INT; + GDScriptCodeGenerator::Address type = codegen.add_local("@match_type", typeof_type); + Vector<GDScriptCodeGenerator::Address> typeof_args; typeof_args.push_back(value); gen->write_call_builtin(type, GDScriptFunctions::TYPE_OF, typeof_args); @@ -1457,12 +1548,6 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui gen->write_endif(); } - gen->pop_temporary(); - - if (value.mode == GDScriptCodeGenerator::Address::TEMPORARY) { - codegen.generator->pop_temporary(); - } - gen->end_match(); } break; case GDScriptParser::Node::IF: { @@ -1500,12 +1585,20 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui codegen.start_block(); GDScriptCodeGenerator::Address iterator = codegen.add_local(for_n->variable->name, _gdtype_from_datatype(for_n->variable->get_datatype())); + gen->start_for(iterator.type, _gdtype_from_datatype(for_n->list->get_datatype())); + GDScriptCodeGenerator::Address list = _parse_expression(codegen, error, for_n->list); if (error) { return error; } - gen->write_for(iterator, list); + gen->write_for_assignment(iterator, list); + + if (list.mode == GDScriptCodeGenerator::Address::TEMPORARY) { + codegen.generator->pop_temporary(); + } + + gen->write_for(); error = _parse_block(codegen, for_n->loop); if (error) { @@ -1514,10 +1607,6 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui gen->write_endfor(); - if (list.mode == GDScriptCodeGenerator::Address::TEMPORARY) { - codegen.generator->pop_temporary(); - } - codegen.end_block(); } break; case GDScriptParser::Node::WHILE: { @@ -1963,6 +2052,8 @@ Error GDScriptCompiler::_parse_class_level(GDScript *p_script, const GDScriptPar } p_script->member_indices = base->member_indices; + native = base->native; + p_script->native = native; } break; default: { _set_error("Parser bug: invalid inheritance.", p_class); diff --git a/modules/gdscript/gdscript_disassembler.cpp b/modules/gdscript/gdscript_disassembler.cpp new file mode 100644 index 0000000000..92a44c57f8 --- /dev/null +++ b/modules/gdscript/gdscript_disassembler.cpp @@ -0,0 +1,810 @@ +/*************************************************************************/ +/* gdscript_disassembler.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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. */ +/*************************************************************************/ + +#ifdef DEBUG_ENABLED + +#include "gdscript_function.h" + +#include "core/string/string_builder.h" +#include "gdscript.h" +#include "gdscript_functions.h" + +static String _get_variant_string(const Variant &p_variant) { + String txt; + if (p_variant.get_type() == Variant::STRING) { + txt = "\"" + String(p_variant) + "\""; + } else if (p_variant.get_type() == Variant::STRING_NAME) { + txt = "&\"" + String(p_variant) + "\""; + } else if (p_variant.get_type() == Variant::NODE_PATH) { + txt = "^\"" + String(p_variant) + "\""; + } else if (p_variant.get_type() == Variant::OBJECT) { + Object *obj = p_variant; + if (!obj) { + txt = "null"; + } else { + GDScriptNativeClass *cls = Object::cast_to<GDScriptNativeClass>(obj); + if (cls) { + txt += cls->get_name(); + txt += " (class)"; + } else { + txt = obj->get_class(); + if (obj->get_script_instance()) { + txt += "(" + obj->get_script_instance()->get_script()->get_path() + ")"; + } + } + } + } else { + txt = p_variant; + } + return txt; +} + +static String _disassemble_address(const GDScript *p_script, const GDScriptFunction &p_function, int p_address) { + int addr = p_address & GDScriptFunction::ADDR_MASK; + + switch (p_address >> GDScriptFunction::ADDR_BITS) { + case GDScriptFunction::ADDR_TYPE_SELF: { + return "self"; + } break; + case GDScriptFunction::ADDR_TYPE_CLASS: { + return "class"; + } break; + case GDScriptFunction::ADDR_TYPE_MEMBER: { + return "member(" + p_script->debug_get_member_by_index(addr) + ")"; + } break; + case GDScriptFunction::ADDR_TYPE_CLASS_CONSTANT: { + return "class_const(" + p_function.get_global_name(addr) + ")"; + } break; + case GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT: { + return "const(" + _get_variant_string(p_function.get_constant(addr)) + ")"; + } break; + case GDScriptFunction::ADDR_TYPE_STACK: { + return "stack(" + itos(addr) + ")"; + } break; + case GDScriptFunction::ADDR_TYPE_STACK_VARIABLE: { + return "var_stack(" + itos(addr) + ")"; + } break; + case GDScriptFunction::ADDR_TYPE_GLOBAL: { + return "global(" + _get_variant_string(GDScriptLanguage::get_singleton()->get_global_array()[addr]) + ")"; + } break; + case GDScriptFunction::ADDR_TYPE_NAMED_GLOBAL: { + return "named_global(" + p_function.get_global_name(addr) + ")"; + } break; + case GDScriptFunction::ADDR_TYPE_NIL: { + return "nil"; + } break; + } + + return "<err>"; +} + +void GDScriptFunction::disassemble(const Vector<String> &p_code_lines) const { +#define DADDR(m_ip) (_disassemble_address(_script, *this, _code_ptr[ip + m_ip])) + + for (int ip = 0; ip < _code_size;) { + StringBuilder text; + int incr = 0; + + text += " "; + text += itos(ip); + text += ": "; + + // This makes the compiler complain if some opcode is unchecked in the switch. + Opcode code = Opcode(_code_ptr[ip] & INSTR_MASK); + int instr_var_args = (_code_ptr[ip] & INSTR_ARGS_MASK) >> INSTR_BITS; + + switch (code) { + case OPCODE_OPERATOR: { + int operation = _code_ptr[ip + 4]; + + text += "operator "; + + text += DADDR(3); + text += " = "; + text += DADDR(1); + text += " "; + text += Variant::get_operator_name(Variant::Operator(operation)); + text += " "; + text += DADDR(2); + + incr += 5; + } break; + case OPCODE_OPERATOR_VALIDATED: { + text += "validated operator "; + + text += DADDR(3); + text += " = "; + text += DADDR(1); + text += " <operator function> "; + text += DADDR(2); + + incr += 5; + } break; + case OPCODE_EXTENDS_TEST: { + text += "is object "; + text += DADDR(3); + text += " = "; + text += DADDR(1); + text += " is "; + text += DADDR(2); + + incr += 4; + } break; + case OPCODE_IS_BUILTIN: { + text += "is builtin "; + text += DADDR(2); + text += " = "; + text += DADDR(1); + text += " is "; + text += Variant::get_type_name(Variant::Type(_code_ptr[ip + 3])); + + incr += 4; + } break; + case OPCODE_SET_KEYED: { + text += "set keyed "; + text += DADDR(1); + text += "["; + text += DADDR(2); + text += "] = "; + text += DADDR(3); + + incr += 4; + } break; + case OPCODE_SET_KEYED_VALIDATED: { + text += "set keyed validated "; + text += DADDR(1); + text += "["; + text += DADDR(2); + text += "] = "; + text += DADDR(3); + + incr += 5; + } break; + case OPCODE_SET_INDEXED_VALIDATED: { + text += "set indexed validated "; + text += DADDR(1); + text += "["; + text += DADDR(2); + text += "] = "; + text += DADDR(3); + + incr += 5; + } break; + case OPCODE_GET_KEYED: { + text += "get keyed "; + text += DADDR(3); + text += " = "; + text += DADDR(1); + text += "["; + text += DADDR(2); + text += "]"; + + incr += 4; + } break; + case OPCODE_GET_KEYED_VALIDATED: { + text += "get keyed validated "; + text += DADDR(3); + text += " = "; + text += DADDR(1); + text += "["; + text += DADDR(2); + text += "]"; + + incr += 5; + } break; + case OPCODE_GET_INDEXED_VALIDATED: { + text += "get indexed validated "; + text += DADDR(3); + text += " = "; + text += DADDR(1); + text += "["; + text += DADDR(2); + text += "]"; + + incr += 5; + } break; + case OPCODE_SET_NAMED: { + text += "set_named "; + text += DADDR(1); + text += "[\""; + text += _global_names_ptr[_code_ptr[ip + 3]]; + text += "\"] = "; + text += DADDR(2); + + incr += 4; + } break; + case OPCODE_SET_NAMED_VALIDATED: { + text += "set_named validated "; + text += DADDR(1); + text += "[\""; + text += "<unknown name>"; + text += "\"] = "; + text += DADDR(2); + + incr += 4; + } break; + case OPCODE_GET_NAMED: { + text += "get_named "; + text += DADDR(2); + text += " = "; + text += DADDR(1); + text += "[\""; + text += _global_names_ptr[_code_ptr[ip + 3]]; + text += "\"]"; + + incr += 4; + } break; + case OPCODE_GET_NAMED_VALIDATED: { + text += "get_named validated "; + text += DADDR(2); + text += " = "; + text += DADDR(1); + text += "[\""; + text += "<unknown name>"; + text += "\"]"; + + incr += 4; + } break; + case OPCODE_SET_MEMBER: { + text += "set_member "; + text += "[\""; + text += _global_names_ptr[_code_ptr[ip + 2]]; + text += "\"] = "; + text += DADDR(1); + + incr += 3; + } break; + case OPCODE_GET_MEMBER: { + text += "get_member "; + text += DADDR(1); + text += " = "; + text += "[\""; + text += _global_names_ptr[_code_ptr[ip + 2]]; + text += "\"]"; + + incr += 3; + } break; + case OPCODE_ASSIGN: { + text += "assign "; + text += DADDR(1); + text += " = "; + text += DADDR(2); + + incr += 3; + } break; + case OPCODE_ASSIGN_TRUE: { + text += "assign "; + text += DADDR(1); + text += " = true"; + + incr += 2; + } break; + case OPCODE_ASSIGN_FALSE: { + text += "assign "; + text += DADDR(1); + text += " = false"; + + incr += 2; + } break; + case OPCODE_ASSIGN_TYPED_BUILTIN: { + text += "assign typed builtin ("; + text += Variant::get_type_name((Variant::Type)_code_ptr[ip + 3]); + text += ") "; + text += DADDR(1); + text += " = "; + text += DADDR(2); + + incr += 4; + } break; + case OPCODE_ASSIGN_TYPED_NATIVE: { + Variant class_name = _constants_ptr[_code_ptr[ip + 3]]; + GDScriptNativeClass *nc = Object::cast_to<GDScriptNativeClass>(class_name.operator Object *()); + + text += "assign typed native ("; + text += nc->get_name().operator String(); + text += ") "; + text += DADDR(1); + text += " = "; + text += DADDR(2); + + incr += 4; + } break; + case OPCODE_ASSIGN_TYPED_SCRIPT: { + Variant script = _constants_ptr[_code_ptr[ip + 3]]; + Script *sc = Object::cast_to<Script>(script.operator Object *()); + + text += "assign typed script ("; + text += sc->get_path(); + text += ") "; + text += DADDR(1); + text += " = "; + text += DADDR(2); + + incr += 4; + } break; + case OPCODE_CAST_TO_BUILTIN: { + text += "cast builtin "; + text += DADDR(2); + text += " = "; + text += DADDR(1); + text += " as "; + text += Variant::get_type_name(Variant::Type(_code_ptr[ip + 1])); + + incr += 4; + } break; + case OPCODE_CAST_TO_NATIVE: { + text += "cast native "; + text += DADDR(2); + text += " = "; + text += DADDR(1); + text += " as "; + text += DADDR(3); + + incr += 4; + } break; + case OPCODE_CAST_TO_SCRIPT: { + text += "cast "; + text += DADDR(2); + text += " = "; + text += DADDR(1); + text += " as "; + text += DADDR(3); + + incr += 4; + } break; + case OPCODE_CONSTRUCT: { + Variant::Type t = Variant::Type(_code_ptr[ip + 3 + instr_var_args]); + int argc = _code_ptr[ip + 1 + instr_var_args]; + + text += "construct "; + text += DADDR(1 + argc); + text += " = "; + + text += Variant::get_type_name(t) + "("; + for (int i = 0; i < argc; i++) { + if (i > 0) + text += ", "; + text += DADDR(i + 1); + } + text += ")"; + + incr = 3 + instr_var_args; + } break; + case OPCODE_CONSTRUCT_VALIDATED: { + int argc = _code_ptr[ip + 1 + instr_var_args]; + + text += "construct validated "; + text += DADDR(1 + argc); + text += " = "; + + text += "<unkown type>("; + for (int i = 0; i < argc; i++) { + if (i > 0) + text += ", "; + text += DADDR(i + 1); + } + text += ")"; + + incr = 3 + instr_var_args; + } break; + case OPCODE_CONSTRUCT_ARRAY: { + int argc = _code_ptr[ip + 1 + instr_var_args]; + text += " make_array "; + text += DADDR(1 + argc); + text += " = ["; + + for (int i = 0; i < argc; i++) { + if (i > 0) + text += ", "; + text += DADDR(1 + i); + } + + text += "]"; + + incr += 3 + argc; + } break; + case OPCODE_CONSTRUCT_DICTIONARY: { + int argc = _code_ptr[ip + 1 + instr_var_args]; + text += "make_dict "; + text += DADDR(1 + argc * 2); + text += " = {"; + + for (int i = 0; i < argc; i++) { + if (i > 0) + text += ", "; + text += DADDR(1 + i * 2 + 0); + text += ": "; + text += DADDR(1 + i * 2 + 1); + } + + text += "}"; + + incr += 3 + argc * 2; + } break; + case OPCODE_CALL: + case OPCODE_CALL_RETURN: + case OPCODE_CALL_ASYNC: { + bool ret = (_code_ptr[ip] & INSTR_MASK) == OPCODE_CALL_RETURN; + bool async = (_code_ptr[ip] & INSTR_MASK) == OPCODE_CALL_ASYNC; + + if (ret) { + text += "call-ret "; + } else if (async) { + text += "call-async "; + } else { + text += "call "; + } + + int argc = _code_ptr[ip + 1 + instr_var_args]; + if (ret || async) { + text += DADDR(2 + argc) + " = "; + } + + text += DADDR(1 + argc) + "."; + text += String(_global_names_ptr[_code_ptr[ip + 2 + instr_var_args]]); + text += "("; + + for (int i = 0; i < argc; i++) { + if (i > 0) + text += ", "; + text += DADDR(1 + i); + } + text += ")"; + + incr = 5 + argc; + } break; + case OPCODE_CALL_METHOD_BIND: + case OPCODE_CALL_METHOD_BIND_RET: { + bool ret = (_code_ptr[ip] & INSTR_MASK) == OPCODE_CALL_METHOD_BIND_RET; + + if (ret) { + text += "call-method_bind-ret "; + } else { + text += "call-method_bind "; + } + + MethodBind *method = _methods_ptr[_code_ptr[ip + 2 + instr_var_args]]; + + int argc = _code_ptr[ip + 1 + instr_var_args]; + if (ret) { + text += DADDR(2 + argc) + " = "; + } + + text += DADDR(1 + argc) + "."; + text += method->get_name(); + text += "("; + + for (int i = 0; i < argc; i++) { + if (i > 0) + text += ", "; + text += DADDR(1 + i); + } + text += ")"; + + incr = 5 + argc; + } break; + case OPCODE_CALL_PTRCALL_NO_RETURN: { + text += "call-ptrcall (no return) "; + + MethodBind *method = _methods_ptr[_code_ptr[ip + 2 + instr_var_args]]; + + int argc = _code_ptr[ip + 1 + instr_var_args]; + + text += DADDR(1 + argc) + "."; + text += method->get_name(); + text += "("; + + for (int i = 0; i < argc; i++) { + if (i > 0) + text += ", "; + text += DADDR(1 + i); + } + text += ")"; + + incr = 5 + argc; + } break; + +#define DISASSEMBLE_PTRCALL(m_type) \ + case OPCODE_CALL_PTRCALL_##m_type: { \ + text += "call-ptrcall (return "; \ + text += #m_type; \ + text += ") "; \ + MethodBind *method = _methods_ptr[_code_ptr[ip + 2 + instr_var_args]]; \ + int argc = _code_ptr[ip + 1 + instr_var_args]; \ + text += DADDR(2 + argc) + " = "; \ + text += DADDR(1 + argc) + "."; \ + text += method->get_name(); \ + text += "("; \ + for (int i = 0; i < argc; i++) { \ + if (i > 0) \ + text += ", "; \ + text += DADDR(1 + i); \ + } \ + text += ")"; \ + incr = 5 + argc; \ + } break + + DISASSEMBLE_PTRCALL(BOOL); + DISASSEMBLE_PTRCALL(INT); + DISASSEMBLE_PTRCALL(FLOAT); + DISASSEMBLE_PTRCALL(STRING); + DISASSEMBLE_PTRCALL(VECTOR2); + DISASSEMBLE_PTRCALL(VECTOR2I); + DISASSEMBLE_PTRCALL(RECT2); + DISASSEMBLE_PTRCALL(RECT2I); + DISASSEMBLE_PTRCALL(VECTOR3); + DISASSEMBLE_PTRCALL(VECTOR3I); + DISASSEMBLE_PTRCALL(TRANSFORM2D); + DISASSEMBLE_PTRCALL(PLANE); + DISASSEMBLE_PTRCALL(AABB); + DISASSEMBLE_PTRCALL(BASIS); + DISASSEMBLE_PTRCALL(TRANSFORM); + DISASSEMBLE_PTRCALL(COLOR); + DISASSEMBLE_PTRCALL(STRING_NAME); + DISASSEMBLE_PTRCALL(NODE_PATH); + DISASSEMBLE_PTRCALL(RID); + DISASSEMBLE_PTRCALL(QUAT); + DISASSEMBLE_PTRCALL(OBJECT); + DISASSEMBLE_PTRCALL(CALLABLE); + DISASSEMBLE_PTRCALL(SIGNAL); + DISASSEMBLE_PTRCALL(DICTIONARY); + DISASSEMBLE_PTRCALL(ARRAY); + DISASSEMBLE_PTRCALL(PACKED_BYTE_ARRAY); + DISASSEMBLE_PTRCALL(PACKED_INT32_ARRAY); + DISASSEMBLE_PTRCALL(PACKED_INT64_ARRAY); + DISASSEMBLE_PTRCALL(PACKED_FLOAT32_ARRAY); + DISASSEMBLE_PTRCALL(PACKED_FLOAT64_ARRAY); + DISASSEMBLE_PTRCALL(PACKED_STRING_ARRAY); + DISASSEMBLE_PTRCALL(PACKED_VECTOR2_ARRAY); + DISASSEMBLE_PTRCALL(PACKED_VECTOR3_ARRAY); + DISASSEMBLE_PTRCALL(PACKED_COLOR_ARRAY); + + case OPCODE_CALL_BUILTIN_TYPE_VALIDATED: { + int argc = _code_ptr[ip + 1 + instr_var_args]; + + text += "call-builtin-method validated "; + + text += DADDR(2 + argc) + " = "; + + text += DADDR(1) + "."; + text += "<unknown method>"; + + text += "("; + + for (int i = 0; i < argc; i++) { + if (i > 0) + text += ", "; + text += DADDR(1 + i); + } + text += ")"; + + incr = 5 + argc; + } break; + case OPCODE_CALL_BUILT_IN: { + text += "call-built-in "; + + int argc = _code_ptr[ip + 1 + instr_var_args]; + text += DADDR(1 + argc) + " = "; + + text += GDScriptFunctions::get_func_name(GDScriptFunctions::Function(_code_ptr[ip + 2 + instr_var_args])); + text += "("; + + for (int i = 0; i < argc; i++) { + if (i > 0) + text += ", "; + text += DADDR(1 + i); + } + text += ")"; + + incr = 4 + argc; + } break; + case OPCODE_CALL_SELF_BASE: { + text += "call-self-base "; + + int argc = _code_ptr[ip + 1 + instr_var_args]; + text += DADDR(2 + argc) + " = "; + + text += _global_names_ptr[_code_ptr[ip + 2 + instr_var_args]]; + text += "("; + + for (int i = 0; i < argc; i++) { + if (i > 0) + text += ", "; + text += DADDR(1 + i); + } + text += ")"; + + incr = 4 + argc; + } break; + case OPCODE_AWAIT: { + text += "await "; + text += DADDR(1); + + incr += 2; + } break; + case OPCODE_AWAIT_RESUME: { + text += "await resume "; + text += DADDR(1); + + incr = 2; + } break; + case OPCODE_JUMP: { + text += "jump "; + text += itos(_code_ptr[ip + 1]); + + incr = 2; + } break; + case OPCODE_JUMP_IF: { + text += "jump-if "; + text += DADDR(1); + text += " to "; + text += itos(_code_ptr[ip + 2]); + + incr = 3; + } break; + case OPCODE_JUMP_IF_NOT: { + text += "jump-if-not "; + text += DADDR(1); + text += " to "; + text += itos(_code_ptr[ip + 2]); + + incr = 3; + } break; + case OPCODE_JUMP_TO_DEF_ARGUMENT: { + text += "jump-to-default-argument "; + + incr = 1; + } break; + case OPCODE_RETURN: { + text += "return "; + text += DADDR(1); + + incr = 2; + } break; + +#define DISASSEMBLE_ITERATE(m_type) \ + case OPCODE_ITERATE_##m_type: { \ + text += "for-loop (typed "; \ + text += #m_type; \ + text += ") "; \ + text += DADDR(3); \ + text += " in "; \ + text += DADDR(2); \ + text += " counter "; \ + text += DADDR(1); \ + text += " end "; \ + text += itos(_code_ptr[ip + 4]); \ + incr += 5; \ + } break + +#define DISASSEMBLE_ITERATE_BEGIN(m_type) \ + case OPCODE_ITERATE_BEGIN_##m_type: { \ + text += "for-init (typed "; \ + text += #m_type; \ + text += ") "; \ + text += DADDR(3); \ + text += " in "; \ + text += DADDR(2); \ + text += " counter "; \ + text += DADDR(1); \ + text += " end "; \ + text += itos(_code_ptr[ip + 4]); \ + incr += 5; \ + } break + +#define DISASSEMBLE_ITERATE_TYPES(m_macro) \ + m_macro(INT); \ + m_macro(FLOAT); \ + m_macro(VECTOR2); \ + m_macro(VECTOR2I); \ + m_macro(VECTOR3); \ + m_macro(VECTOR3I); \ + m_macro(STRING); \ + m_macro(DICTIONARY); \ + m_macro(ARRAY); \ + m_macro(PACKED_BYTE_ARRAY); \ + m_macro(PACKED_INT32_ARRAY); \ + m_macro(PACKED_INT64_ARRAY); \ + m_macro(PACKED_FLOAT32_ARRAY); \ + m_macro(PACKED_FLOAT64_ARRAY); \ + m_macro(PACKED_STRING_ARRAY); \ + m_macro(PACKED_VECTOR2_ARRAY); \ + m_macro(PACKED_VECTOR3_ARRAY); \ + m_macro(PACKED_COLOR_ARRAY); \ + m_macro(OBJECT) + + case OPCODE_ITERATE_BEGIN: { + text += "for-init "; + text += DADDR(3); + text += " in "; + text += DADDR(2); + text += " counter "; + text += DADDR(1); + text += " end "; + text += itos(_code_ptr[ip + 4]); + + incr += 5; + } break; + DISASSEMBLE_ITERATE_TYPES(DISASSEMBLE_ITERATE_BEGIN); + case OPCODE_ITERATE: { + text += "for-loop "; + text += DADDR(2); + text += " in "; + text += DADDR(2); + text += " counter "; + text += DADDR(1); + text += " end "; + text += itos(_code_ptr[ip + 4]); + + incr += 5; + } break; + DISASSEMBLE_ITERATE_TYPES(DISASSEMBLE_ITERATE); + case OPCODE_LINE: { + int line = _code_ptr[ip + 1] - 1; + if (line >= 0 && line < p_code_lines.size()) { + text += "line "; + text += itos(line + 1); + text += ": "; + text += p_code_lines[line]; + } else { + text += ""; + } + + incr += 2; + } break; + case OPCODE_ASSERT: { + text += "assert ("; + text += DADDR(1); + text += ", "; + text += DADDR(2); + text += ")"; + + incr += 3; + } break; + case OPCODE_BREAKPOINT: { + text += "breakpoint"; + + incr += 1; + } break; + case OPCODE_END: { + text += "== END =="; + + incr += 1; + } break; + } + + ip += incr; + if (text.get_string_length() > 0) { + print_line(text.as_string()); + } + } +} + +#endif diff --git a/modules/gdscript/gdscript_function.cpp b/modules/gdscript/gdscript_function.cpp index 8372672cf7..32372439c5 100644 --- a/modules/gdscript/gdscript_function.cpp +++ b/modules/gdscript/gdscript_function.cpp @@ -30,1574 +30,7 @@ #include "gdscript_function.h" -#include "core/os/os.h" #include "gdscript.h" -#include "gdscript_functions.h" - -#ifdef DEBUG_ENABLED -#include "core/string/string_builder.h" -#endif - -Variant *GDScriptFunction::_get_variant(int p_address, GDScriptInstance *p_instance, GDScript *p_script, Variant &self, Variant &static_ref, Variant *p_stack, String &r_error) const { - int address = p_address & ADDR_MASK; - - //sequential table (jump table generated by compiler) - switch ((p_address & ADDR_TYPE_MASK) >> ADDR_BITS) { - case ADDR_TYPE_SELF: { -#ifdef DEBUG_ENABLED - if (unlikely(!p_instance)) { - r_error = "Cannot access self without instance."; - return nullptr; - } -#endif - return &self; - } break; - case ADDR_TYPE_CLASS: { - return &static_ref; - } break; - case ADDR_TYPE_MEMBER: { -#ifdef DEBUG_ENABLED - if (unlikely(!p_instance)) { - r_error = "Cannot access member without instance."; - return nullptr; - } -#endif - //member indexing is O(1) - return &p_instance->members.write[address]; - } break; - case ADDR_TYPE_CLASS_CONSTANT: { - //todo change to index! - GDScript *s = p_script; -#ifdef DEBUG_ENABLED - ERR_FAIL_INDEX_V(address, _global_names_count, nullptr); -#endif - const StringName *sn = &_global_names_ptr[address]; - - while (s) { - GDScript *o = s; - while (o) { - Map<StringName, Variant>::Element *E = o->constants.find(*sn); - if (E) { - return &E->get(); - } - o = o->_owner; - } - s = s->_base; - } - - ERR_FAIL_V_MSG(nullptr, "GDScriptCompiler bug."); - } break; - case ADDR_TYPE_LOCAL_CONSTANT: { -#ifdef DEBUG_ENABLED - ERR_FAIL_INDEX_V(address, _constant_count, nullptr); -#endif - return &_constants_ptr[address]; - } break; - case ADDR_TYPE_STACK: - case ADDR_TYPE_STACK_VARIABLE: { -#ifdef DEBUG_ENABLED - ERR_FAIL_INDEX_V(address, _stack_size, nullptr); -#endif - return &p_stack[address]; - } break; - case ADDR_TYPE_GLOBAL: { -#ifdef DEBUG_ENABLED - ERR_FAIL_INDEX_V(address, GDScriptLanguage::get_singleton()->get_global_array_size(), nullptr); -#endif - return &GDScriptLanguage::get_singleton()->get_global_array()[address]; - } break; -#ifdef TOOLS_ENABLED - case ADDR_TYPE_NAMED_GLOBAL: { -#ifdef DEBUG_ENABLED - ERR_FAIL_INDEX_V(address, _global_names_count, nullptr); -#endif - StringName id = _global_names_ptr[address]; - - if (GDScriptLanguage::get_singleton()->get_named_globals_map().has(id)) { - return (Variant *)&GDScriptLanguage::get_singleton()->get_named_globals_map()[id]; - } else { - r_error = "Autoload singleton '" + String(id) + "' has been removed."; - return nullptr; - } - } break; -#endif - case ADDR_TYPE_NIL: { - return &nil; - } break; - } - - ERR_FAIL_V_MSG(nullptr, "Bad code! (unknown addressing mode)."); - return nullptr; -} - -#ifdef DEBUG_ENABLED -static String _get_var_type(const Variant *p_var) { - String basestr; - - if (p_var->get_type() == Variant::OBJECT) { - bool was_freed; - Object *bobj = p_var->get_validated_object_with_check(was_freed); - if (!bobj) { - if (was_freed) { - basestr = "null instance"; - } else { - basestr = "previously freed"; - } - } else { - if (bobj->get_script_instance()) { - basestr = bobj->get_class() + " (" + bobj->get_script_instance()->get_script()->get_path().get_file() + ")"; - } else { - basestr = bobj->get_class(); - } - } - - } else { - basestr = Variant::get_type_name(p_var->get_type()); - } - - return basestr; -} -#endif // DEBUG_ENABLED - -String GDScriptFunction::_get_call_error(const Callable::CallError &p_err, const String &p_where, const Variant **argptrs) const { - String err_text; - - if (p_err.error == Callable::CallError::CALL_ERROR_INVALID_ARGUMENT) { - int errorarg = p_err.argument; - // Handle the Object to Object case separately as we don't have further class details. -#ifdef DEBUG_ENABLED - if (p_err.expected == Variant::OBJECT && argptrs[errorarg]->get_type() == p_err.expected) { - err_text = "Invalid type in " + p_where + ". The Object-derived class of argument " + itos(errorarg + 1) + " (" + _get_var_type(argptrs[errorarg]) + ") is not a subclass of the expected argument class."; - } else -#endif // DEBUG_ENABLED - { - err_text = "Invalid type in " + p_where + ". Cannot convert argument " + itos(errorarg + 1) + " from " + Variant::get_type_name(argptrs[errorarg]->get_type()) + " to " + Variant::get_type_name(Variant::Type(p_err.expected)) + "."; - } - } else if (p_err.error == Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) { - err_text = "Invalid call to " + p_where + ". Expected " + itos(p_err.argument) + " arguments."; - } else if (p_err.error == Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) { - err_text = "Invalid call to " + p_where + ". Expected " + itos(p_err.argument) + " arguments."; - } else if (p_err.error == Callable::CallError::CALL_ERROR_INVALID_METHOD) { - err_text = "Invalid call. Nonexistent " + p_where + "."; - } else if (p_err.error == Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL) { - err_text = "Attempt to call " + p_where + " on a null instance."; - } else { - err_text = "Bug, call error: #" + itos(p_err.error); - } - - return err_text; -} - -#if defined(__GNUC__) -#define OPCODES_TABLE \ - static const void *switch_table_ops[] = { \ - &&OPCODE_OPERATOR, \ - &&OPCODE_EXTENDS_TEST, \ - &&OPCODE_IS_BUILTIN, \ - &&OPCODE_SET, \ - &&OPCODE_GET, \ - &&OPCODE_SET_NAMED, \ - &&OPCODE_GET_NAMED, \ - &&OPCODE_SET_MEMBER, \ - &&OPCODE_GET_MEMBER, \ - &&OPCODE_ASSIGN, \ - &&OPCODE_ASSIGN_TRUE, \ - &&OPCODE_ASSIGN_FALSE, \ - &&OPCODE_ASSIGN_TYPED_BUILTIN, \ - &&OPCODE_ASSIGN_TYPED_NATIVE, \ - &&OPCODE_ASSIGN_TYPED_SCRIPT, \ - &&OPCODE_CAST_TO_BUILTIN, \ - &&OPCODE_CAST_TO_NATIVE, \ - &&OPCODE_CAST_TO_SCRIPT, \ - &&OPCODE_CONSTRUCT, \ - &&OPCODE_CONSTRUCT_ARRAY, \ - &&OPCODE_CONSTRUCT_DICTIONARY, \ - &&OPCODE_CALL, \ - &&OPCODE_CALL_RETURN, \ - &&OPCODE_CALL_ASYNC, \ - &&OPCODE_CALL_BUILT_IN, \ - &&OPCODE_CALL_SELF_BASE, \ - &&OPCODE_AWAIT, \ - &&OPCODE_AWAIT_RESUME, \ - &&OPCODE_JUMP, \ - &&OPCODE_JUMP_IF, \ - &&OPCODE_JUMP_IF_NOT, \ - &&OPCODE_JUMP_TO_DEF_ARGUMENT, \ - &&OPCODE_RETURN, \ - &&OPCODE_ITERATE_BEGIN, \ - &&OPCODE_ITERATE, \ - &&OPCODE_ASSERT, \ - &&OPCODE_BREAKPOINT, \ - &&OPCODE_LINE, \ - &&OPCODE_END \ - }; \ - static_assert((sizeof(switch_table_ops) / sizeof(switch_table_ops[0]) == (OPCODE_END + 1)), "Opcodes in jump table aren't the same as opcodes in enum."); - -#define OPCODE(m_op) \ - m_op: -#define OPCODE_WHILE(m_test) -#define OPCODES_END \ - OPSEXIT: -#define OPCODES_OUT \ - OPSOUT: -#define DISPATCH_OPCODE goto *switch_table_ops[_code_ptr[ip]] -#define OPCODE_SWITCH(m_test) DISPATCH_OPCODE; -#define OPCODE_BREAK goto OPSEXIT -#define OPCODE_OUT goto OPSOUT -#else -#define OPCODES_TABLE -#define OPCODE(m_op) case m_op: -#define OPCODE_WHILE(m_test) while (m_test) -#define OPCODES_END -#define OPCODES_OUT -#define DISPATCH_OPCODE continue -#define OPCODE_SWITCH(m_test) switch (m_test) -#define OPCODE_BREAK break -#define OPCODE_OUT break -#endif - -Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_args, int p_argcount, Callable::CallError &r_err, CallState *p_state) { - OPCODES_TABLE; - - if (!_code_ptr) { - return Variant(); - } - - r_err.error = Callable::CallError::CALL_OK; - - Variant self; - Variant static_ref; - Variant retvalue; - Variant *stack = nullptr; - Variant **call_args; - int defarg = 0; - -#ifdef DEBUG_ENABLED - - //GDScriptLanguage::get_singleton()->calls++; - -#endif - - uint32_t alloca_size = 0; - GDScript *script; - int ip = 0; - int line = _initial_line; - - if (p_state) { - //use existing (supplied) state (awaited) - stack = (Variant *)p_state->stack.ptr(); - call_args = (Variant **)&p_state->stack.ptr()[sizeof(Variant) * p_state->stack_size]; //ptr() to avoid bounds check - line = p_state->line; - ip = p_state->ip; - alloca_size = p_state->stack.size(); - script = p_state->script; - p_instance = p_state->instance; - defarg = p_state->defarg; - self = p_state->self; - - } else { - if (p_argcount != _argument_count) { - if (p_argcount > _argument_count) { - r_err.error = Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; - r_err.argument = _argument_count; - - return Variant(); - } else if (p_argcount < _argument_count - _default_arg_count) { - r_err.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; - r_err.argument = _argument_count - _default_arg_count; - return Variant(); - } else { - defarg = _argument_count - p_argcount; - } - } - - alloca_size = sizeof(Variant *) * _call_size + sizeof(Variant) * _stack_size; - - if (alloca_size) { - uint8_t *aptr = (uint8_t *)alloca(alloca_size); - - if (_stack_size) { - stack = (Variant *)aptr; - for (int i = 0; i < p_argcount; i++) { - if (!argument_types[i].has_type) { - memnew_placement(&stack[i], Variant(*p_args[i])); - continue; - } - - if (!argument_types[i].is_type(*p_args[i], true)) { - r_err.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_err.argument = i; - r_err.expected = argument_types[i].kind == GDScriptDataType::BUILTIN ? argument_types[i].builtin_type : Variant::OBJECT; - return Variant(); - } - if (argument_types[i].kind == GDScriptDataType::BUILTIN) { - Variant arg; - Variant::construct(argument_types[i].builtin_type, arg, &p_args[i], 1, r_err); - memnew_placement(&stack[i], Variant(arg)); - } else { - memnew_placement(&stack[i], Variant(*p_args[i])); - } - } - for (int i = p_argcount; i < _stack_size; i++) { - memnew_placement(&stack[i], Variant); - } - } else { - stack = nullptr; - } - - if (_call_size) { - call_args = (Variant **)&aptr[sizeof(Variant) * _stack_size]; - } else { - call_args = nullptr; - } - - } else { - stack = nullptr; - call_args = nullptr; - } - - if (p_instance) { - if (p_instance->base_ref && static_cast<Reference *>(p_instance->owner)->is_referenced()) { - self = REF(static_cast<Reference *>(p_instance->owner)); - } else { - self = p_instance->owner; - } - script = p_instance->script.ptr(); - } else { - script = _script; - } - } - - static_ref = script; - - String err_text; - -#ifdef DEBUG_ENABLED - - if (EngineDebugger::is_active()) { - GDScriptLanguage::get_singleton()->enter_function(p_instance, this, stack, &ip, &line); - } - -#define GD_ERR_BREAK(m_cond) \ - { \ - if (unlikely(m_cond)) { \ - _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Condition ' " _STR(m_cond) " ' is true. Breaking..:"); \ - OPCODE_BREAK; \ - } \ - } - -#define CHECK_SPACE(m_space) \ - GD_ERR_BREAK((ip + m_space) > _code_size) - -#define GET_VARIANT_PTR(m_v, m_code_ofs) \ - Variant *m_v; \ - m_v = _get_variant(_code_ptr[ip + m_code_ofs], p_instance, script, self, static_ref, stack, err_text); \ - if (unlikely(!m_v)) \ - OPCODE_BREAK; - -#else -#define GD_ERR_BREAK(m_cond) -#define CHECK_SPACE(m_space) -#define GET_VARIANT_PTR(m_v, m_code_ofs) \ - Variant *m_v; \ - m_v = _get_variant(_code_ptr[ip + m_code_ofs], p_instance, script, self, static_ref, stack, err_text); - -#endif - -#ifdef DEBUG_ENABLED - - uint64_t function_start_time = 0; - uint64_t function_call_time = 0; - - if (GDScriptLanguage::get_singleton()->profiling) { - function_start_time = OS::get_singleton()->get_ticks_usec(); - function_call_time = 0; - profile.call_count++; - profile.frame_call_count++; - } - bool exit_ok = false; - bool awaited = false; -#endif - -#ifdef DEBUG_ENABLED - OPCODE_WHILE(ip < _code_size) { - int last_opcode = _code_ptr[ip]; -#else - OPCODE_WHILE(true) { -#endif - - OPCODE_SWITCH(_code_ptr[ip]) { - OPCODE(OPCODE_OPERATOR) { - CHECK_SPACE(5); - - bool valid; - Variant::Operator op = (Variant::Operator)_code_ptr[ip + 1]; - GD_ERR_BREAK(op >= Variant::OP_MAX); - - GET_VARIANT_PTR(a, 2); - GET_VARIANT_PTR(b, 3); - GET_VARIANT_PTR(dst, 4); - -#ifdef DEBUG_ENABLED - - Variant ret; - Variant::evaluate(op, *a, *b, ret, valid); -#else - Variant::evaluate(op, *a, *b, *dst, valid); -#endif -#ifdef DEBUG_ENABLED - if (!valid) { - if (ret.get_type() == Variant::STRING) { - //return a string when invalid with the error - err_text = ret; - err_text += " in operator '" + Variant::get_operator_name(op) + "'."; - } else { - err_text = "Invalid operands '" + Variant::get_type_name(a->get_type()) + "' and '" + Variant::get_type_name(b->get_type()) + "' in operator '" + Variant::get_operator_name(op) + "'."; - } - OPCODE_BREAK; - } - *dst = ret; -#endif - ip += 5; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_EXTENDS_TEST) { - CHECK_SPACE(4); - - GET_VARIANT_PTR(a, 1); - GET_VARIANT_PTR(b, 2); - GET_VARIANT_PTR(dst, 3); - -#ifdef DEBUG_ENABLED - if (b->get_type() != Variant::OBJECT || b->operator Object *() == nullptr) { - err_text = "Right operand of 'is' is not a class."; - OPCODE_BREAK; - } -#endif - - bool extends_ok = false; - if (a->get_type() == Variant::OBJECT && a->operator Object *() != nullptr) { -#ifdef DEBUG_ENABLED - bool was_freed; - Object *obj_A = a->get_validated_object_with_check(was_freed); - - if (was_freed) { - err_text = "Left operand of 'is' is a previously freed instance."; - OPCODE_BREAK; - } - - Object *obj_B = b->get_validated_object_with_check(was_freed); - - if (was_freed) { - err_text = "Right operand of 'is' is a previously freed instance."; - OPCODE_BREAK; - } -#else - - Object *obj_A = *a; - Object *obj_B = *b; -#endif // DEBUG_ENABLED - - GDScript *scr_B = Object::cast_to<GDScript>(obj_B); - - if (scr_B) { - //if B is a script, the only valid condition is that A has an instance which inherits from the script - //in other situation, this shoul return false. - - if (obj_A->get_script_instance() && obj_A->get_script_instance()->get_language() == GDScriptLanguage::get_singleton()) { - GDScript *cmp = static_cast<GDScript *>(obj_A->get_script_instance()->get_script().ptr()); - //bool found=false; - while (cmp) { - if (cmp == scr_B) { - //inherits from script, all ok - extends_ok = true; - break; - } - - cmp = cmp->_base; - } - } - - } else { - GDScriptNativeClass *nc = Object::cast_to<GDScriptNativeClass>(obj_B); - -#ifdef DEBUG_ENABLED - if (!nc) { - err_text = "Right operand of 'is' is not a class (type: '" + obj_B->get_class() + "')."; - OPCODE_BREAK; - } -#endif - extends_ok = ClassDB::is_parent_class(obj_A->get_class_name(), nc->get_name()); - } - } - - *dst = extends_ok; - ip += 4; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_IS_BUILTIN) { - CHECK_SPACE(4); - - GET_VARIANT_PTR(value, 1); - Variant::Type var_type = (Variant::Type)_code_ptr[ip + 2]; - GET_VARIANT_PTR(dst, 3); - - GD_ERR_BREAK(var_type < 0 || var_type >= Variant::VARIANT_MAX); - - *dst = value->get_type() == var_type; - ip += 4; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_SET) { - CHECK_SPACE(3); - - GET_VARIANT_PTR(dst, 1); - GET_VARIANT_PTR(index, 2); - GET_VARIANT_PTR(value, 3); - - bool valid; - dst->set(*index, *value, &valid); - -#ifdef DEBUG_ENABLED - if (!valid) { - String v = index->operator String(); - if (v != "") { - v = "'" + v + "'"; - } else { - v = "of type '" + _get_var_type(index) + "'"; - } - err_text = "Invalid set index " + v + " (on base: '" + _get_var_type(dst) + "') with value of type '" + _get_var_type(value) + "'"; - OPCODE_BREAK; - } -#endif - ip += 4; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_GET) { - CHECK_SPACE(3); - - GET_VARIANT_PTR(src, 1); - GET_VARIANT_PTR(index, 2); - GET_VARIANT_PTR(dst, 3); - - bool valid; -#ifdef DEBUG_ENABLED - //allow better error message in cases where src and dst are the same stack position - Variant ret = src->get(*index, &valid); -#else - *dst = src->get(*index, &valid); - -#endif -#ifdef DEBUG_ENABLED - if (!valid) { - String v = index->operator String(); - if (v != "") { - v = "'" + v + "'"; - } else { - v = "of type '" + _get_var_type(index) + "'"; - } - err_text = "Invalid get index " + v + " (on base: '" + _get_var_type(src) + "')."; - OPCODE_BREAK; - } - *dst = ret; -#endif - ip += 4; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_SET_NAMED) { - CHECK_SPACE(3); - - GET_VARIANT_PTR(dst, 1); - GET_VARIANT_PTR(value, 3); - - int indexname = _code_ptr[ip + 2]; - - GD_ERR_BREAK(indexname < 0 || indexname >= _global_names_count); - const StringName *index = &_global_names_ptr[indexname]; - - bool valid; - dst->set_named(*index, *value, valid); - -#ifdef DEBUG_ENABLED - if (!valid) { - String err_type; - err_text = "Invalid set index '" + String(*index) + "' (on base: '" + _get_var_type(dst) + "') with value of type '" + _get_var_type(value) + "'."; - OPCODE_BREAK; - } -#endif - ip += 4; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_GET_NAMED) { - CHECK_SPACE(4); - - GET_VARIANT_PTR(src, 1); - GET_VARIANT_PTR(dst, 3); - - int indexname = _code_ptr[ip + 2]; - - GD_ERR_BREAK(indexname < 0 || indexname >= _global_names_count); - const StringName *index = &_global_names_ptr[indexname]; - - bool valid; -#ifdef DEBUG_ENABLED - //allow better error message in cases where src and dst are the same stack position - Variant ret = src->get_named(*index, valid); - -#else - *dst = src->get_named(*index, valid); -#endif -#ifdef DEBUG_ENABLED - if (!valid) { - if (src->has_method(*index)) { - err_text = "Invalid get index '" + index->operator String() + "' (on base: '" + _get_var_type(src) + "'). Did you mean '." + index->operator String() + "()' or funcref(obj, \"" + index->operator String() + "\") ?"; - } else { - err_text = "Invalid get index '" + index->operator String() + "' (on base: '" + _get_var_type(src) + "')."; - } - OPCODE_BREAK; - } - *dst = ret; -#endif - ip += 4; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_SET_MEMBER) { - CHECK_SPACE(3); - int indexname = _code_ptr[ip + 1]; - GD_ERR_BREAK(indexname < 0 || indexname >= _global_names_count); - const StringName *index = &_global_names_ptr[indexname]; - GET_VARIANT_PTR(src, 2); - - bool valid; -#ifndef DEBUG_ENABLED - ClassDB::set_property(p_instance->owner, *index, *src, &valid); -#else - bool ok = ClassDB::set_property(p_instance->owner, *index, *src, &valid); - if (!ok) { - err_text = "Internal error setting property: " + String(*index); - OPCODE_BREAK; - } else if (!valid) { - err_text = "Error setting property '" + String(*index) + "' with value of type " + Variant::get_type_name(src->get_type()) + "."; - OPCODE_BREAK; - } -#endif - ip += 3; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_GET_MEMBER) { - CHECK_SPACE(3); - int indexname = _code_ptr[ip + 1]; - GD_ERR_BREAK(indexname < 0 || indexname >= _global_names_count); - const StringName *index = &_global_names_ptr[indexname]; - GET_VARIANT_PTR(dst, 2); - -#ifndef DEBUG_ENABLED - ClassDB::get_property(p_instance->owner, *index, *dst); -#else - bool ok = ClassDB::get_property(p_instance->owner, *index, *dst); - if (!ok) { - err_text = "Internal error getting property: " + String(*index); - OPCODE_BREAK; - } -#endif - ip += 3; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_ASSIGN) { - CHECK_SPACE(3); - GET_VARIANT_PTR(dst, 1); - GET_VARIANT_PTR(src, 2); - - *dst = *src; - - ip += 3; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_ASSIGN_TRUE) { - CHECK_SPACE(2); - GET_VARIANT_PTR(dst, 1); - - *dst = true; - - ip += 2; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_ASSIGN_FALSE) { - CHECK_SPACE(2); - GET_VARIANT_PTR(dst, 1); - - *dst = false; - - ip += 2; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_ASSIGN_TYPED_BUILTIN) { - CHECK_SPACE(4); - GET_VARIANT_PTR(dst, 2); - GET_VARIANT_PTR(src, 3); - - Variant::Type var_type = (Variant::Type)_code_ptr[ip + 1]; - GD_ERR_BREAK(var_type < 0 || var_type >= Variant::VARIANT_MAX); - - if (src->get_type() != var_type) { -#ifdef DEBUG_ENABLED - if (Variant::can_convert_strict(src->get_type(), var_type)) { -#endif // DEBUG_ENABLED - Callable::CallError ce; - Variant::construct(var_type, *dst, const_cast<const Variant **>(&src), 1, ce); - } else { -#ifdef DEBUG_ENABLED - err_text = "Trying to assign value of type '" + Variant::get_type_name(src->get_type()) + - "' to a variable of type '" + Variant::get_type_name(var_type) + "'."; - OPCODE_BREAK; - } - } else { -#endif // DEBUG_ENABLED - *dst = *src; - } - - ip += 4; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_ASSIGN_TYPED_NATIVE) { - CHECK_SPACE(4); - GET_VARIANT_PTR(dst, 2); - GET_VARIANT_PTR(src, 3); - -#ifdef DEBUG_ENABLED - GET_VARIANT_PTR(type, 1); - GDScriptNativeClass *nc = Object::cast_to<GDScriptNativeClass>(type->operator Object *()); - GD_ERR_BREAK(!nc); - if (src->get_type() != Variant::OBJECT && src->get_type() != Variant::NIL) { - err_text = "Trying to assign value of type '" + Variant::get_type_name(src->get_type()) + - "' to a variable of type '" + nc->get_name() + "'."; - OPCODE_BREAK; - } - Object *src_obj = src->operator Object *(); - - if (src_obj && !ClassDB::is_parent_class(src_obj->get_class_name(), nc->get_name())) { - err_text = "Trying to assign value of type '" + src_obj->get_class_name() + - "' to a variable of type '" + nc->get_name() + "'."; - OPCODE_BREAK; - } -#endif // DEBUG_ENABLED - *dst = *src; - - ip += 4; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_ASSIGN_TYPED_SCRIPT) { - CHECK_SPACE(4); - GET_VARIANT_PTR(dst, 2); - GET_VARIANT_PTR(src, 3); - -#ifdef DEBUG_ENABLED - GET_VARIANT_PTR(type, 1); - Script *base_type = Object::cast_to<Script>(type->operator Object *()); - - GD_ERR_BREAK(!base_type); - - if (src->get_type() != Variant::OBJECT && src->get_type() != Variant::NIL) { - err_text = "Trying to assign a non-object value to a variable of type '" + base_type->get_path().get_file() + "'."; - OPCODE_BREAK; - } - - if (src->get_type() != Variant::NIL && src->operator Object *() != nullptr) { - ScriptInstance *scr_inst = src->operator Object *()->get_script_instance(); - if (!scr_inst) { - err_text = "Trying to assign value of type '" + src->operator Object *()->get_class_name() + - "' to a variable of type '" + base_type->get_path().get_file() + "'."; - OPCODE_BREAK; - } - - Script *src_type = src->operator Object *()->get_script_instance()->get_script().ptr(); - bool valid = false; - - while (src_type) { - if (src_type == base_type) { - valid = true; - break; - } - src_type = src_type->get_base_script().ptr(); - } - - if (!valid) { - err_text = "Trying to assign value of type '" + src->operator Object *()->get_script_instance()->get_script()->get_path().get_file() + - "' to a variable of type '" + base_type->get_path().get_file() + "'."; - OPCODE_BREAK; - } - } -#endif // DEBUG_ENABLED - - *dst = *src; - - ip += 4; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_CAST_TO_BUILTIN) { - CHECK_SPACE(4); - Variant::Type to_type = (Variant::Type)_code_ptr[ip + 1]; - GET_VARIANT_PTR(src, 2); - GET_VARIANT_PTR(dst, 3); - - GD_ERR_BREAK(to_type < 0 || to_type >= Variant::VARIANT_MAX); - - Callable::CallError err; - Variant::construct(to_type, *dst, (const Variant **)&src, 1, err); - -#ifdef DEBUG_ENABLED - if (err.error != Callable::CallError::CALL_OK) { - err_text = "Invalid cast: could not convert value to '" + Variant::get_type_name(to_type) + "'."; - OPCODE_BREAK; - } -#endif - - ip += 4; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_CAST_TO_NATIVE) { - CHECK_SPACE(4); - GET_VARIANT_PTR(to_type, 1); - GET_VARIANT_PTR(src, 2); - GET_VARIANT_PTR(dst, 3); - - GDScriptNativeClass *nc = Object::cast_to<GDScriptNativeClass>(to_type->operator Object *()); - GD_ERR_BREAK(!nc); - -#ifdef DEBUG_ENABLED - if (src->get_type() != Variant::OBJECT && src->get_type() != Variant::NIL) { - err_text = "Invalid cast: can't convert a non-object value to an object type."; - OPCODE_BREAK; - } -#endif - Object *src_obj = src->operator Object *(); - - if (src_obj && !ClassDB::is_parent_class(src_obj->get_class_name(), nc->get_name())) { - *dst = Variant(); // invalid cast, assign NULL - } else { - *dst = *src; - } - - ip += 4; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_CAST_TO_SCRIPT) { - CHECK_SPACE(4); - GET_VARIANT_PTR(to_type, 1); - GET_VARIANT_PTR(src, 2); - GET_VARIANT_PTR(dst, 3); - - Script *base_type = Object::cast_to<Script>(to_type->operator Object *()); - - GD_ERR_BREAK(!base_type); - -#ifdef DEBUG_ENABLED - if (src->get_type() != Variant::OBJECT && src->get_type() != Variant::NIL) { - err_text = "Trying to assign a non-object value to a variable of type '" + base_type->get_path().get_file() + "'."; - OPCODE_BREAK; - } -#endif - - bool valid = false; - - if (src->get_type() != Variant::NIL && src->operator Object *() != nullptr) { - ScriptInstance *scr_inst = src->operator Object *()->get_script_instance(); - - if (scr_inst) { - Script *src_type = src->operator Object *()->get_script_instance()->get_script().ptr(); - - while (src_type) { - if (src_type == base_type) { - valid = true; - break; - } - src_type = src_type->get_base_script().ptr(); - } - } - } - - if (valid) { - *dst = *src; // Valid cast, copy the source object - } else { - *dst = Variant(); // invalid cast, assign NULL - } - - ip += 4; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_CONSTRUCT) { - CHECK_SPACE(2); - Variant::Type t = Variant::Type(_code_ptr[ip + 1]); - int argc = _code_ptr[ip + 2]; - CHECK_SPACE(argc + 2); - Variant **argptrs = call_args; - for (int i = 0; i < argc; i++) { - GET_VARIANT_PTR(v, 3 + i); - argptrs[i] = v; - } - - GET_VARIANT_PTR(dst, 3 + argc); - Callable::CallError err; - Variant::construct(t, *dst, (const Variant **)argptrs, argc, err); - -#ifdef DEBUG_ENABLED - if (err.error != Callable::CallError::CALL_OK) { - err_text = _get_call_error(err, "'" + Variant::get_type_name(t) + "' constructor", (const Variant **)argptrs); - OPCODE_BREAK; - } -#endif - - ip += 4 + argc; - //construct a basic type - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_CONSTRUCT_ARRAY) { - CHECK_SPACE(1); - int argc = _code_ptr[ip + 1]; - Array array; //arrays are always shared - array.resize(argc); - CHECK_SPACE(argc + 2); - - for (int i = 0; i < argc; i++) { - GET_VARIANT_PTR(v, 2 + i); - array[i] = *v; - } - - GET_VARIANT_PTR(dst, 2 + argc); - - *dst = array; - - ip += 3 + argc; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_CONSTRUCT_DICTIONARY) { - CHECK_SPACE(1); - int argc = _code_ptr[ip + 1]; - Dictionary dict; //arrays are always shared - - CHECK_SPACE(argc * 2 + 2); - - for (int i = 0; i < argc; i++) { - GET_VARIANT_PTR(k, 2 + i * 2 + 0); - GET_VARIANT_PTR(v, 2 + i * 2 + 1); - dict[*k] = *v; - } - - GET_VARIANT_PTR(dst, 2 + argc * 2); - - *dst = dict; - - ip += 3 + argc * 2; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_CALL_ASYNC) - OPCODE(OPCODE_CALL_RETURN) - OPCODE(OPCODE_CALL) { - CHECK_SPACE(4); - bool call_ret = _code_ptr[ip] != OPCODE_CALL; -#ifdef DEBUG_ENABLED - bool call_async = _code_ptr[ip] == OPCODE_CALL_ASYNC; -#endif - - int argc = _code_ptr[ip + 1]; - GET_VARIANT_PTR(base, 2); - int nameg = _code_ptr[ip + 3]; - - GD_ERR_BREAK(nameg < 0 || nameg >= _global_names_count); - const StringName *methodname = &_global_names_ptr[nameg]; - - GD_ERR_BREAK(argc < 0); - ip += 4; - CHECK_SPACE(argc + 1); - Variant **argptrs = call_args; - - for (int i = 0; i < argc; i++) { - GET_VARIANT_PTR(v, i); - argptrs[i] = v; - } - -#ifdef DEBUG_ENABLED - uint64_t call_time = 0; - - if (GDScriptLanguage::get_singleton()->profiling) { - call_time = OS::get_singleton()->get_ticks_usec(); - } - -#endif - Callable::CallError err; - if (call_ret) { - GET_VARIANT_PTR(ret, argc); - base->call(*methodname, (const Variant **)argptrs, argc, *ret, err); -#ifdef DEBUG_ENABLED - if (!call_async && ret->get_type() == Variant::OBJECT) { - // Check if getting a function state without await. - bool was_freed = false; - Object *obj = ret->get_validated_object_with_check(was_freed); - - if (was_freed) { - err_text = "Got a freed object as a result of the call."; - OPCODE_BREAK; - } - if (obj && obj->is_class_ptr(GDScriptFunctionState::get_class_ptr_static())) { - err_text = R"(Trying to call an async function without "await".)"; - OPCODE_BREAK; - } - } -#endif - } else { - Variant ret; - base->call(*methodname, (const Variant **)argptrs, argc, ret, err); - } -#ifdef DEBUG_ENABLED - if (GDScriptLanguage::get_singleton()->profiling) { - function_call_time += OS::get_singleton()->get_ticks_usec() - call_time; - } - - if (err.error != Callable::CallError::CALL_OK) { - String methodstr = *methodname; - String basestr = _get_var_type(base); - - if (methodstr == "call") { - if (argc >= 1) { - methodstr = String(*argptrs[0]) + " (via call)"; - if (err.error == Callable::CallError::CALL_ERROR_INVALID_ARGUMENT) { - err.argument += 1; - } - } - } else if (methodstr == "free") { - if (err.error == Callable::CallError::CALL_ERROR_INVALID_METHOD) { - if (base->is_ref()) { - err_text = "Attempted to free a reference."; - OPCODE_BREAK; - } else if (base->get_type() == Variant::OBJECT) { - err_text = "Attempted to free a locked object (calling or emitting)."; - OPCODE_BREAK; - } - } - } else if (methodstr == "call_recursive" && basestr == "TreeItem") { - if (argc >= 1) { - methodstr = String(*argptrs[0]) + " (via TreeItem.call_recursive)"; - if (err.error == Callable::CallError::CALL_ERROR_INVALID_ARGUMENT) { - err.argument += 1; - } - } - } - err_text = _get_call_error(err, "function '" + methodstr + "' in base '" + basestr + "'", (const Variant **)argptrs); - OPCODE_BREAK; - } -#endif - - //_call_func(nullptr,base,*methodname,ip,argc,p_instance,stack); - ip += argc + 1; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_CALL_BUILT_IN) { - CHECK_SPACE(4); - - GDScriptFunctions::Function func = GDScriptFunctions::Function(_code_ptr[ip + 1]); - int argc = _code_ptr[ip + 2]; - GD_ERR_BREAK(argc < 0); - - ip += 3; - CHECK_SPACE(argc + 1); - Variant **argptrs = call_args; - - for (int i = 0; i < argc; i++) { - GET_VARIANT_PTR(v, i); - argptrs[i] = v; - } - - GET_VARIANT_PTR(dst, argc); - - Callable::CallError err; - - GDScriptFunctions::call(func, (const Variant **)argptrs, argc, *dst, err); - -#ifdef DEBUG_ENABLED - if (err.error != Callable::CallError::CALL_OK) { - String methodstr = GDScriptFunctions::get_func_name(func); - if (dst->get_type() == Variant::STRING) { - //call provided error string - err_text = "Error calling built-in function '" + methodstr + "': " + String(*dst); - } else { - err_text = _get_call_error(err, "built-in function '" + methodstr + "'", (const Variant **)argptrs); - } - OPCODE_BREAK; - } -#endif - ip += argc + 1; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_CALL_SELF_BASE) { - CHECK_SPACE(2); - int self_fun = _code_ptr[ip + 1]; - -#ifdef DEBUG_ENABLED - if (self_fun < 0 || self_fun >= _global_names_count) { - err_text = "compiler bug, function name not found"; - OPCODE_BREAK; - } -#endif - const StringName *methodname = &_global_names_ptr[self_fun]; - - int argc = _code_ptr[ip + 2]; - - CHECK_SPACE(2 + argc + 1); - - Variant **argptrs = call_args; - - for (int i = 0; i < argc; i++) { - GET_VARIANT_PTR(v, i + 3); - argptrs[i] = v; - } - - GET_VARIANT_PTR(dst, argc + 3); - - const GDScript *gds = _script; - - const Map<StringName, GDScriptFunction *>::Element *E = nullptr; - while (gds->base.ptr()) { - gds = gds->base.ptr(); - E = gds->member_functions.find(*methodname); - if (E) { - break; - } - } - - Callable::CallError err; - - if (E) { - *dst = E->get()->call(p_instance, (const Variant **)argptrs, argc, err); - } else if (gds->native.ptr()) { - if (*methodname != GDScriptLanguage::get_singleton()->strings._init) { - MethodBind *mb = ClassDB::get_method(gds->native->get_name(), *methodname); - if (!mb) { - err.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; - } else { - *dst = mb->call(p_instance->owner, (const Variant **)argptrs, argc, err); - } - } else { - err.error = Callable::CallError::CALL_OK; - } - } else { - if (*methodname != GDScriptLanguage::get_singleton()->strings._init) { - err.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; - } else { - err.error = Callable::CallError::CALL_OK; - } - } - - if (err.error != Callable::CallError::CALL_OK) { - String methodstr = *methodname; - err_text = _get_call_error(err, "function '" + methodstr + "'", (const Variant **)argptrs); - - OPCODE_BREAK; - } - - ip += 4 + argc; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_AWAIT) { - CHECK_SPACE(2); - - //do the oneshot connect - GET_VARIANT_PTR(argobj, 1); - - Signal sig; - bool is_signal = true; - - { - Variant result = *argobj; - - if (argobj->get_type() == Variant::OBJECT) { - bool was_freed = false; - Object *obj = argobj->get_validated_object_with_check(was_freed); - - if (was_freed) { - err_text = "Trying to await on a freed object."; - OPCODE_BREAK; - } - - // Is this even possible to be null at this point? - if (obj) { - if (obj->is_class_ptr(GDScriptFunctionState::get_class_ptr_static())) { - static StringName completed = _scs_create("completed"); - result = Signal(obj, completed); - } - } - } - - if (result.get_type() != Variant::SIGNAL) { - ip += 4; // Skip OPCODE_AWAIT_RESUME and its data. - // The stack pointer should be the same, so we don't need to set a return value. - is_signal = false; - } else { - sig = result; - } - } - - if (is_signal) { - Ref<GDScriptFunctionState> gdfs = memnew(GDScriptFunctionState); - gdfs->function = this; - - gdfs->state.stack.resize(alloca_size); - //copy variant stack - for (int i = 0; i < _stack_size; i++) { - memnew_placement(&gdfs->state.stack.write[sizeof(Variant) * i], Variant(stack[i])); - } - gdfs->state.stack_size = _stack_size; - gdfs->state.self = self; - gdfs->state.alloca_size = alloca_size; - gdfs->state.ip = ip + 2; - gdfs->state.line = line; - gdfs->state.script = _script; - { - MutexLock lock(GDScriptLanguage::get_singleton()->lock); - _script->pending_func_states.add(&gdfs->scripts_list); - if (p_instance) { - gdfs->state.instance = p_instance; - p_instance->pending_func_states.add(&gdfs->instances_list); - } else { - gdfs->state.instance = nullptr; - } - } -#ifdef DEBUG_ENABLED - gdfs->state.function_name = name; - gdfs->state.script_path = _script->get_path(); -#endif - gdfs->state.defarg = defarg; - gdfs->function = this; - - retvalue = gdfs; - - Error err = sig.connect(Callable(gdfs.ptr(), "_signal_callback"), varray(gdfs), Object::CONNECT_ONESHOT); - if (err != OK) { - err_text = "Error connecting to signal: " + sig.get_name() + " during await."; - OPCODE_BREAK; - } - -#ifdef DEBUG_ENABLED - exit_ok = true; - awaited = true; -#endif - OPCODE_BREAK; - } - } - DISPATCH_OPCODE; // Needed for synchronous calls (when result is immediately available). - - OPCODE(OPCODE_AWAIT_RESUME) { - CHECK_SPACE(2); -#ifdef DEBUG_ENABLED - if (!p_state) { - err_text = ("Invalid Resume (bug?)"); - OPCODE_BREAK; - } -#endif - GET_VARIANT_PTR(result, 1); - *result = p_state->result; - ip += 2; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_JUMP) { - CHECK_SPACE(2); - int to = _code_ptr[ip + 1]; - - GD_ERR_BREAK(to < 0 || to > _code_size); - ip = to; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_JUMP_IF) { - CHECK_SPACE(3); - - GET_VARIANT_PTR(test, 1); - - bool result = test->booleanize(); - - if (result) { - int to = _code_ptr[ip + 2]; - GD_ERR_BREAK(to < 0 || to > _code_size); - ip = to; - } else { - ip += 3; - } - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_JUMP_IF_NOT) { - CHECK_SPACE(3); - - GET_VARIANT_PTR(test, 1); - - bool result = test->booleanize(); - - if (!result) { - int to = _code_ptr[ip + 2]; - GD_ERR_BREAK(to < 0 || to > _code_size); - ip = to; - } else { - ip += 3; - } - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_JUMP_TO_DEF_ARGUMENT) { - CHECK_SPACE(2); - ip = _default_arg_ptr[defarg]; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_RETURN) { - CHECK_SPACE(2); - GET_VARIANT_PTR(r, 1); - retvalue = *r; -#ifdef DEBUG_ENABLED - exit_ok = true; -#endif - OPCODE_BREAK; - } - - OPCODE(OPCODE_ITERATE_BEGIN) { - CHECK_SPACE(8); //space for this a regular iterate - - GET_VARIANT_PTR(counter, 1); - GET_VARIANT_PTR(container, 2); - - bool valid; - if (!container->iter_init(*counter, valid)) { -#ifdef DEBUG_ENABLED - if (!valid) { - err_text = "Unable to iterate on object of type '" + Variant::get_type_name(container->get_type()) + "'."; - OPCODE_BREAK; - } -#endif - int jumpto = _code_ptr[ip + 3]; - GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size); - ip = jumpto; - } else { - GET_VARIANT_PTR(iterator, 4); - - *iterator = container->iter_get(*counter, valid); -#ifdef DEBUG_ENABLED - if (!valid) { - err_text = "Unable to obtain iterator object of type '" + Variant::get_type_name(container->get_type()) + "'."; - OPCODE_BREAK; - } -#endif - ip += 5; //skip regular iterate which is always next - } - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_ITERATE) { - CHECK_SPACE(4); - - GET_VARIANT_PTR(counter, 1); - GET_VARIANT_PTR(container, 2); - - bool valid; - if (!container->iter_next(*counter, valid)) { -#ifdef DEBUG_ENABLED - if (!valid) { - err_text = "Unable to iterate on object of type '" + Variant::get_type_name(container->get_type()) + "' (type changed since first iteration?)."; - OPCODE_BREAK; - } -#endif - int jumpto = _code_ptr[ip + 3]; - GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size); - ip = jumpto; - } else { - GET_VARIANT_PTR(iterator, 4); - - *iterator = container->iter_get(*counter, valid); -#ifdef DEBUG_ENABLED - if (!valid) { - err_text = "Unable to obtain iterator object of type '" + Variant::get_type_name(container->get_type()) + "' (but was obtained on first iteration?)."; - OPCODE_BREAK; - } -#endif - ip += 5; //loop again - } - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_ASSERT) { - CHECK_SPACE(3); - -#ifdef DEBUG_ENABLED - GET_VARIANT_PTR(test, 1); - bool result = test->booleanize(); - - if (!result) { - String message_str; - if (_code_ptr[ip + 2] != 0) { - GET_VARIANT_PTR(message, 2); - message_str = *message; - } - if (message_str.empty()) { - err_text = "Assertion failed."; - } else { - err_text = "Assertion failed: " + message_str; - } - OPCODE_BREAK; - } - -#endif - ip += 3; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_BREAKPOINT) { -#ifdef DEBUG_ENABLED - if (EngineDebugger::is_active()) { - GDScriptLanguage::get_singleton()->debug_break("Breakpoint Statement", true); - } -#endif - ip += 1; - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_LINE) { - CHECK_SPACE(2); - - line = _code_ptr[ip + 1]; - ip += 2; - - if (EngineDebugger::is_active()) { - // line - bool do_break = false; - - if (EngineDebugger::get_script_debugger()->get_lines_left() > 0) { - if (EngineDebugger::get_script_debugger()->get_depth() <= 0) { - EngineDebugger::get_script_debugger()->set_lines_left(EngineDebugger::get_script_debugger()->get_lines_left() - 1); - } - if (EngineDebugger::get_script_debugger()->get_lines_left() <= 0) { - do_break = true; - } - } - - if (EngineDebugger::get_script_debugger()->is_breakpoint(line, source)) { - do_break = true; - } - - if (do_break) { - GDScriptLanguage::get_singleton()->debug_break("Breakpoint", true); - } - - EngineDebugger::get_singleton()->line_poll(); - } - } - DISPATCH_OPCODE; - - OPCODE(OPCODE_END) { -#ifdef DEBUG_ENABLED - exit_ok = true; -#endif - OPCODE_BREAK; - } - -#if 0 // Enable for debugging. - default: { - err_text = "Illegal opcode " + itos(_code_ptr[ip]) + " at address " + itos(ip); - OPCODE_BREAK; - } -#endif - } - - OPCODES_END -#ifdef DEBUG_ENABLED - if (exit_ok) { - OPCODE_OUT; - } - //error - // function, file, line, error, explanation - String err_file; - if (p_instance && ObjectDB::get_instance(p_instance->owner_id) != nullptr && p_instance->script->is_valid() && p_instance->script->path != "") { - err_file = p_instance->script->path; - } else if (script) { - err_file = script->path; - } - if (err_file == "") { - err_file = "<built-in>"; - } - String err_func = name; - if (p_instance && ObjectDB::get_instance(p_instance->owner_id) != nullptr && p_instance->script->is_valid() && p_instance->script->name != "") { - err_func = p_instance->script->name + "." + err_func; - } - int err_line = line; - if (err_text == "") { - err_text = "Internal Script Error! - opcode #" + itos(last_opcode) + " (report please)."; - } - - if (!GDScriptLanguage::get_singleton()->debug_break(err_text, false)) { - // debugger break did not happen - - _err_print_error(err_func.utf8().get_data(), err_file.utf8().get_data(), err_line, err_text.utf8().get_data(), ERR_HANDLER_SCRIPT); - } - -#endif - OPCODE_OUT; - } - - OPCODES_OUT -#ifdef DEBUG_ENABLED - if (GDScriptLanguage::get_singleton()->profiling) { - uint64_t time_taken = OS::get_singleton()->get_ticks_usec() - function_start_time; - profile.total_time += time_taken; - profile.self_time += time_taken - function_call_time; - profile.frame_total_time += time_taken; - profile.frame_self_time += time_taken - function_call_time; - GDScriptLanguage::get_singleton()->script_frame_time += time_taken - function_call_time; - } - - // Check if this is the last time the function is resuming from await - // Will be true if never awaited as well - // When it's the last resume it will postpone the exit from stack, - // so the debugger knows which function triggered the resume of the next function (if any) - if (!p_state || awaited) { - if (EngineDebugger::is_active()) { - GDScriptLanguage::get_singleton()->exit_function(); - } -#endif - - if (_stack_size) { - //free stack - for (int i = 0; i < _stack_size; i++) { - stack[i].~Variant(); - } - } - -#ifdef DEBUG_ENABLED - } -#endif - - return retvalue; -} const int *GDScriptFunction::get_code() const { return _code_ptr; @@ -1706,31 +139,13 @@ void GDScriptFunction::debug_get_stack_member_state(int p_line, List<Pair<String } } -GDScriptFunction::GDScriptFunction() : - function_list(this) { - _stack_size = 0; - _call_size = 0; - rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED; +GDScriptFunction::GDScriptFunction() { name = "<anonymous>"; #ifdef DEBUG_ENABLED - _func_cname = nullptr; - { MutexLock lock(GDScriptLanguage::get_singleton()->lock); - GDScriptLanguage::get_singleton()->function_list.add(&function_list); } - - profile.call_count = 0; - profile.self_time = 0; - profile.total_time = 0; - profile.frame_call_count = 0; - profile.frame_self_time = 0; - profile.frame_total_time = 0; - profile.last_frame_call_count = 0; - profile.last_frame_self_time = 0; - profile.last_frame_total_time = 0; - #endif } @@ -1891,506 +306,3 @@ GDScriptFunctionState::~GDScriptFunctionState() { instances_list.remove_from_list(); } } - -#ifdef DEBUG_ENABLED -static String _get_variant_string(const Variant &p_variant) { - String txt; - if (p_variant.get_type() == Variant::STRING) { - txt = "\"" + String(p_variant) + "\""; - } else if (p_variant.get_type() == Variant::STRING_NAME) { - txt = "&\"" + String(p_variant) + "\""; - } else if (p_variant.get_type() == Variant::NODE_PATH) { - txt = "^\"" + String(p_variant) + "\""; - } else if (p_variant.get_type() == Variant::OBJECT) { - Object *obj = p_variant; - if (!obj) { - txt = "null"; - } else { - GDScriptNativeClass *cls = Object::cast_to<GDScriptNativeClass>(obj); - if (cls) { - txt += cls->get_name(); - txt += " (class)"; - } else { - txt = obj->get_class(); - if (obj->get_script_instance()) { - txt += "(" + obj->get_script_instance()->get_script()->get_path() + ")"; - } - } - } - } else { - txt = p_variant; - } - return txt; -} - -static String _disassemble_address(const GDScript *p_script, const GDScriptFunction &p_function, int p_address) { - int addr = p_address & GDScriptFunction::ADDR_MASK; - - switch (p_address >> GDScriptFunction::ADDR_BITS) { - case GDScriptFunction::ADDR_TYPE_SELF: { - return "self"; - } break; - case GDScriptFunction::ADDR_TYPE_CLASS: { - return "class"; - } break; - case GDScriptFunction::ADDR_TYPE_MEMBER: { - return "member(" + p_script->debug_get_member_by_index(addr) + ")"; - } break; - case GDScriptFunction::ADDR_TYPE_CLASS_CONSTANT: { - return "class_const(" + p_function.get_global_name(addr) + ")"; - } break; - case GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT: { - return "const(" + _get_variant_string(p_function.get_constant(addr)) + ")"; - } break; - case GDScriptFunction::ADDR_TYPE_STACK: { - return "stack(" + itos(addr) + ")"; - } break; - case GDScriptFunction::ADDR_TYPE_STACK_VARIABLE: { - return "var_stack(" + itos(addr) + ")"; - } break; - case GDScriptFunction::ADDR_TYPE_GLOBAL: { - return "global(" + _get_variant_string(GDScriptLanguage::get_singleton()->get_global_array()[addr]) + ")"; - } break; - case GDScriptFunction::ADDR_TYPE_NAMED_GLOBAL: { - return "named_global(" + p_function.get_global_name(addr) + ")"; - } break; - case GDScriptFunction::ADDR_TYPE_NIL: { - return "nil"; - } break; - } - - return "<err>"; -} - -void GDScriptFunction::disassemble(const Vector<String> &p_code_lines) const { -#define DADDR(m_ip) (_disassemble_address(_script, *this, _code_ptr[ip + m_ip])) - - for (int ip = 0; ip < _code_size;) { - StringBuilder text; - int incr = 0; - - text += " "; - text += itos(ip); - text += ": "; - - // This makes the compiler complain if some opcode is unchecked in the switch. - Opcode code = Opcode(_code_ptr[ip]); - - switch (code) { - case OPCODE_OPERATOR: { - int operation = _code_ptr[ip + 1]; - - text += "operator "; - - text += DADDR(4); - text += " = "; - text += DADDR(2); - text += " "; - text += Variant::get_operator_name(Variant::Operator(operation)); - text += " "; - text += DADDR(3); - - incr += 5; - } break; - case OPCODE_EXTENDS_TEST: { - text += "is object "; - text += DADDR(3); - text += " = "; - text += DADDR(1); - text += " is "; - text += DADDR(2); - - incr += 4; - } break; - case OPCODE_IS_BUILTIN: { - text += "is builtin "; - text += DADDR(3); - text += " = "; - text += DADDR(1); - text += " is "; - text += Variant::get_type_name(Variant::Type(_code_ptr[ip + 2])); - - incr += 4; - } break; - case OPCODE_SET: { - text += "set "; - text += DADDR(1); - text += "["; - text += DADDR(2); - text += "] = "; - text += DADDR(3); - - incr += 4; - } break; - case OPCODE_GET: { - text += "get "; - text += DADDR(3); - text += " = "; - text += DADDR(1); - text += "["; - text += DADDR(2); - text += "]"; - - incr += 4; - } break; - case OPCODE_SET_NAMED: { - text += "set_named "; - text += DADDR(1); - text += "[\""; - text += _global_names_ptr[_code_ptr[ip + 2]]; - text += "\"] = "; - text += DADDR(3); - - incr += 4; - } break; - case OPCODE_GET_NAMED: { - text += "get_named "; - text += DADDR(3); - text += " = "; - text += DADDR(1); - text += "[\""; - text += _global_names_ptr[_code_ptr[ip + 2]]; - text += "\"]"; - - incr += 4; - } break; - case OPCODE_SET_MEMBER: { - text += "set_member "; - text += "[\""; - text += _global_names_ptr[_code_ptr[ip + 1]]; - text += "\"] = "; - text += DADDR(2); - - incr += 3; - } break; - case OPCODE_GET_MEMBER: { - text += "get_member "; - text += DADDR(2); - text += " = "; - text += "[\""; - text += _global_names_ptr[_code_ptr[ip + 1]]; - text += "\"]"; - - incr += 3; - } break; - case OPCODE_ASSIGN: { - text += "assign "; - text += DADDR(1); - text += " = "; - text += DADDR(2); - - incr += 3; - } break; - case OPCODE_ASSIGN_TRUE: { - text += "assign "; - text += DADDR(1); - text += " = true"; - - incr += 2; - } break; - case OPCODE_ASSIGN_FALSE: { - text += "assign "; - text += DADDR(1); - text += " = false"; - - incr += 2; - } break; - case OPCODE_ASSIGN_TYPED_BUILTIN: { - text += "assign typed builtin ("; - text += Variant::get_type_name((Variant::Type)_code_ptr[ip + 1]); - text += ") "; - text += DADDR(2); - text += " = "; - text += DADDR(3); - - incr += 4; - } break; - case OPCODE_ASSIGN_TYPED_NATIVE: { - Variant class_name = _constants_ptr[_code_ptr[ip + 1]]; - GDScriptNativeClass *nc = Object::cast_to<GDScriptNativeClass>(class_name.operator Object *()); - - text += "assign typed native ("; - text += nc->get_name().operator String(); - text += ") "; - text += DADDR(2); - text += " = "; - text += DADDR(3); - - incr += 4; - } break; - case OPCODE_ASSIGN_TYPED_SCRIPT: { - Variant script = _constants_ptr[_code_ptr[ip + 1]]; - Script *sc = Object::cast_to<Script>(script.operator Object *()); - - text += "assign typed script ("; - text += sc->get_path(); - text += ") "; - text += DADDR(2); - text += " = "; - text += DADDR(3); - - incr += 4; - } break; - case OPCODE_CAST_TO_BUILTIN: { - text += "cast builtin "; - text += DADDR(3); - text += " = "; - text += DADDR(2); - text += " as "; - text += Variant::get_type_name(Variant::Type(_code_ptr[ip + 1])); - - incr += 4; - } break; - case OPCODE_CAST_TO_NATIVE: { - Variant class_name = _constants_ptr[_code_ptr[ip + 1]]; - GDScriptNativeClass *nc = Object::cast_to<GDScriptNativeClass>(class_name.operator Object *()); - - text += "cast native "; - text += DADDR(3); - text += " = "; - text += DADDR(2); - text += " as "; - text += nc->get_name(); - - incr += 4; - } break; - case OPCODE_CAST_TO_SCRIPT: { - text += "cast "; - text += DADDR(3); - text += " = "; - text += DADDR(2); - text += " as "; - text += DADDR(1); - - incr += 4; - } break; - case OPCODE_CONSTRUCT: { - Variant::Type t = Variant::Type(_code_ptr[ip + 1]); - int argc = _code_ptr[ip + 2]; - - text += "construct "; - text += DADDR(3 + argc); - text += " = "; - - text += Variant::get_type_name(t) + "("; - for (int i = 0; i < argc; i++) { - if (i > 0) - text += ", "; - text += DADDR(i + 3); - } - text += ")"; - - incr = 4 + argc; - } break; - case OPCODE_CONSTRUCT_ARRAY: { - int argc = _code_ptr[ip + 1]; - text += " make_array "; - text += DADDR(2 + argc); - text += " = ["; - - for (int i = 0; i < argc; i++) { - if (i > 0) - text += ", "; - text += DADDR(2 + i); - } - - text += "]"; - - incr += 3 + argc; - } break; - case OPCODE_CONSTRUCT_DICTIONARY: { - int argc = _code_ptr[ip + 1]; - text += "make_dict "; - text += DADDR(2 + argc * 2); - text += " = {"; - - for (int i = 0; i < argc; i++) { - if (i > 0) - text += ", "; - text += DADDR(2 + i * 2 + 0); - text += ": "; - text += DADDR(2 + i * 2 + 1); - } - - text += "}"; - - incr += 3 + argc * 2; - } break; - case OPCODE_CALL: - case OPCODE_CALL_RETURN: - case OPCODE_CALL_ASYNC: { - bool ret = _code_ptr[ip] == OPCODE_CALL_RETURN; - bool async = _code_ptr[ip] == OPCODE_CALL_ASYNC; - - if (ret) { - text += "call-ret "; - } else if (async) { - text += "call-async "; - } else { - text += "call "; - } - - int argc = _code_ptr[ip + 1]; - if (ret || async) { - text += DADDR(4 + argc) + " = "; - } - - text += DADDR(2) + "."; - text += String(_global_names_ptr[_code_ptr[ip + 3]]); - text += "("; - - for (int i = 0; i < argc; i++) { - if (i > 0) - text += ", "; - text += DADDR(4 + i); - } - text += ")"; - - incr = 5 + argc; - } break; - case OPCODE_CALL_BUILT_IN: { - text += "call-built-in "; - - int argc = _code_ptr[ip + 2]; - text += DADDR(3 + argc) + " = "; - - text += GDScriptFunctions::get_func_name(GDScriptFunctions::Function(_code_ptr[ip + 1])); - text += "("; - - for (int i = 0; i < argc; i++) { - if (i > 0) - text += ", "; - text += DADDR(3 + i); - } - text += ")"; - - incr = 4 + argc; - } break; - case OPCODE_CALL_SELF_BASE: { - text += "call-self-base "; - - int argc = _code_ptr[ip + 2]; - text += DADDR(3 + argc) + " = "; - - text += _global_names_ptr[_code_ptr[ip + 1]]; - text += "("; - - for (int i = 0; i < argc; i++) { - if (i > 0) - text += ", "; - text += DADDR(3 + i); - } - text += ")"; - - incr = 4 + argc; - } break; - case OPCODE_AWAIT: { - text += "await "; - text += DADDR(1); - - incr += 2; - } break; - case OPCODE_AWAIT_RESUME: { - text += "await resume "; - text += DADDR(1); - - incr = 2; - } break; - case OPCODE_JUMP: { - text += "jump "; - text += itos(_code_ptr[ip + 1]); - - incr = 2; - } break; - case OPCODE_JUMP_IF: { - text += "jump-if "; - text += DADDR(1); - text += " to "; - text += itos(_code_ptr[ip + 2]); - - incr = 3; - } break; - case OPCODE_JUMP_IF_NOT: { - text += "jump-if-not "; - text += DADDR(1); - text += " to "; - text += itos(_code_ptr[ip + 2]); - - incr = 3; - } break; - case OPCODE_JUMP_TO_DEF_ARGUMENT: { - text += "jump-to-default-argument "; - - incr = 1; - } break; - case OPCODE_RETURN: { - text += "return "; - text += DADDR(1); - - incr = 2; - } break; - case OPCODE_ITERATE_BEGIN: { - text += "for-init "; - text += DADDR(4); - text += " in "; - text += DADDR(2); - text += " counter "; - text += DADDR(1); - text += " end "; - text += itos(_code_ptr[ip + 3]); - - incr += 5; - } break; - case OPCODE_ITERATE: { - text += "for-loop "; - text += DADDR(4); - text += " in "; - text += DADDR(2); - text += " counter "; - text += DADDR(1); - text += " end "; - text += itos(_code_ptr[ip + 3]); - - incr += 5; - } break; - case OPCODE_LINE: { - int line = _code_ptr[ip + 1] - 1; - if (line >= 0 && line < p_code_lines.size()) { - text += "line "; - text += itos(line + 1); - text += ": "; - text += p_code_lines[line]; - } else { - text += ""; - } - - incr += 2; - } break; - case OPCODE_ASSERT: { - text += "assert ("; - text += DADDR(1); - text += ", "; - text += DADDR(2); - text += ")"; - - incr += 3; - } break; - case OPCODE_BREAKPOINT: { - text += "breakpoint"; - - incr += 1; - } break; - case OPCODE_END: { - text += "== END =="; - - incr += 1; - } break; - } - - ip += incr; - if (text.get_string_length() > 0) { - print_line(text.as_string()); - } - } -} -#endif diff --git a/modules/gdscript/gdscript_function.h b/modules/gdscript/gdscript_function.h index 50eadcaf86..bb5cc1284d 100644 --- a/modules/gdscript/gdscript_function.h +++ b/modules/gdscript/gdscript_function.h @@ -159,12 +159,19 @@ class GDScriptFunction { public: enum Opcode { OPCODE_OPERATOR, + OPCODE_OPERATOR_VALIDATED, OPCODE_EXTENDS_TEST, OPCODE_IS_BUILTIN, - OPCODE_SET, - OPCODE_GET, + OPCODE_SET_KEYED, + OPCODE_SET_KEYED_VALIDATED, + OPCODE_SET_INDEXED_VALIDATED, + OPCODE_GET_KEYED, + OPCODE_GET_KEYED_VALIDATED, + OPCODE_GET_INDEXED_VALIDATED, OPCODE_SET_NAMED, + OPCODE_SET_NAMED_VALIDATED, OPCODE_GET_NAMED, + OPCODE_GET_NAMED_VALIDATED, OPCODE_SET_MEMBER, OPCODE_GET_MEMBER, OPCODE_ASSIGN, @@ -176,14 +183,54 @@ public: OPCODE_CAST_TO_BUILTIN, OPCODE_CAST_TO_NATIVE, OPCODE_CAST_TO_SCRIPT, - OPCODE_CONSTRUCT, //only for basic types!! + OPCODE_CONSTRUCT, // Only for basic types! + OPCODE_CONSTRUCT_VALIDATED, // Only for basic types! OPCODE_CONSTRUCT_ARRAY, OPCODE_CONSTRUCT_DICTIONARY, OPCODE_CALL, OPCODE_CALL_RETURN, OPCODE_CALL_ASYNC, OPCODE_CALL_BUILT_IN, + OPCODE_CALL_BUILTIN_TYPE_VALIDATED, OPCODE_CALL_SELF_BASE, + OPCODE_CALL_METHOD_BIND, + OPCODE_CALL_METHOD_BIND_RET, + // ptrcall have one instruction per return type. + OPCODE_CALL_PTRCALL_NO_RETURN, + OPCODE_CALL_PTRCALL_BOOL, + OPCODE_CALL_PTRCALL_INT, + OPCODE_CALL_PTRCALL_FLOAT, + OPCODE_CALL_PTRCALL_STRING, + OPCODE_CALL_PTRCALL_VECTOR2, + OPCODE_CALL_PTRCALL_VECTOR2I, + OPCODE_CALL_PTRCALL_RECT2, + OPCODE_CALL_PTRCALL_RECT2I, + OPCODE_CALL_PTRCALL_VECTOR3, + OPCODE_CALL_PTRCALL_VECTOR3I, + OPCODE_CALL_PTRCALL_TRANSFORM2D, + OPCODE_CALL_PTRCALL_PLANE, + OPCODE_CALL_PTRCALL_QUAT, + OPCODE_CALL_PTRCALL_AABB, + OPCODE_CALL_PTRCALL_BASIS, + OPCODE_CALL_PTRCALL_TRANSFORM, + OPCODE_CALL_PTRCALL_COLOR, + OPCODE_CALL_PTRCALL_STRING_NAME, + OPCODE_CALL_PTRCALL_NODE_PATH, + OPCODE_CALL_PTRCALL_RID, + OPCODE_CALL_PTRCALL_OBJECT, + OPCODE_CALL_PTRCALL_CALLABLE, + OPCODE_CALL_PTRCALL_SIGNAL, + OPCODE_CALL_PTRCALL_DICTIONARY, + OPCODE_CALL_PTRCALL_ARRAY, + OPCODE_CALL_PTRCALL_PACKED_BYTE_ARRAY, + OPCODE_CALL_PTRCALL_PACKED_INT32_ARRAY, + OPCODE_CALL_PTRCALL_PACKED_INT64_ARRAY, + OPCODE_CALL_PTRCALL_PACKED_FLOAT32_ARRAY, + OPCODE_CALL_PTRCALL_PACKED_FLOAT64_ARRAY, + OPCODE_CALL_PTRCALL_PACKED_STRING_ARRAY, + OPCODE_CALL_PTRCALL_PACKED_VECTOR2_ARRAY, + OPCODE_CALL_PTRCALL_PACKED_VECTOR3_ARRAY, + OPCODE_CALL_PTRCALL_PACKED_COLOR_ARRAY, OPCODE_AWAIT, OPCODE_AWAIT_RESUME, OPCODE_JUMP, @@ -192,7 +239,45 @@ public: OPCODE_JUMP_TO_DEF_ARGUMENT, OPCODE_RETURN, OPCODE_ITERATE_BEGIN, + OPCODE_ITERATE_BEGIN_INT, + OPCODE_ITERATE_BEGIN_FLOAT, + OPCODE_ITERATE_BEGIN_VECTOR2, + OPCODE_ITERATE_BEGIN_VECTOR2I, + OPCODE_ITERATE_BEGIN_VECTOR3, + OPCODE_ITERATE_BEGIN_VECTOR3I, + OPCODE_ITERATE_BEGIN_STRING, + OPCODE_ITERATE_BEGIN_DICTIONARY, + OPCODE_ITERATE_BEGIN_ARRAY, + OPCODE_ITERATE_BEGIN_PACKED_BYTE_ARRAY, + OPCODE_ITERATE_BEGIN_PACKED_INT32_ARRAY, + OPCODE_ITERATE_BEGIN_PACKED_INT64_ARRAY, + OPCODE_ITERATE_BEGIN_PACKED_FLOAT32_ARRAY, + OPCODE_ITERATE_BEGIN_PACKED_FLOAT64_ARRAY, + OPCODE_ITERATE_BEGIN_PACKED_STRING_ARRAY, + OPCODE_ITERATE_BEGIN_PACKED_VECTOR2_ARRAY, + OPCODE_ITERATE_BEGIN_PACKED_VECTOR3_ARRAY, + OPCODE_ITERATE_BEGIN_PACKED_COLOR_ARRAY, + OPCODE_ITERATE_BEGIN_OBJECT, OPCODE_ITERATE, + OPCODE_ITERATE_INT, + OPCODE_ITERATE_FLOAT, + OPCODE_ITERATE_VECTOR2, + OPCODE_ITERATE_VECTOR2I, + OPCODE_ITERATE_VECTOR3, + OPCODE_ITERATE_VECTOR3I, + OPCODE_ITERATE_STRING, + OPCODE_ITERATE_DICTIONARY, + OPCODE_ITERATE_ARRAY, + OPCODE_ITERATE_PACKED_BYTE_ARRAY, + OPCODE_ITERATE_PACKED_INT32_ARRAY, + OPCODE_ITERATE_PACKED_INT64_ARRAY, + OPCODE_ITERATE_PACKED_FLOAT32_ARRAY, + OPCODE_ITERATE_PACKED_FLOAT64_ARRAY, + OPCODE_ITERATE_PACKED_STRING_ARRAY, + OPCODE_ITERATE_PACKED_VECTOR2_ARRAY, + OPCODE_ITERATE_PACKED_VECTOR3_ARRAY, + OPCODE_ITERATE_PACKED_COLOR_ARRAY, + OPCODE_ITERATE_OBJECT, OPCODE_ASSERT, OPCODE_BREAKPOINT, OPCODE_LINE, @@ -215,6 +300,12 @@ public: ADDR_TYPE_NIL = 9 }; + enum Instruction { + INSTR_BITS = 20, + INSTR_MASK = ((1 << INSTR_BITS) - 1), + INSTR_ARGS_MASK = ~INSTR_MASK, + }; + struct StackDebug { int line; int pos; @@ -229,27 +320,59 @@ private: StringName source; mutable Variant nil; - mutable Variant *_constants_ptr; - int _constant_count; - const StringName *_global_names_ptr; - int _global_names_count; - const int *_default_arg_ptr; - int _default_arg_count; - const int *_code_ptr; - int _code_size; - int _argument_count; - int _stack_size; - int _call_size; - int _initial_line; - bool _static; - MultiplayerAPI::RPCMode rpc_mode; - - GDScript *_script; + mutable Variant *_constants_ptr = nullptr; + int _constant_count = 0; + const StringName *_global_names_ptr = nullptr; + int _global_names_count = 0; + const int *_default_arg_ptr = nullptr; + int _default_arg_count = 0; + int _operator_funcs_count = 0; + const Variant::ValidatedOperatorEvaluator *_operator_funcs_ptr = nullptr; + int _setters_count = 0; + const Variant::ValidatedSetter *_setters_ptr = nullptr; + int _getters_count = 0; + const Variant::ValidatedGetter *_getters_ptr = nullptr; + int _keyed_setters_count = 0; + const Variant::ValidatedKeyedSetter *_keyed_setters_ptr = nullptr; + int _keyed_getters_count = 0; + const Variant::ValidatedKeyedGetter *_keyed_getters_ptr = nullptr; + int _indexed_setters_count = 0; + const Variant::ValidatedIndexedSetter *_indexed_setters_ptr = nullptr; + int _indexed_getters_count = 0; + const Variant::ValidatedIndexedGetter *_indexed_getters_ptr = nullptr; + int _builtin_methods_count = 0; + const Variant::ValidatedBuiltInMethod *_builtin_methods_ptr = nullptr; + int _constructors_count = 0; + const Variant::ValidatedConstructor *_constructors_ptr = nullptr; + int _methods_count = 0; + MethodBind **_methods_ptr = nullptr; + const int *_code_ptr = nullptr; + int _code_size = 0; + int _argument_count = 0; + int _stack_size = 0; + int _instruction_args_size = 0; + int _ptrcall_args_size = 0; + + int _initial_line = 0; + bool _static = false; + MultiplayerAPI::RPCMode rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED; + + GDScript *_script = nullptr; StringName name; Vector<Variant> constants; Vector<StringName> global_names; Vector<int> default_arguments; + Vector<Variant::ValidatedOperatorEvaluator> operator_funcs; + Vector<Variant::ValidatedSetter> setters; + Vector<Variant::ValidatedGetter> getters; + Vector<Variant::ValidatedKeyedSetter> keyed_setters; + Vector<Variant::ValidatedKeyedGetter> keyed_getters; + Vector<Variant::ValidatedIndexedSetter> indexed_setters; + Vector<Variant::ValidatedIndexedGetter> indexed_getters; + Vector<Variant::ValidatedBuiltInMethod> builtin_methods; + Vector<Variant::ValidatedConstructor> constructors; + Vector<MethodBind *> methods; Vector<int> code; Vector<GDScriptDataType> argument_types; GDScriptDataType return_type; @@ -265,22 +388,22 @@ private: friend class GDScriptLanguage; - SelfList<GDScriptFunction> function_list; + SelfList<GDScriptFunction> function_list{ this }; #ifdef DEBUG_ENABLED CharString func_cname; - const char *_func_cname; + const char *_func_cname = nullptr; struct Profile { StringName signature; - uint64_t call_count; - uint64_t self_time; - uint64_t total_time; - uint64_t frame_call_count; - uint64_t frame_self_time; - uint64_t frame_total_time; - uint64_t last_frame_call_count; - uint64_t last_frame_self_time; - uint64_t last_frame_total_time; + uint64_t call_count = 0; + uint64_t self_time = 0; + uint64_t total_time = 0; + uint64_t frame_call_count = 0; + uint64_t frame_self_time = 0; + uint64_t frame_total_time = 0; + uint64_t last_frame_call_count = 0; + uint64_t last_frame_self_time = 0; + uint64_t last_frame_total_time = 0; } profile; #endif diff --git a/modules/gdscript/gdscript_parser.cpp b/modules/gdscript/gdscript_parser.cpp index fde3662d66..372af204f5 100644 --- a/modules/gdscript/gdscript_parser.cpp +++ b/modules/gdscript/gdscript_parser.cpp @@ -184,6 +184,7 @@ void GDScriptParser::push_error(const String &p_message, const Node *p_origin) { #ifdef DEBUG_ENABLED void GDScriptParser::push_warning(const Node *p_source, GDScriptWarning::Code p_code, const String &p_symbol1, const String &p_symbol2, const String &p_symbol3, const String &p_symbol4) { + ERR_FAIL_COND(p_source == nullptr); Vector<String> symbols; if (!p_symbol1.empty()) { symbols.push_back(p_symbol1); @@ -201,6 +202,7 @@ void GDScriptParser::push_warning(const Node *p_source, GDScriptWarning::Code p_ } void GDScriptParser::push_warning(const Node *p_source, GDScriptWarning::Code p_code, const Vector<String> &p_symbols) { + ERR_FAIL_COND(p_source == nullptr); if (is_ignoring_warnings) { return; } @@ -1419,9 +1421,13 @@ GDScriptParser::Node *GDScriptParser::parse_statement() { } #ifdef DEBUG_ENABLED - if (unreachable) { + if (unreachable && result != nullptr) { current_suite->has_unreachable_code = true; - push_warning(result, GDScriptWarning::UNREACHABLE_CODE, current_function->identifier->name); + if (current_function) { + push_warning(result, GDScriptWarning::UNREACHABLE_CODE, current_function->identifier->name); + } else { + // TODO: Properties setters and getters with unreachable code are not being warned + } } #endif diff --git a/modules/gdscript/gdscript_vm.cpp b/modules/gdscript/gdscript_vm.cpp new file mode 100644 index 0000000000..7942ee8d97 --- /dev/null +++ b/modules/gdscript/gdscript_vm.cpp @@ -0,0 +1,2863 @@ +/*************************************************************************/ +/* gdscript_vm.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 "gdscript_function.h" + +#include "core/core_string_names.h" +#include "core/os/os.h" +#include "gdscript.h" +#include "gdscript_functions.h" + +Variant *GDScriptFunction::_get_variant(int p_address, GDScriptInstance *p_instance, GDScript *p_script, Variant &self, Variant &static_ref, Variant *p_stack, String &r_error) const { + int address = p_address & ADDR_MASK; + + //sequential table (jump table generated by compiler) + switch ((p_address & ADDR_TYPE_MASK) >> ADDR_BITS) { + case ADDR_TYPE_SELF: { +#ifdef DEBUG_ENABLED + if (unlikely(!p_instance)) { + r_error = "Cannot access self without instance."; + return nullptr; + } +#endif + return &self; + } break; + case ADDR_TYPE_CLASS: { + return &static_ref; + } break; + case ADDR_TYPE_MEMBER: { +#ifdef DEBUG_ENABLED + if (unlikely(!p_instance)) { + r_error = "Cannot access member without instance."; + return nullptr; + } +#endif + //member indexing is O(1) + return &p_instance->members.write[address]; + } break; + case ADDR_TYPE_CLASS_CONSTANT: { + //todo change to index! + GDScript *s = p_script; +#ifdef DEBUG_ENABLED + ERR_FAIL_INDEX_V(address, _global_names_count, nullptr); +#endif + const StringName *sn = &_global_names_ptr[address]; + + while (s) { + GDScript *o = s; + while (o) { + Map<StringName, Variant>::Element *E = o->constants.find(*sn); + if (E) { + return &E->get(); + } + o = o->_owner; + } + s = s->_base; + } + + ERR_FAIL_V_MSG(nullptr, "GDScriptCompiler bug."); + } break; + case ADDR_TYPE_LOCAL_CONSTANT: { +#ifdef DEBUG_ENABLED + ERR_FAIL_INDEX_V(address, _constant_count, nullptr); +#endif + return &_constants_ptr[address]; + } break; + case ADDR_TYPE_STACK: + case ADDR_TYPE_STACK_VARIABLE: { +#ifdef DEBUG_ENABLED + ERR_FAIL_INDEX_V(address, _stack_size, nullptr); +#endif + return &p_stack[address]; + } break; + case ADDR_TYPE_GLOBAL: { +#ifdef DEBUG_ENABLED + ERR_FAIL_INDEX_V(address, GDScriptLanguage::get_singleton()->get_global_array_size(), nullptr); +#endif + return &GDScriptLanguage::get_singleton()->get_global_array()[address]; + } break; +#ifdef TOOLS_ENABLED + case ADDR_TYPE_NAMED_GLOBAL: { +#ifdef DEBUG_ENABLED + ERR_FAIL_INDEX_V(address, _global_names_count, nullptr); +#endif + StringName id = _global_names_ptr[address]; + + if (GDScriptLanguage::get_singleton()->get_named_globals_map().has(id)) { + return (Variant *)&GDScriptLanguage::get_singleton()->get_named_globals_map()[id]; + } else { + r_error = "Autoload singleton '" + String(id) + "' has been removed."; + return nullptr; + } + } break; +#endif + case ADDR_TYPE_NIL: { + return &nil; + } break; + } + + ERR_FAIL_V_MSG(nullptr, "Bad code! (unknown addressing mode)."); + return nullptr; +} + +#ifdef DEBUG_ENABLED +static String _get_var_type(const Variant *p_var) { + String basestr; + + if (p_var->get_type() == Variant::OBJECT) { + bool was_freed; + Object *bobj = p_var->get_validated_object_with_check(was_freed); + if (!bobj) { + if (was_freed) { + basestr = "null instance"; + } else { + basestr = "previously freed"; + } + } else { + if (bobj->get_script_instance()) { + basestr = bobj->get_class() + " (" + bobj->get_script_instance()->get_script()->get_path().get_file() + ")"; + } else { + basestr = bobj->get_class(); + } + } + + } else { + basestr = Variant::get_type_name(p_var->get_type()); + } + + return basestr; +} +#endif // DEBUG_ENABLED + +String GDScriptFunction::_get_call_error(const Callable::CallError &p_err, const String &p_where, const Variant **argptrs) const { + String err_text; + + if (p_err.error == Callable::CallError::CALL_ERROR_INVALID_ARGUMENT) { + int errorarg = p_err.argument; + // Handle the Object to Object case separately as we don't have further class details. +#ifdef DEBUG_ENABLED + if (p_err.expected == Variant::OBJECT && argptrs[errorarg]->get_type() == p_err.expected) { + err_text = "Invalid type in " + p_where + ". The Object-derived class of argument " + itos(errorarg + 1) + " (" + _get_var_type(argptrs[errorarg]) + ") is not a subclass of the expected argument class."; + } else +#endif // DEBUG_ENABLED + { + err_text = "Invalid type in " + p_where + ". Cannot convert argument " + itos(errorarg + 1) + " from " + Variant::get_type_name(argptrs[errorarg]->get_type()) + " to " + Variant::get_type_name(Variant::Type(p_err.expected)) + "."; + } + } else if (p_err.error == Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) { + err_text = "Invalid call to " + p_where + ". Expected " + itos(p_err.argument) + " arguments."; + } else if (p_err.error == Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) { + err_text = "Invalid call to " + p_where + ". Expected " + itos(p_err.argument) + " arguments."; + } else if (p_err.error == Callable::CallError::CALL_ERROR_INVALID_METHOD) { + err_text = "Invalid call. Nonexistent " + p_where + "."; + } else if (p_err.error == Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL) { + err_text = "Attempt to call " + p_where + " on a null instance."; + } else { + err_text = "Bug, call error: #" + itos(p_err.error); + } + + return err_text; +} + +#if defined(__GNUC__) +#define OPCODES_TABLE \ + static const void *switch_table_ops[] = { \ + &&OPCODE_OPERATOR, \ + &&OPCODE_OPERATOR_VALIDATED, \ + &&OPCODE_EXTENDS_TEST, \ + &&OPCODE_IS_BUILTIN, \ + &&OPCODE_SET_KEYED, \ + &&OPCODE_SET_KEYED_VALIDATED, \ + &&OPCODE_SET_INDEXED_VALIDATED, \ + &&OPCODE_GET_KEYED, \ + &&OPCODE_GET_KEYED_VALIDATED, \ + &&OPCODE_GET_INDEXED_VALIDATED, \ + &&OPCODE_SET_NAMED, \ + &&OPCODE_SET_NAMED_VALIDATED, \ + &&OPCODE_GET_NAMED, \ + &&OPCODE_GET_NAMED_VALIDATED, \ + &&OPCODE_SET_MEMBER, \ + &&OPCODE_GET_MEMBER, \ + &&OPCODE_ASSIGN, \ + &&OPCODE_ASSIGN_TRUE, \ + &&OPCODE_ASSIGN_FALSE, \ + &&OPCODE_ASSIGN_TYPED_BUILTIN, \ + &&OPCODE_ASSIGN_TYPED_NATIVE, \ + &&OPCODE_ASSIGN_TYPED_SCRIPT, \ + &&OPCODE_CAST_TO_BUILTIN, \ + &&OPCODE_CAST_TO_NATIVE, \ + &&OPCODE_CAST_TO_SCRIPT, \ + &&OPCODE_CONSTRUCT, \ + &&OPCODE_CONSTRUCT_VALIDATED, \ + &&OPCODE_CONSTRUCT_ARRAY, \ + &&OPCODE_CONSTRUCT_DICTIONARY, \ + &&OPCODE_CALL, \ + &&OPCODE_CALL_RETURN, \ + &&OPCODE_CALL_ASYNC, \ + &&OPCODE_CALL_BUILT_IN, \ + &&OPCODE_CALL_BUILTIN_TYPE_VALIDATED, \ + &&OPCODE_CALL_SELF_BASE, \ + &&OPCODE_CALL_METHOD_BIND, \ + &&OPCODE_CALL_METHOD_BIND_RET, \ + &&OPCODE_CALL_PTRCALL_NO_RETURN, \ + &&OPCODE_CALL_PTRCALL_BOOL, \ + &&OPCODE_CALL_PTRCALL_INT, \ + &&OPCODE_CALL_PTRCALL_FLOAT, \ + &&OPCODE_CALL_PTRCALL_STRING, \ + &&OPCODE_CALL_PTRCALL_VECTOR2, \ + &&OPCODE_CALL_PTRCALL_VECTOR2I, \ + &&OPCODE_CALL_PTRCALL_RECT2, \ + &&OPCODE_CALL_PTRCALL_RECT2I, \ + &&OPCODE_CALL_PTRCALL_VECTOR3, \ + &&OPCODE_CALL_PTRCALL_VECTOR3I, \ + &&OPCODE_CALL_PTRCALL_TRANSFORM2D, \ + &&OPCODE_CALL_PTRCALL_PLANE, \ + &&OPCODE_CALL_PTRCALL_QUAT, \ + &&OPCODE_CALL_PTRCALL_AABB, \ + &&OPCODE_CALL_PTRCALL_BASIS, \ + &&OPCODE_CALL_PTRCALL_TRANSFORM, \ + &&OPCODE_CALL_PTRCALL_COLOR, \ + &&OPCODE_CALL_PTRCALL_STRING_NAME, \ + &&OPCODE_CALL_PTRCALL_NODE_PATH, \ + &&OPCODE_CALL_PTRCALL_RID, \ + &&OPCODE_CALL_PTRCALL_OBJECT, \ + &&OPCODE_CALL_PTRCALL_CALLABLE, \ + &&OPCODE_CALL_PTRCALL_SIGNAL, \ + &&OPCODE_CALL_PTRCALL_DICTIONARY, \ + &&OPCODE_CALL_PTRCALL_ARRAY, \ + &&OPCODE_CALL_PTRCALL_PACKED_BYTE_ARRAY, \ + &&OPCODE_CALL_PTRCALL_PACKED_INT32_ARRAY, \ + &&OPCODE_CALL_PTRCALL_PACKED_INT64_ARRAY, \ + &&OPCODE_CALL_PTRCALL_PACKED_FLOAT32_ARRAY, \ + &&OPCODE_CALL_PTRCALL_PACKED_FLOAT64_ARRAY, \ + &&OPCODE_CALL_PTRCALL_PACKED_STRING_ARRAY, \ + &&OPCODE_CALL_PTRCALL_PACKED_VECTOR2_ARRAY, \ + &&OPCODE_CALL_PTRCALL_PACKED_VECTOR3_ARRAY, \ + &&OPCODE_CALL_PTRCALL_PACKED_COLOR_ARRAY, \ + &&OPCODE_AWAIT, \ + &&OPCODE_AWAIT_RESUME, \ + &&OPCODE_JUMP, \ + &&OPCODE_JUMP_IF, \ + &&OPCODE_JUMP_IF_NOT, \ + &&OPCODE_JUMP_TO_DEF_ARGUMENT, \ + &&OPCODE_RETURN, \ + &&OPCODE_ITERATE_BEGIN, \ + &&OPCODE_ITERATE_BEGIN_INT, \ + &&OPCODE_ITERATE_BEGIN_FLOAT, \ + &&OPCODE_ITERATE_BEGIN_VECTOR2, \ + &&OPCODE_ITERATE_BEGIN_VECTOR2I, \ + &&OPCODE_ITERATE_BEGIN_VECTOR3, \ + &&OPCODE_ITERATE_BEGIN_VECTOR3I, \ + &&OPCODE_ITERATE_BEGIN_STRING, \ + &&OPCODE_ITERATE_BEGIN_DICTIONARY, \ + &&OPCODE_ITERATE_BEGIN_ARRAY, \ + &&OPCODE_ITERATE_BEGIN_PACKED_BYTE_ARRAY, \ + &&OPCODE_ITERATE_BEGIN_PACKED_INT32_ARRAY, \ + &&OPCODE_ITERATE_BEGIN_PACKED_INT64_ARRAY, \ + &&OPCODE_ITERATE_BEGIN_PACKED_FLOAT32_ARRAY, \ + &&OPCODE_ITERATE_BEGIN_PACKED_FLOAT64_ARRAY, \ + &&OPCODE_ITERATE_BEGIN_PACKED_STRING_ARRAY, \ + &&OPCODE_ITERATE_BEGIN_PACKED_VECTOR2_ARRAY, \ + &&OPCODE_ITERATE_BEGIN_PACKED_VECTOR3_ARRAY, \ + &&OPCODE_ITERATE_BEGIN_PACKED_COLOR_ARRAY, \ + &&OPCODE_ITERATE_BEGIN_OBJECT, \ + &&OPCODE_ITERATE, \ + &&OPCODE_ITERATE_INT, \ + &&OPCODE_ITERATE_FLOAT, \ + &&OPCODE_ITERATE_VECTOR2, \ + &&OPCODE_ITERATE_VECTOR2I, \ + &&OPCODE_ITERATE_VECTOR3, \ + &&OPCODE_ITERATE_VECTOR3I, \ + &&OPCODE_ITERATE_STRING, \ + &&OPCODE_ITERATE_DICTIONARY, \ + &&OPCODE_ITERATE_ARRAY, \ + &&OPCODE_ITERATE_PACKED_BYTE_ARRAY, \ + &&OPCODE_ITERATE_PACKED_INT32_ARRAY, \ + &&OPCODE_ITERATE_PACKED_INT64_ARRAY, \ + &&OPCODE_ITERATE_PACKED_FLOAT32_ARRAY, \ + &&OPCODE_ITERATE_PACKED_FLOAT64_ARRAY, \ + &&OPCODE_ITERATE_PACKED_STRING_ARRAY, \ + &&OPCODE_ITERATE_PACKED_VECTOR2_ARRAY, \ + &&OPCODE_ITERATE_PACKED_VECTOR3_ARRAY, \ + &&OPCODE_ITERATE_PACKED_COLOR_ARRAY, \ + &&OPCODE_ITERATE_OBJECT, \ + &&OPCODE_ASSERT, \ + &&OPCODE_BREAKPOINT, \ + &&OPCODE_LINE, \ + &&OPCODE_END \ + }; \ + static_assert((sizeof(switch_table_ops) / sizeof(switch_table_ops[0]) == (OPCODE_END + 1)), "Opcodes in jump table aren't the same as opcodes in enum."); + +#define OPCODE(m_op) \ + m_op: +#define OPCODE_WHILE(m_test) \ + OPSWHILE: +#define OPCODES_END \ + OPSEXIT: +#define OPCODES_OUT \ + OPSOUT: +#define DISPATCH_OPCODE goto OPSWHILE +#define OPCODE_SWITCH(m_test) goto *switch_table_ops[m_test]; +#define OPCODE_BREAK goto OPSEXIT +#define OPCODE_OUT goto OPSOUT +#else +#define OPCODES_TABLE +#define OPCODE(m_op) case m_op: +#define OPCODE_WHILE(m_test) while (m_test) +#define OPCODES_END +#define OPCODES_OUT +#define DISPATCH_OPCODE continue +#define OPCODE_SWITCH(m_test) switch (m_test) +#define OPCODE_BREAK break +#define OPCODE_OUT break +#endif + +// Helpers for VariantInternal methods in macros. +#define OP_GET_BOOL get_bool +#define OP_GET_INT get_int +#define OP_GET_FLOAT get_float +#define OP_GET_VECTOR2 get_vector2 +#define OP_GET_VECTOR2I get_vector2i +#define OP_GET_VECTOR3 get_vector3 +#define OP_GET_VECTOR3I get_vector3i +#define OP_GET_RECT2 get_rect2 +#define OP_GET_RECT2I get_rect2i +#define OP_GET_QUAT get_quat +#define OP_GET_COLOR get_color +#define OP_GET_STRING get_string +#define OP_GET_STRING_NAME get_string_name +#define OP_GET_NODE_PATH get_node_path +#define OP_GET_CALLABLE get_callable +#define OP_GET_SIGNAL get_signal +#define OP_GET_ARRAY get_array +#define OP_GET_DICTIONARY get_dictionary +#define OP_GET_PACKED_BYTE_ARRAY get_byte_array +#define OP_GET_PACKED_INT32_ARRAY get_int32_array +#define OP_GET_PACKED_INT64_ARRAY get_int64_array +#define OP_GET_PACKED_FLOAT32_ARRAY get_float32_array +#define OP_GET_PACKED_FLOAT64_ARRAY get_float64_array +#define OP_GET_PACKED_STRING_ARRAY get_string_array +#define OP_GET_PACKED_VECTOR2_ARRAY get_vector2_array +#define OP_GET_PACKED_VECTOR3_ARRAY get_vector3_array +#define OP_GET_PACKED_COLOR_ARRAY get_color_array +#define OP_GET_TRANSFORM get_transform +#define OP_GET_TRANSFORM2D get_transform2d +#define OP_GET_PLANE get_plane +#define OP_GET_AABB get_aabb +#define OP_GET_BASIS get_basis +#define OP_GET_RID get_rid + +Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_args, int p_argcount, Callable::CallError &r_err, CallState *p_state) { + OPCODES_TABLE; + + if (!_code_ptr) { + return Variant(); + } + + r_err.error = Callable::CallError::CALL_OK; + + Variant self; + Variant static_ref; + Variant retvalue; + Variant *stack = nullptr; + Variant **instruction_args; + const void **call_args_ptr = nullptr; + int defarg = 0; + +#ifdef DEBUG_ENABLED + + //GDScriptLanguage::get_singleton()->calls++; + +#endif + + uint32_t alloca_size = 0; + GDScript *script; + int ip = 0; + int line = _initial_line; + + if (p_state) { + //use existing (supplied) state (awaited) + stack = (Variant *)p_state->stack.ptr(); + instruction_args = (Variant **)&p_state->stack.ptr()[sizeof(Variant) * p_state->stack_size]; //ptr() to avoid bounds check + line = p_state->line; + ip = p_state->ip; + alloca_size = p_state->stack.size(); + script = p_state->script; + p_instance = p_state->instance; + defarg = p_state->defarg; + self = p_state->self; + + } else { + if (p_argcount != _argument_count) { + if (p_argcount > _argument_count) { + r_err.error = Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; + r_err.argument = _argument_count; + + return Variant(); + } else if (p_argcount < _argument_count - _default_arg_count) { + r_err.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; + r_err.argument = _argument_count - _default_arg_count; + return Variant(); + } else { + defarg = _argument_count - p_argcount; + } + } + + alloca_size = sizeof(Variant *) * _instruction_args_size + sizeof(Variant) * _stack_size; + + if (alloca_size) { + uint8_t *aptr = (uint8_t *)alloca(alloca_size); + + if (_stack_size) { + stack = (Variant *)aptr; + for (int i = 0; i < p_argcount; i++) { + if (!argument_types[i].has_type) { + memnew_placement(&stack[i], Variant(*p_args[i])); + continue; + } + + if (!argument_types[i].is_type(*p_args[i], true)) { + r_err.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_err.argument = i; + r_err.expected = argument_types[i].kind == GDScriptDataType::BUILTIN ? argument_types[i].builtin_type : Variant::OBJECT; + return Variant(); + } + if (argument_types[i].kind == GDScriptDataType::BUILTIN) { + Variant arg; + Variant::construct(argument_types[i].builtin_type, arg, &p_args[i], 1, r_err); + memnew_placement(&stack[i], Variant(arg)); + } else { + memnew_placement(&stack[i], Variant(*p_args[i])); + } + } + for (int i = p_argcount; i < _stack_size; i++) { + memnew_placement(&stack[i], Variant); + } + } else { + stack = nullptr; + } + + if (_instruction_args_size) { + instruction_args = (Variant **)&aptr[sizeof(Variant) * _stack_size]; + } else { + instruction_args = nullptr; + } + + } else { + stack = nullptr; + instruction_args = nullptr; + } + + if (p_instance) { + if (p_instance->base_ref && static_cast<Reference *>(p_instance->owner)->is_referenced()) { + self = REF(static_cast<Reference *>(p_instance->owner)); + } else { + self = p_instance->owner; + } + script = p_instance->script.ptr(); + } else { + script = _script; + } + } + if (_ptrcall_args_size) { + call_args_ptr = (const void **)alloca(_ptrcall_args_size * sizeof(void *)); + } else { + call_args_ptr = nullptr; + } + + static_ref = script; + + String err_text; + +#ifdef DEBUG_ENABLED + + if (EngineDebugger::is_active()) { + GDScriptLanguage::get_singleton()->enter_function(p_instance, this, stack, &ip, &line); + } + +#define GD_ERR_BREAK(m_cond) \ + { \ + if (unlikely(m_cond)) { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Condition ' " _STR(m_cond) " ' is true. Breaking..:"); \ + OPCODE_BREAK; \ + } \ + } + +#define CHECK_SPACE(m_space) \ + GD_ERR_BREAK((ip + m_space) > _code_size) + +#define GET_VARIANT_PTR(m_v, m_code_ofs) \ + Variant *m_v; \ + m_v = _get_variant(_code_ptr[ip + m_code_ofs], p_instance, script, self, static_ref, stack, err_text); \ + if (unlikely(!m_v)) \ + OPCODE_BREAK; + +#else +#define GD_ERR_BREAK(m_cond) +#define CHECK_SPACE(m_space) +#define GET_VARIANT_PTR(m_v, m_code_ofs) \ + Variant *m_v; \ + m_v = _get_variant(_code_ptr[ip + m_code_ofs], p_instance, script, self, static_ref, stack, err_text); + +#endif + +#define GET_INSTRUCTION_ARG(m_v, m_idx) \ + Variant *m_v = instruction_args[m_idx] + +#ifdef DEBUG_ENABLED + + uint64_t function_start_time = 0; + uint64_t function_call_time = 0; + + if (GDScriptLanguage::get_singleton()->profiling) { + function_start_time = OS::get_singleton()->get_ticks_usec(); + function_call_time = 0; + profile.call_count++; + profile.frame_call_count++; + } + bool exit_ok = false; + bool awaited = false; +#endif + +#ifdef DEBUG_ENABLED + OPCODE_WHILE(ip < _code_size) { + int last_opcode = _code_ptr[ip]; +#else + OPCODE_WHILE(true) { +#endif + // Load arguments for the instruction before each instruction. + int instr_arg_count = ((_code_ptr[ip]) & INSTR_ARGS_MASK) >> INSTR_BITS; + for (int i = 0; i < instr_arg_count; i++) { + GET_VARIANT_PTR(v, i + 1); + instruction_args[i] = v; + } + + OPCODE_SWITCH(_code_ptr[ip] & INSTR_MASK) { + OPCODE(OPCODE_OPERATOR) { + CHECK_SPACE(5); + + bool valid; + Variant::Operator op = (Variant::Operator)_code_ptr[ip + 4]; + GD_ERR_BREAK(op >= Variant::OP_MAX); + + GET_INSTRUCTION_ARG(a, 0); + GET_INSTRUCTION_ARG(b, 1); + GET_INSTRUCTION_ARG(dst, 2); + +#ifdef DEBUG_ENABLED + + Variant ret; + Variant::evaluate(op, *a, *b, ret, valid); +#else + Variant::evaluate(op, *a, *b, *dst, valid); +#endif +#ifdef DEBUG_ENABLED + if (!valid) { + if (ret.get_type() == Variant::STRING) { + //return a string when invalid with the error + err_text = ret; + err_text += " in operator '" + Variant::get_operator_name(op) + "'."; + } else { + err_text = "Invalid operands '" + Variant::get_type_name(a->get_type()) + "' and '" + Variant::get_type_name(b->get_type()) + "' in operator '" + Variant::get_operator_name(op) + "'."; + } + OPCODE_BREAK; + } + *dst = ret; +#endif + ip += 5; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_OPERATOR_VALIDATED) { + CHECK_SPACE(5); + + int operator_idx = _code_ptr[ip + 4]; + GD_ERR_BREAK(operator_idx < 0 || operator_idx >= _operator_funcs_count); + Variant::ValidatedOperatorEvaluator operator_func = _operator_funcs_ptr[operator_idx]; + + GET_INSTRUCTION_ARG(a, 0); + GET_INSTRUCTION_ARG(b, 1); + GET_INSTRUCTION_ARG(dst, 2); + + operator_func(a, b, dst); + + ip += 5; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_EXTENDS_TEST) { + CHECK_SPACE(4); + + GET_INSTRUCTION_ARG(a, 0); + GET_INSTRUCTION_ARG(b, 1); + GET_INSTRUCTION_ARG(dst, 2); + +#ifdef DEBUG_ENABLED + if (b->get_type() != Variant::OBJECT || b->operator Object *() == nullptr) { + err_text = "Right operand of 'is' is not a class."; + OPCODE_BREAK; + } +#endif + + bool extends_ok = false; + if (a->get_type() == Variant::OBJECT && a->operator Object *() != nullptr) { +#ifdef DEBUG_ENABLED + bool was_freed; + Object *obj_A = a->get_validated_object_with_check(was_freed); + + if (was_freed) { + err_text = "Left operand of 'is' is a previously freed instance."; + OPCODE_BREAK; + } + + Object *obj_B = b->get_validated_object_with_check(was_freed); + + if (was_freed) { + err_text = "Right operand of 'is' is a previously freed instance."; + OPCODE_BREAK; + } +#else + + Object *obj_A = *a; + Object *obj_B = *b; +#endif // DEBUG_ENABLED + + GDScript *scr_B = Object::cast_to<GDScript>(obj_B); + + if (scr_B) { + //if B is a script, the only valid condition is that A has an instance which inherits from the script + //in other situation, this shoul return false. + + if (obj_A->get_script_instance() && obj_A->get_script_instance()->get_language() == GDScriptLanguage::get_singleton()) { + GDScript *cmp = static_cast<GDScript *>(obj_A->get_script_instance()->get_script().ptr()); + //bool found=false; + while (cmp) { + if (cmp == scr_B) { + //inherits from script, all ok + extends_ok = true; + break; + } + + cmp = cmp->_base; + } + } + + } else { + GDScriptNativeClass *nc = Object::cast_to<GDScriptNativeClass>(obj_B); + +#ifdef DEBUG_ENABLED + if (!nc) { + err_text = "Right operand of 'is' is not a class (type: '" + obj_B->get_class() + "')."; + OPCODE_BREAK; + } +#endif + extends_ok = ClassDB::is_parent_class(obj_A->get_class_name(), nc->get_name()); + } + } + + *dst = extends_ok; + ip += 4; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_IS_BUILTIN) { + CHECK_SPACE(4); + + GET_INSTRUCTION_ARG(value, 0); + GET_INSTRUCTION_ARG(dst, 1); + Variant::Type var_type = (Variant::Type)_code_ptr[ip + 3]; + + GD_ERR_BREAK(var_type < 0 || var_type >= Variant::VARIANT_MAX); + + *dst = value->get_type() == var_type; + ip += 4; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_SET_KEYED) { + CHECK_SPACE(3); + + GET_INSTRUCTION_ARG(dst, 0); + GET_INSTRUCTION_ARG(index, 1); + GET_INSTRUCTION_ARG(value, 2); + + bool valid; + dst->set(*index, *value, &valid); + +#ifdef DEBUG_ENABLED + if (!valid) { + String v = index->operator String(); + if (v != "") { + v = "'" + v + "'"; + } else { + v = "of type '" + _get_var_type(index) + "'"; + } + err_text = "Invalid set index " + v + " (on base: '" + _get_var_type(dst) + "') with value of type '" + _get_var_type(value) + "'"; + OPCODE_BREAK; + } +#endif + ip += 4; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_SET_KEYED_VALIDATED) { + CHECK_SPACE(4); + + GET_INSTRUCTION_ARG(dst, 0); + GET_INSTRUCTION_ARG(index, 1); + GET_INSTRUCTION_ARG(value, 2); + + int index_setter = _code_ptr[ip + 4]; + GD_ERR_BREAK(index_setter < 0 || index_setter >= _keyed_setters_count); + const Variant::ValidatedKeyedSetter setter = _keyed_setters_ptr[index_setter]; + + bool valid; + setter(dst, index, value, valid); + +#ifdef DEBUG_ENABLED + if (!valid) { + String v = index->operator String(); + if (v != "") { + v = "'" + v + "'"; + } else { + v = "of type '" + _get_var_type(index) + "'"; + } + err_text = "Invalid set index " + v + " (on base: '" + _get_var_type(dst) + "') with value of type '" + _get_var_type(value) + "'"; + OPCODE_BREAK; + } +#endif + ip += 5; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_SET_INDEXED_VALIDATED) { + CHECK_SPACE(4); + + GET_INSTRUCTION_ARG(dst, 0); + GET_INSTRUCTION_ARG(index, 1); + GET_INSTRUCTION_ARG(value, 2); + + int index_setter = _code_ptr[ip + 4]; + GD_ERR_BREAK(index_setter < 0 || index_setter >= _indexed_setters_count); + const Variant::ValidatedIndexedSetter setter = _indexed_setters_ptr[index_setter]; + + int64_t int_index = *VariantInternal::get_int(index); + + bool oob; + setter(dst, int_index, value, oob); + +#ifdef DEBUG_ENABLED + if (oob) { + String v = index->operator String(); + if (v != "") { + v = "'" + v + "'"; + } else { + v = "of type '" + _get_var_type(index) + "'"; + } + err_text = "Out of bounds set index " + v + " (on base: '" + _get_var_type(dst) + "')"; + OPCODE_BREAK; + } +#endif + ip += 5; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_GET_KEYED) { + CHECK_SPACE(3); + + GET_INSTRUCTION_ARG(src, 0); + GET_INSTRUCTION_ARG(index, 1); + GET_INSTRUCTION_ARG(dst, 2); + + bool valid; +#ifdef DEBUG_ENABLED + // Allow better error message in cases where src and dst are the same stack position. + Variant ret = src->get(*index, &valid); +#else + *dst = src->get(*index, &valid); + +#endif +#ifdef DEBUG_ENABLED + if (!valid) { + String v = index->operator String(); + if (v != "") { + v = "'" + v + "'"; + } else { + v = "of type '" + _get_var_type(index) + "'"; + } + err_text = "Invalid get index " + v + " (on base: '" + _get_var_type(src) + "')."; + OPCODE_BREAK; + } + *dst = ret; +#endif + ip += 4; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_GET_KEYED_VALIDATED) { + CHECK_SPACE(4); + + GET_INSTRUCTION_ARG(src, 0); + GET_INSTRUCTION_ARG(key, 1); + GET_INSTRUCTION_ARG(dst, 2); + + int index_getter = _code_ptr[ip + 4]; + GD_ERR_BREAK(index_getter < 0 || index_getter >= _keyed_getters_count); + const Variant::ValidatedKeyedGetter getter = _keyed_getters_ptr[index_getter]; + + bool valid; +#ifdef DEBUG_ENABLED + // Allow better error message in cases where src and dst are the same stack position. + Variant ret; + getter(src, key, &ret, valid); +#else + getter(src, key, dst, valid); +#endif +#ifdef DEBUG_ENABLED + if (!valid) { + String v = key->operator String(); + if (v != "") { + v = "'" + v + "'"; + } else { + v = "of type '" + _get_var_type(key) + "'"; + } + err_text = "Invalid get index " + v + " (on base: '" + _get_var_type(src) + "')."; + OPCODE_BREAK; + } + *dst = ret; +#endif + ip += 5; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_GET_INDEXED_VALIDATED) { + CHECK_SPACE(4); + + GET_INSTRUCTION_ARG(src, 0); + GET_INSTRUCTION_ARG(index, 1); + GET_INSTRUCTION_ARG(dst, 2); + + int index_getter = _code_ptr[ip + 4]; + GD_ERR_BREAK(index_getter < 0 || index_getter >= _indexed_getters_count); + const Variant::ValidatedIndexedGetter getter = _indexed_getters_ptr[index_getter]; + + int64_t int_index = *VariantInternal::get_int(index); + + bool oob; + getter(src, int_index, dst, oob); + +#ifdef DEBUG_ENABLED + if (oob) { + String v = index->operator String(); + if (v != "") { + v = "'" + v + "'"; + } else { + v = "of type '" + _get_var_type(index) + "'"; + } + err_text = "Out of bounds get index " + v + " (on base: '" + _get_var_type(src) + "')"; + OPCODE_BREAK; + } +#endif + ip += 5; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_SET_NAMED) { + CHECK_SPACE(3); + + GET_INSTRUCTION_ARG(dst, 0); + GET_INSTRUCTION_ARG(value, 1); + + int indexname = _code_ptr[ip + 3]; + + GD_ERR_BREAK(indexname < 0 || indexname >= _global_names_count); + const StringName *index = &_global_names_ptr[indexname]; + + bool valid; + dst->set_named(*index, *value, valid); + +#ifdef DEBUG_ENABLED + if (!valid) { + String err_type; + err_text = "Invalid set index '" + String(*index) + "' (on base: '" + _get_var_type(dst) + "') with value of type '" + _get_var_type(value) + "'."; + OPCODE_BREAK; + } +#endif + ip += 4; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_SET_NAMED_VALIDATED) { + CHECK_SPACE(3); + + GET_INSTRUCTION_ARG(dst, 0); + GET_INSTRUCTION_ARG(value, 1); + + int index_setter = _code_ptr[ip + 3]; + GD_ERR_BREAK(index_setter < 0 || index_setter >= _setters_count); + const Variant::ValidatedSetter setter = _setters_ptr[index_setter]; + + setter(dst, value); + ip += 4; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_GET_NAMED) { + CHECK_SPACE(4); + + GET_INSTRUCTION_ARG(src, 0); + GET_INSTRUCTION_ARG(dst, 1); + + int indexname = _code_ptr[ip + 3]; + + GD_ERR_BREAK(indexname < 0 || indexname >= _global_names_count); + const StringName *index = &_global_names_ptr[indexname]; + + bool valid; +#ifdef DEBUG_ENABLED + //allow better error message in cases where src and dst are the same stack position + Variant ret = src->get_named(*index, valid); + +#else + *dst = src->get_named(*index, valid); +#endif +#ifdef DEBUG_ENABLED + if (!valid) { + if (src->has_method(*index)) { + err_text = "Invalid get index '" + index->operator String() + "' (on base: '" + _get_var_type(src) + "'). Did you mean '." + index->operator String() + "()' or funcref(obj, \"" + index->operator String() + "\") ?"; + } else { + err_text = "Invalid get index '" + index->operator String() + "' (on base: '" + _get_var_type(src) + "')."; + } + OPCODE_BREAK; + } + *dst = ret; +#endif + ip += 4; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_GET_NAMED_VALIDATED) { + CHECK_SPACE(3); + + GET_INSTRUCTION_ARG(src, 0); + GET_INSTRUCTION_ARG(dst, 1); + + int index_getter = _code_ptr[ip + 3]; + GD_ERR_BREAK(index_getter < 0 || index_getter >= _getters_count); + const Variant::ValidatedGetter getter = _getters_ptr[index_getter]; + + getter(src, dst); + ip += 4; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_SET_MEMBER) { + CHECK_SPACE(3); + GET_INSTRUCTION_ARG(src, 0); + int indexname = _code_ptr[ip + 2]; + GD_ERR_BREAK(indexname < 0 || indexname >= _global_names_count); + const StringName *index = &_global_names_ptr[indexname]; + + bool valid; +#ifndef DEBUG_ENABLED + ClassDB::set_property(p_instance->owner, *index, *src, &valid); +#else + bool ok = ClassDB::set_property(p_instance->owner, *index, *src, &valid); + if (!ok) { + err_text = "Internal error setting property: " + String(*index); + OPCODE_BREAK; + } else if (!valid) { + err_text = "Error setting property '" + String(*index) + "' with value of type " + Variant::get_type_name(src->get_type()) + "."; + OPCODE_BREAK; + } +#endif + ip += 3; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_GET_MEMBER) { + CHECK_SPACE(3); + GET_INSTRUCTION_ARG(dst, 0); + int indexname = _code_ptr[ip + 2]; + GD_ERR_BREAK(indexname < 0 || indexname >= _global_names_count); + const StringName *index = &_global_names_ptr[indexname]; +#ifndef DEBUG_ENABLED + ClassDB::get_property(p_instance->owner, *index, *dst); +#else + bool ok = ClassDB::get_property(p_instance->owner, *index, *dst); + if (!ok) { + err_text = "Internal error getting property: " + String(*index); + OPCODE_BREAK; + } +#endif + ip += 3; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ASSIGN) { + CHECK_SPACE(3); + GET_INSTRUCTION_ARG(dst, 0); + GET_INSTRUCTION_ARG(src, 1); + + *dst = *src; + + ip += 3; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ASSIGN_TRUE) { + CHECK_SPACE(2); + GET_INSTRUCTION_ARG(dst, 0); + + *dst = true; + + ip += 2; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ASSIGN_FALSE) { + CHECK_SPACE(2); + GET_INSTRUCTION_ARG(dst, 0); + + *dst = false; + + ip += 2; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ASSIGN_TYPED_BUILTIN) { + CHECK_SPACE(4); + GET_INSTRUCTION_ARG(dst, 0); + GET_INSTRUCTION_ARG(src, 1); + + Variant::Type var_type = (Variant::Type)_code_ptr[ip + 3]; + GD_ERR_BREAK(var_type < 0 || var_type >= Variant::VARIANT_MAX); + + if (src->get_type() != var_type) { +#ifdef DEBUG_ENABLED + if (Variant::can_convert_strict(src->get_type(), var_type)) { +#endif // DEBUG_ENABLED + Callable::CallError ce; + Variant::construct(var_type, *dst, const_cast<const Variant **>(&src), 1, ce); + } else { +#ifdef DEBUG_ENABLED + err_text = "Trying to assign value of type '" + Variant::get_type_name(src->get_type()) + + "' to a variable of type '" + Variant::get_type_name(var_type) + "'."; + OPCODE_BREAK; + } + } else { +#endif // DEBUG_ENABLED + *dst = *src; + } + + ip += 4; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ASSIGN_TYPED_NATIVE) { + CHECK_SPACE(4); + GET_INSTRUCTION_ARG(dst, 0); + GET_INSTRUCTION_ARG(src, 1); + +#ifdef DEBUG_ENABLED + GET_INSTRUCTION_ARG(type, 2); + GDScriptNativeClass *nc = Object::cast_to<GDScriptNativeClass>(type->operator Object *()); + GD_ERR_BREAK(!nc); + if (src->get_type() != Variant::OBJECT && src->get_type() != Variant::NIL) { + err_text = "Trying to assign value of type '" + Variant::get_type_name(src->get_type()) + + "' to a variable of type '" + nc->get_name() + "'."; + OPCODE_BREAK; + } + Object *src_obj = src->operator Object *(); + + if (src_obj && !ClassDB::is_parent_class(src_obj->get_class_name(), nc->get_name())) { + err_text = "Trying to assign value of type '" + src_obj->get_class_name() + + "' to a variable of type '" + nc->get_name() + "'."; + OPCODE_BREAK; + } +#endif // DEBUG_ENABLED + *dst = *src; + + ip += 4; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ASSIGN_TYPED_SCRIPT) { + CHECK_SPACE(4); + GET_INSTRUCTION_ARG(dst, 0); + GET_INSTRUCTION_ARG(src, 1); + +#ifdef DEBUG_ENABLED + GET_INSTRUCTION_ARG(type, 2); + Script *base_type = Object::cast_to<Script>(type->operator Object *()); + + GD_ERR_BREAK(!base_type); + + if (src->get_type() != Variant::OBJECT && src->get_type() != Variant::NIL) { + err_text = "Trying to assign a non-object value to a variable of type '" + base_type->get_path().get_file() + "'."; + OPCODE_BREAK; + } + + if (src->get_type() != Variant::NIL && src->operator Object *() != nullptr) { + ScriptInstance *scr_inst = src->operator Object *()->get_script_instance(); + if (!scr_inst) { + err_text = "Trying to assign value of type '" + src->operator Object *()->get_class_name() + + "' to a variable of type '" + base_type->get_path().get_file() + "'."; + OPCODE_BREAK; + } + + Script *src_type = src->operator Object *()->get_script_instance()->get_script().ptr(); + bool valid = false; + + while (src_type) { + if (src_type == base_type) { + valid = true; + break; + } + src_type = src_type->get_base_script().ptr(); + } + + if (!valid) { + err_text = "Trying to assign value of type '" + src->operator Object *()->get_script_instance()->get_script()->get_path().get_file() + + "' to a variable of type '" + base_type->get_path().get_file() + "'."; + OPCODE_BREAK; + } + } +#endif // DEBUG_ENABLED + + *dst = *src; + + ip += 4; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_CAST_TO_BUILTIN) { + CHECK_SPACE(4); + GET_INSTRUCTION_ARG(src, 0); + GET_INSTRUCTION_ARG(dst, 1); + Variant::Type to_type = (Variant::Type)_code_ptr[ip + 3]; + + GD_ERR_BREAK(to_type < 0 || to_type >= Variant::VARIANT_MAX); + + Callable::CallError err; + Variant::construct(to_type, *dst, (const Variant **)&src, 1, err); + +#ifdef DEBUG_ENABLED + if (err.error != Callable::CallError::CALL_OK) { + err_text = "Invalid cast: could not convert value to '" + Variant::get_type_name(to_type) + "'."; + OPCODE_BREAK; + } +#endif + + ip += 4; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_CAST_TO_NATIVE) { + CHECK_SPACE(4); + GET_INSTRUCTION_ARG(src, 0); + GET_INSTRUCTION_ARG(dst, 1); + GET_INSTRUCTION_ARG(to_type, 2); + + GDScriptNativeClass *nc = Object::cast_to<GDScriptNativeClass>(to_type->operator Object *()); + GD_ERR_BREAK(!nc); + +#ifdef DEBUG_ENABLED + if (src->get_type() != Variant::OBJECT && src->get_type() != Variant::NIL) { + err_text = "Invalid cast: can't convert a non-object value to an object type."; + OPCODE_BREAK; + } +#endif + Object *src_obj = src->operator Object *(); + + if (src_obj && !ClassDB::is_parent_class(src_obj->get_class_name(), nc->get_name())) { + *dst = Variant(); // invalid cast, assign NULL + } else { + *dst = *src; + } + + ip += 4; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_CAST_TO_SCRIPT) { + CHECK_SPACE(4); + GET_INSTRUCTION_ARG(src, 0); + GET_INSTRUCTION_ARG(dst, 1); + GET_INSTRUCTION_ARG(to_type, 2); + + Script *base_type = Object::cast_to<Script>(to_type->operator Object *()); + + GD_ERR_BREAK(!base_type); + +#ifdef DEBUG_ENABLED + if (src->get_type() != Variant::OBJECT && src->get_type() != Variant::NIL) { + err_text = "Trying to assign a non-object value to a variable of type '" + base_type->get_path().get_file() + "'."; + OPCODE_BREAK; + } +#endif + + bool valid = false; + + if (src->get_type() != Variant::NIL && src->operator Object *() != nullptr) { + ScriptInstance *scr_inst = src->operator Object *()->get_script_instance(); + + if (scr_inst) { + Script *src_type = src->operator Object *()->get_script_instance()->get_script().ptr(); + + while (src_type) { + if (src_type == base_type) { + valid = true; + break; + } + src_type = src_type->get_base_script().ptr(); + } + } + } + + if (valid) { + *dst = *src; // Valid cast, copy the source object + } else { + *dst = Variant(); // invalid cast, assign NULL + } + + ip += 4; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_CONSTRUCT) { + CHECK_SPACE(2 + instr_arg_count); + + ip += instr_arg_count; + + int argc = _code_ptr[ip + 1]; + + Variant::Type t = Variant::Type(_code_ptr[ip + 2]); + Variant **argptrs = instruction_args; + + GET_INSTRUCTION_ARG(dst, argc); + + Callable::CallError err; + Variant::construct(t, *dst, (const Variant **)argptrs, argc, err); + +#ifdef DEBUG_ENABLED + if (err.error != Callable::CallError::CALL_OK) { + err_text = _get_call_error(err, "'" + Variant::get_type_name(t) + "' constructor", (const Variant **)argptrs); + OPCODE_BREAK; + } +#endif + + ip += 3; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_CONSTRUCT_VALIDATED) { + CHECK_SPACE(2 + instr_arg_count); + + ip += instr_arg_count; + + int argc = _code_ptr[ip + 1]; + + int constructor_idx = _code_ptr[ip + 2]; + GD_ERR_BREAK(constructor_idx < 0 || constructor_idx >= _constructors_count); + Variant::ValidatedConstructor constructor = _constructors_ptr[constructor_idx]; + + Variant **argptrs = instruction_args; + + GET_INSTRUCTION_ARG(dst, argc); + + constructor(*dst, (const Variant **)argptrs); + + ip += 3; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_CONSTRUCT_ARRAY) { + CHECK_SPACE(1 + instr_arg_count); + ip += instr_arg_count; + + int argc = _code_ptr[ip + 1]; + Array array; + array.resize(argc); + + for (int i = 0; i < argc; i++) { + array[i] = *(instruction_args[i]); + } + + GET_INSTRUCTION_ARG(dst, argc); + + *dst = array; + + ip += 2; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_CONSTRUCT_DICTIONARY) { + CHECK_SPACE(2 + instr_arg_count); + + ip += instr_arg_count; + + int argc = _code_ptr[ip + 1]; + Dictionary dict; + + for (int i = 0; i < argc; i++) { + GET_INSTRUCTION_ARG(k, i * 2 + 0); + GET_INSTRUCTION_ARG(v, i * 2 + 1); + dict[*k] = *v; + } + + GET_INSTRUCTION_ARG(dst, argc * 2); + + *dst = dict; + + ip += 2; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_CALL_ASYNC) + OPCODE(OPCODE_CALL_RETURN) + OPCODE(OPCODE_CALL) { + CHECK_SPACE(3 + instr_arg_count); + bool call_ret = (_code_ptr[ip] & INSTR_MASK) != OPCODE_CALL; +#ifdef DEBUG_ENABLED + bool call_async = (_code_ptr[ip] & INSTR_MASK) == OPCODE_CALL_ASYNC; +#endif + + ip += instr_arg_count; + + int argc = _code_ptr[ip + 1]; + GD_ERR_BREAK(argc < 0); + + int methodname_idx = _code_ptr[ip + 2]; + GD_ERR_BREAK(methodname_idx < 0 || methodname_idx >= _global_names_count); + const StringName *methodname = &_global_names_ptr[methodname_idx]; + + GET_INSTRUCTION_ARG(base, argc); + Variant **argptrs = instruction_args; + +#ifdef DEBUG_ENABLED + uint64_t call_time = 0; + + if (GDScriptLanguage::get_singleton()->profiling) { + call_time = OS::get_singleton()->get_ticks_usec(); + } + +#endif + Callable::CallError err; + if (call_ret) { + GET_INSTRUCTION_ARG(ret, argc + 1); + base->call(*methodname, (const Variant **)argptrs, argc, *ret, err); +#ifdef DEBUG_ENABLED + if (!call_async && ret->get_type() == Variant::OBJECT) { + // Check if getting a function state without await. + bool was_freed = false; + Object *obj = ret->get_validated_object_with_check(was_freed); + + if (was_freed) { + err_text = "Got a freed object as a result of the call."; + OPCODE_BREAK; + } + if (obj && obj->is_class_ptr(GDScriptFunctionState::get_class_ptr_static())) { + err_text = R"(Trying to call an async function without "await".)"; + OPCODE_BREAK; + } + } +#endif + } else { + Variant ret; + base->call(*methodname, (const Variant **)argptrs, argc, ret, err); + } +#ifdef DEBUG_ENABLED + if (GDScriptLanguage::get_singleton()->profiling) { + function_call_time += OS::get_singleton()->get_ticks_usec() - call_time; + } + + if (err.error != Callable::CallError::CALL_OK) { + String methodstr = *methodname; + String basestr = _get_var_type(base); + + if (methodstr == "call") { + if (argc >= 1) { + methodstr = String(*argptrs[0]) + " (via call)"; + if (err.error == Callable::CallError::CALL_ERROR_INVALID_ARGUMENT) { + err.argument += 1; + } + } + } else if (methodstr == "free") { + if (err.error == Callable::CallError::CALL_ERROR_INVALID_METHOD) { + if (base->is_ref()) { + err_text = "Attempted to free a reference."; + OPCODE_BREAK; + } else if (base->get_type() == Variant::OBJECT) { + err_text = "Attempted to free a locked object (calling or emitting)."; + OPCODE_BREAK; + } + } + } else if (methodstr == "call_recursive" && basestr == "TreeItem") { + if (argc >= 1) { + methodstr = String(*argptrs[0]) + " (via TreeItem.call_recursive)"; + if (err.error == Callable::CallError::CALL_ERROR_INVALID_ARGUMENT) { + err.argument += 1; + } + } + } + err_text = _get_call_error(err, "function '" + methodstr + "' in base '" + basestr + "'", (const Variant **)argptrs); + OPCODE_BREAK; + } +#endif + + ip += 3; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_CALL_METHOD_BIND) + OPCODE(OPCODE_CALL_METHOD_BIND_RET) { + CHECK_SPACE(3 + instr_arg_count); + bool call_ret = (_code_ptr[ip] & INSTR_MASK) == OPCODE_CALL_METHOD_BIND_RET; + + ip += instr_arg_count; + + int argc = _code_ptr[ip + 1]; + GD_ERR_BREAK(argc < 0); + GD_ERR_BREAK(_code_ptr[ip + 2] < 0 || _code_ptr[ip + 2] >= _methods_count); + MethodBind *method = _methods_ptr[_code_ptr[ip + 2]]; + + GET_INSTRUCTION_ARG(base, argc); + +#ifdef DEBUG_ENABLED + bool freed = false; + Object *base_obj = base->get_validated_object_with_check(freed); + if (freed) { + err_text = "Trying to call a function on a previously freed instance."; + OPCODE_BREAK; + } else if (!base_obj) { + err_text = "Trying to call a function on a null value."; + OPCODE_BREAK; + } +#else + Object *base_obj = base->operator Object *(); +#endif + Variant **argptrs = instruction_args; + +#ifdef DEBUG_ENABLED + uint64_t call_time = 0; + + if (GDScriptLanguage::get_singleton()->profiling) { + call_time = OS::get_singleton()->get_ticks_usec(); + } +#endif + + Callable::CallError err; + if (call_ret) { + GET_INSTRUCTION_ARG(ret, argc + 1); + *ret = method->call(base_obj, (const Variant **)argptrs, argc, err); + } else { + method->call(base_obj, (const Variant **)argptrs, argc, err); + } + +#ifdef DEBUG_ENABLED + if (GDScriptLanguage::get_singleton()->profiling) { + function_call_time += OS::get_singleton()->get_ticks_usec() - call_time; + } + + if (err.error != Callable::CallError::CALL_OK) { + String methodstr = method->get_name(); + String basestr = _get_var_type(base); + + if (methodstr == "call") { + if (argc >= 1) { + methodstr = String(*argptrs[0]) + " (via call)"; + if (err.error == Callable::CallError::CALL_ERROR_INVALID_ARGUMENT) { + err.argument += 1; + } + } + } else if (methodstr == "free") { + if (err.error == Callable::CallError::CALL_ERROR_INVALID_METHOD) { + if (base->is_ref()) { + err_text = "Attempted to free a reference."; + OPCODE_BREAK; + } else if (base->get_type() == Variant::OBJECT) { + err_text = "Attempted to free a locked object (calling or emitting)."; + OPCODE_BREAK; + } + } + } + err_text = _get_call_error(err, "function '" + methodstr + "' in base '" + basestr + "'", (const Variant **)argptrs); + OPCODE_BREAK; + } +#endif + ip += 3; + } + DISPATCH_OPCODE; + +#ifdef DEBUG_ENABLED +#define OPCODE_CALL_PTR(m_type) \ + OPCODE(OPCODE_CALL_PTRCALL_##m_type) { \ + CHECK_SPACE(3 + instr_arg_count); \ + ip += instr_arg_count; \ + int argc = _code_ptr[ip + 1]; \ + GD_ERR_BREAK(argc < 0); \ + GET_INSTRUCTION_ARG(base, argc); \ + GD_ERR_BREAK(_code_ptr[ip + 2] < 0 || _code_ptr[ip + 2] >= _methods_count); \ + MethodBind *method = _methods_ptr[_code_ptr[ip + 2]]; \ + bool freed = false; \ + Object *base_obj = base->get_validated_object_with_check(freed); \ + if (freed) { \ + err_text = "Trying to call a function on a previously freed instance."; \ + OPCODE_BREAK; \ + } else if (!base_obj) { \ + err_text = "Trying to call a function on a null value."; \ + OPCODE_BREAK; \ + } \ + const void **argptrs = call_args_ptr; \ + for (int i = 0; i < argc; i++) { \ + GET_INSTRUCTION_ARG(v, i); \ + argptrs[i] = VariantInternal::get_opaque_pointer((const Variant *)v); \ + } \ + uint64_t call_time = 0; \ + if (GDScriptLanguage::get_singleton()->profiling) { \ + call_time = OS::get_singleton()->get_ticks_usec(); \ + } \ + GET_INSTRUCTION_ARG(ret, argc + 1); \ + VariantInternal::initialize(ret, Variant::m_type); \ + void *ret_opaque = VariantInternal::OP_GET_##m_type(ret); \ + method->ptrcall(base_obj, argptrs, ret_opaque); \ + if (GDScriptLanguage::get_singleton()->profiling) { \ + function_call_time += OS::get_singleton()->get_ticks_usec() - call_time; \ + } \ + ip += 3; \ + } \ + DISPATCH_OPCODE +#else +#define OPCODE_CALL_PTR(m_type) \ + OPCODE(OPCODE_CALL_PTRCALL_##m_type) { \ + CHECK_SPACE(3 + instr_arg_count); \ + int argc = _code_ptr[ip + 1]; \ + GET_INSTRUCTION_ARG(base, argc); \ + MethodBind *method = _methods_ptr[_code_ptr[ip + 2]]; \ + Object *base_obj = *VariantInternal::get_object(base); \ + const void **argptrs = call_args_ptr; \ + for (int i = 0; i < argc; i++) { \ + GET_INSTRUCTION_ARG(v, i); \ + argptrs[i] = VariantInternal::get_opaque_pointer((const Variant *)v); \ + } \ + GET_INSTRUCTION_ARG(ret, argc + 1); \ + VariantInternal::initialize(ret, Variant::m_type); \ + void *ret_opaque = VariantInternal::OP_GET_##m_type(ret); \ + method->ptrcall(base_obj, argptrs, ret_opaque); \ + ip += 3; \ + } \ + DISPATCH_OPCODE +#endif + + OPCODE_CALL_PTR(BOOL); + OPCODE_CALL_PTR(INT); + OPCODE_CALL_PTR(FLOAT); + OPCODE_CALL_PTR(STRING); + OPCODE_CALL_PTR(VECTOR2); + OPCODE_CALL_PTR(VECTOR2I); + OPCODE_CALL_PTR(RECT2); + OPCODE_CALL_PTR(RECT2I); + OPCODE_CALL_PTR(VECTOR3); + OPCODE_CALL_PTR(VECTOR3I); + OPCODE_CALL_PTR(TRANSFORM2D); + OPCODE_CALL_PTR(PLANE); + OPCODE_CALL_PTR(QUAT); + OPCODE_CALL_PTR(AABB); + OPCODE_CALL_PTR(BASIS); + OPCODE_CALL_PTR(TRANSFORM); + OPCODE_CALL_PTR(COLOR); + OPCODE_CALL_PTR(STRING_NAME); + OPCODE_CALL_PTR(NODE_PATH); + OPCODE_CALL_PTR(RID); + OPCODE_CALL_PTR(CALLABLE); + OPCODE_CALL_PTR(SIGNAL); + OPCODE_CALL_PTR(DICTIONARY); + OPCODE_CALL_PTR(ARRAY); + OPCODE_CALL_PTR(PACKED_BYTE_ARRAY); + OPCODE_CALL_PTR(PACKED_INT32_ARRAY); + OPCODE_CALL_PTR(PACKED_INT64_ARRAY); + OPCODE_CALL_PTR(PACKED_FLOAT32_ARRAY); + OPCODE_CALL_PTR(PACKED_FLOAT64_ARRAY); + OPCODE_CALL_PTR(PACKED_STRING_ARRAY); + OPCODE_CALL_PTR(PACKED_VECTOR2_ARRAY); + OPCODE_CALL_PTR(PACKED_VECTOR3_ARRAY); + OPCODE_CALL_PTR(PACKED_COLOR_ARRAY); + OPCODE(OPCODE_CALL_PTRCALL_OBJECT) { + CHECK_SPACE(3 + instr_arg_count); + + ip += instr_arg_count; + + int argc = _code_ptr[ip + 1]; + GD_ERR_BREAK(argc < 0); + + GD_ERR_BREAK(_code_ptr[ip + 2] < 0 || _code_ptr[ip + 2] >= _methods_count); + MethodBind *method = _methods_ptr[_code_ptr[ip + 2]]; + + GET_INSTRUCTION_ARG(base, argc); +#ifdef DEBUG_ENABLED + bool freed = false; + Object *base_obj = base->get_validated_object_with_check(freed); + if (freed) { + err_text = "Trying to call a function on a previously freed instance."; + OPCODE_BREAK; + } else if (!base_obj) { + err_text = "Trying to call a function on a null value."; + OPCODE_BREAK; + } +#else + Object *base_obj = *VariantInternal::get_object(base); +#endif + + const void **argptrs = call_args_ptr; + + for (int i = 0; i < argc; i++) { + GET_INSTRUCTION_ARG(v, i); + argptrs[i] = VariantInternal::get_opaque_pointer((const Variant *)v); + } +#ifdef DEBUG_ENABLED + uint64_t call_time = 0; + + if (GDScriptLanguage::get_singleton()->profiling) { + call_time = OS::get_singleton()->get_ticks_usec(); + } +#endif + + GET_INSTRUCTION_ARG(ret, argc + 1); + VariantInternal::initialize(ret, Variant::OBJECT); + Object **ret_opaque = VariantInternal::get_object(ret); + method->ptrcall(base_obj, argptrs, ret_opaque); + VariantInternal::object_assign(ret, *ret_opaque); // Set so ID is correct too. + +#ifdef DEBUG_ENABLED + if (GDScriptLanguage::get_singleton()->profiling) { + function_call_time += OS::get_singleton()->get_ticks_usec() - call_time; + } +#endif + ip += 3; + } + DISPATCH_OPCODE; + OPCODE(OPCODE_CALL_PTRCALL_NO_RETURN) { + CHECK_SPACE(3 + instr_arg_count); + + ip += instr_arg_count; + + int argc = _code_ptr[ip + 1]; + GD_ERR_BREAK(argc < 0); + + GD_ERR_BREAK(_code_ptr[ip + 2] < 0 || _code_ptr[ip + 2] >= _methods_count); + MethodBind *method = _methods_ptr[_code_ptr[ip + 2]]; + + GET_INSTRUCTION_ARG(base, argc); +#ifdef DEBUG_ENABLED + bool freed = false; + Object *base_obj = base->get_validated_object_with_check(freed); + if (freed) { + err_text = "Trying to call a function on a previously freed instance."; + OPCODE_BREAK; + } else if (!base_obj) { + err_text = "Trying to call a function on a null value."; + OPCODE_BREAK; + } +#else + Object *base_obj = *VariantInternal::get_object(base); +#endif + const void **argptrs = call_args_ptr; + + for (int i = 0; i < argc; i++) { + GET_INSTRUCTION_ARG(v, i); + argptrs[i] = VariantInternal::get_opaque_pointer((const Variant *)v); + } +#ifdef DEBUG_ENABLED + uint64_t call_time = 0; + + if (GDScriptLanguage::get_singleton()->profiling) { + call_time = OS::get_singleton()->get_ticks_usec(); + } +#endif + + GET_INSTRUCTION_ARG(ret, argc + 1); + VariantInternal::initialize(ret, Variant::NIL); + method->ptrcall(base_obj, argptrs, nullptr); + +#ifdef DEBUG_ENABLED + if (GDScriptLanguage::get_singleton()->profiling) { + function_call_time += OS::get_singleton()->get_ticks_usec() - call_time; + } +#endif + ip += 3; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_CALL_BUILTIN_TYPE_VALIDATED) { + CHECK_SPACE(3 + instr_arg_count); + + ip += instr_arg_count; + + int argc = _code_ptr[ip + 1]; + GD_ERR_BREAK(argc < 0); + + GET_INSTRUCTION_ARG(base, argc); + + GD_ERR_BREAK(_code_ptr[ip + 2] < 0 || _code_ptr[ip + 2] >= _builtin_methods_count); + Variant::ValidatedBuiltInMethod method = _builtin_methods_ptr[_code_ptr[ip + 2]]; + Variant **argptrs = instruction_args; + +#ifdef DEBUG_ENABLED + uint64_t call_time = 0; + if (GDScriptLanguage::get_singleton()->profiling) { + call_time = OS::get_singleton()->get_ticks_usec(); + } +#endif + + GET_INSTRUCTION_ARG(ret, argc + 1); + method(base, (const Variant **)argptrs, argc, ret); + +#ifdef DEBUG_ENABLED + if (GDScriptLanguage::get_singleton()->profiling) { + function_call_time += OS::get_singleton()->get_ticks_usec() - call_time; + } +#endif + + ip += 3; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_CALL_BUILT_IN) { + CHECK_SPACE(3 + instr_arg_count); + + ip += instr_arg_count; + + int argc = _code_ptr[ip + 1]; + GD_ERR_BREAK(argc < 0); + + GDScriptFunctions::Function func = GDScriptFunctions::Function(_code_ptr[ip + 2]); + Variant **argptrs = instruction_args; + + GET_INSTRUCTION_ARG(dst, argc); + + Callable::CallError err; + GDScriptFunctions::call(func, (const Variant **)argptrs, argc, *dst, err); + +#ifdef DEBUG_ENABLED + if (err.error != Callable::CallError::CALL_OK) { + String methodstr = GDScriptFunctions::get_func_name(func); + if (dst->get_type() == Variant::STRING) { + //call provided error string + err_text = "Error calling built-in function '" + methodstr + "': " + String(*dst); + } else { + err_text = _get_call_error(err, "built-in function '" + methodstr + "'", (const Variant **)argptrs); + } + OPCODE_BREAK; + } +#endif + ip += 3; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_CALL_SELF_BASE) { + CHECK_SPACE(3 + instr_arg_count); + + ip += instr_arg_count; + + int self_fun = _code_ptr[ip + 1]; +#ifdef DEBUG_ENABLED + if (self_fun < 0 || self_fun >= _global_names_count) { + err_text = "compiler bug, function name not found"; + OPCODE_BREAK; + } +#endif + const StringName *methodname = &_global_names_ptr[self_fun]; + + int argc = _code_ptr[ip + 2]; + GD_ERR_BREAK(argc < 0); + + Variant **argptrs = instruction_args; + + GET_INSTRUCTION_ARG(dst, argc); + + const GDScript *gds = _script; + + const Map<StringName, GDScriptFunction *>::Element *E = nullptr; + while (gds->base.ptr()) { + gds = gds->base.ptr(); + E = gds->member_functions.find(*methodname); + if (E) { + break; + } + } + + Callable::CallError err; + + if (E) { + *dst = E->get()->call(p_instance, (const Variant **)argptrs, argc, err); + } else if (gds->native.ptr()) { + if (*methodname != GDScriptLanguage::get_singleton()->strings._init) { + MethodBind *mb = ClassDB::get_method(gds->native->get_name(), *methodname); + if (!mb) { + err.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; + } else { + *dst = mb->call(p_instance->owner, (const Variant **)argptrs, argc, err); + } + } else { + err.error = Callable::CallError::CALL_OK; + } + } else { + if (*methodname != GDScriptLanguage::get_singleton()->strings._init) { + err.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; + } else { + err.error = Callable::CallError::CALL_OK; + } + } + + if (err.error != Callable::CallError::CALL_OK) { + String methodstr = *methodname; + err_text = _get_call_error(err, "function '" + methodstr + "'", (const Variant **)argptrs); + + OPCODE_BREAK; + } + + ip += 3; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_AWAIT) { + CHECK_SPACE(2); + + // Do the oneshot connect. + GET_INSTRUCTION_ARG(argobj, 0); + + Signal sig; + bool is_signal = true; + + { + Variant result = *argobj; + + if (argobj->get_type() == Variant::OBJECT) { + bool was_freed = false; + Object *obj = argobj->get_validated_object_with_check(was_freed); + + if (was_freed) { + err_text = "Trying to await on a freed object."; + OPCODE_BREAK; + } + + // Is this even possible to be null at this point? + if (obj) { + if (obj->is_class_ptr(GDScriptFunctionState::get_class_ptr_static())) { + static StringName completed = _scs_create("completed"); + result = Signal(obj, completed); + } + } + } + + if (result.get_type() != Variant::SIGNAL) { + ip += 4; // Skip OPCODE_AWAIT_RESUME and its data. + // The stack pointer should be the same, so we don't need to set a return value. + is_signal = false; + } else { + sig = result; + } + } + + if (is_signal) { + Ref<GDScriptFunctionState> gdfs = memnew(GDScriptFunctionState); + gdfs->function = this; + + gdfs->state.stack.resize(alloca_size); + //copy variant stack + for (int i = 0; i < _stack_size; i++) { + memnew_placement(&gdfs->state.stack.write[sizeof(Variant) * i], Variant(stack[i])); + } + gdfs->state.stack_size = _stack_size; + gdfs->state.self = self; + gdfs->state.alloca_size = alloca_size; + gdfs->state.ip = ip + 2; + gdfs->state.line = line; + gdfs->state.script = _script; + { + MutexLock lock(GDScriptLanguage::get_singleton()->lock); + _script->pending_func_states.add(&gdfs->scripts_list); + if (p_instance) { + gdfs->state.instance = p_instance; + p_instance->pending_func_states.add(&gdfs->instances_list); + } else { + gdfs->state.instance = nullptr; + } + } +#ifdef DEBUG_ENABLED + gdfs->state.function_name = name; + gdfs->state.script_path = _script->get_path(); +#endif + gdfs->state.defarg = defarg; + gdfs->function = this; + + retvalue = gdfs; + + Error err = sig.connect(Callable(gdfs.ptr(), "_signal_callback"), varray(gdfs), Object::CONNECT_ONESHOT); + if (err != OK) { + err_text = "Error connecting to signal: " + sig.get_name() + " during await."; + OPCODE_BREAK; + } + +#ifdef DEBUG_ENABLED + exit_ok = true; + awaited = true; +#endif + OPCODE_BREAK; + } + } + DISPATCH_OPCODE; // Needed for synchronous calls (when result is immediately available). + + OPCODE(OPCODE_AWAIT_RESUME) { + CHECK_SPACE(2); +#ifdef DEBUG_ENABLED + if (!p_state) { + err_text = ("Invalid Resume (bug?)"); + OPCODE_BREAK; + } +#endif + GET_INSTRUCTION_ARG(result, 0); + *result = p_state->result; + ip += 2; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_JUMP) { + CHECK_SPACE(2); + int to = _code_ptr[ip + 1]; + + GD_ERR_BREAK(to < 0 || to > _code_size); + ip = to; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_JUMP_IF) { + CHECK_SPACE(3); + + GET_INSTRUCTION_ARG(test, 0); + + bool result = test->booleanize(); + + if (result) { + int to = _code_ptr[ip + 2]; + GD_ERR_BREAK(to < 0 || to > _code_size); + ip = to; + } else { + ip += 3; + } + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_JUMP_IF_NOT) { + CHECK_SPACE(3); + + GET_INSTRUCTION_ARG(test, 0); + + bool result = test->booleanize(); + + if (!result) { + int to = _code_ptr[ip + 2]; + GD_ERR_BREAK(to < 0 || to > _code_size); + ip = to; + } else { + ip += 3; + } + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_JUMP_TO_DEF_ARGUMENT) { + CHECK_SPACE(2); + ip = _default_arg_ptr[defarg]; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_RETURN) { + CHECK_SPACE(2); + GET_INSTRUCTION_ARG(r, 0); + retvalue = *r; +#ifdef DEBUG_ENABLED + exit_ok = true; +#endif + OPCODE_BREAK; + } + + OPCODE(OPCODE_ITERATE_BEGIN) { + CHECK_SPACE(8); // Space for this and a regular iterate. + + GET_INSTRUCTION_ARG(counter, 0); + GET_INSTRUCTION_ARG(container, 1); + + bool valid; + if (!container->iter_init(*counter, valid)) { +#ifdef DEBUG_ENABLED + if (!valid) { + err_text = "Unable to iterate on object of type '" + Variant::get_type_name(container->get_type()) + "'."; + OPCODE_BREAK; + } +#endif + int jumpto = _code_ptr[ip + 4]; + GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; + } else { + GET_INSTRUCTION_ARG(iterator, 2); + + *iterator = container->iter_get(*counter, valid); +#ifdef DEBUG_ENABLED + if (!valid) { + err_text = "Unable to obtain iterator object of type '" + Variant::get_type_name(container->get_type()) + "'."; + OPCODE_BREAK; + } +#endif + ip += 5; // Skip regular iterate which is always next. + } + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ITERATE_BEGIN_INT) { + CHECK_SPACE(8); // Check space for iterate instruction too. + + GET_INSTRUCTION_ARG(counter, 0); + GET_INSTRUCTION_ARG(container, 1); + + int64_t size = *VariantInternal::get_int(container); + + VariantInternal::initialize(counter, Variant::INT); + *VariantInternal::get_int(counter) = 0; + + if (size > 0) { + GET_INSTRUCTION_ARG(iterator, 2); + VariantInternal::initialize(iterator, Variant::INT); + *VariantInternal::get_int(iterator) = 0; + + // Skip regular iterate. + ip += 5; + } else { + // Jump to end of loop. + int jumpto = _code_ptr[ip + 4]; + GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; + } + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ITERATE_BEGIN_FLOAT) { + CHECK_SPACE(8); // Check space for iterate instruction too. + + GET_INSTRUCTION_ARG(counter, 0); + GET_INSTRUCTION_ARG(container, 1); + + double size = *VariantInternal::get_float(container); + + VariantInternal::initialize(counter, Variant::FLOAT); + *VariantInternal::get_float(counter) = 0.0; + + if (size > 0) { + GET_INSTRUCTION_ARG(iterator, 2); + VariantInternal::initialize(iterator, Variant::FLOAT); + *VariantInternal::get_float(iterator) = 0; + + // Skip regular iterate. + ip += 5; + } else { + // Jump to end of loop. + int jumpto = _code_ptr[ip + 4]; + GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; + } + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ITERATE_BEGIN_VECTOR2) { + CHECK_SPACE(8); // Check space for iterate instruction too. + + GET_INSTRUCTION_ARG(counter, 0); + GET_INSTRUCTION_ARG(container, 1); + + Vector2 *bounds = VariantInternal::get_vector2(container); + + VariantInternal::initialize(counter, Variant::FLOAT); + *VariantInternal::get_float(counter) = bounds->x; + + if (bounds->x < bounds->y) { + GET_INSTRUCTION_ARG(iterator, 2); + VariantInternal::initialize(iterator, Variant::FLOAT); + *VariantInternal::get_float(iterator) = bounds->x; + + // Skip regular iterate. + ip += 5; + } else { + // Jump to end of loop. + int jumpto = _code_ptr[ip + 4]; + GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; + } + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ITERATE_BEGIN_VECTOR2I) { + CHECK_SPACE(8); // Check space for iterate instruction too. + + GET_INSTRUCTION_ARG(counter, 0); + GET_INSTRUCTION_ARG(container, 1); + + Vector2i *bounds = VariantInternal::get_vector2i(container); + + VariantInternal::initialize(counter, Variant::FLOAT); + *VariantInternal::get_int(counter) = bounds->x; + + if (bounds->x < bounds->y) { + GET_INSTRUCTION_ARG(iterator, 2); + VariantInternal::initialize(iterator, Variant::INT); + *VariantInternal::get_int(iterator) = bounds->x; + + // Skip regular iterate. + ip += 5; + } else { + // Jump to end of loop. + int jumpto = _code_ptr[ip + 4]; + GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; + } + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ITERATE_BEGIN_VECTOR3) { + CHECK_SPACE(8); // Check space for iterate instruction too. + + GET_INSTRUCTION_ARG(counter, 0); + GET_INSTRUCTION_ARG(container, 1); + + Vector3 *bounds = VariantInternal::get_vector3(container); + double from = bounds->x; + double to = bounds->y; + double step = bounds->z; + + VariantInternal::initialize(counter, Variant::FLOAT); + *VariantInternal::get_float(counter) = from; + + bool do_continue = from == to ? false : (from < to ? step > 0 : step < 0); + + if (do_continue) { + GET_INSTRUCTION_ARG(iterator, 2); + VariantInternal::initialize(iterator, Variant::FLOAT); + *VariantInternal::get_float(iterator) = from; + + // Skip regular iterate. + ip += 5; + } else { + // Jump to end of loop. + int jumpto = _code_ptr[ip + 4]; + GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; + } + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ITERATE_BEGIN_VECTOR3I) { + CHECK_SPACE(8); // Check space for iterate instruction too. + + GET_INSTRUCTION_ARG(counter, 0); + GET_INSTRUCTION_ARG(container, 1); + + Vector3i *bounds = VariantInternal::get_vector3i(container); + int64_t from = bounds->x; + int64_t to = bounds->y; + int64_t step = bounds->z; + + VariantInternal::initialize(counter, Variant::INT); + *VariantInternal::get_int(counter) = from; + + bool do_continue = from == to ? false : (from < to ? step > 0 : step < 0); + + if (do_continue) { + GET_INSTRUCTION_ARG(iterator, 2); + VariantInternal::initialize(iterator, Variant::INT); + *VariantInternal::get_int(iterator) = from; + + // Skip regular iterate. + ip += 5; + } else { + // Jump to end of loop. + int jumpto = _code_ptr[ip + 4]; + GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; + } + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ITERATE_BEGIN_STRING) { + CHECK_SPACE(8); // Check space for iterate instruction too. + + GET_INSTRUCTION_ARG(counter, 0); + GET_INSTRUCTION_ARG(container, 1); + + String *str = VariantInternal::get_string(container); + + VariantInternal::initialize(counter, Variant::INT); + *VariantInternal::get_int(counter) = 0; + + if (!str->empty()) { + GET_INSTRUCTION_ARG(iterator, 2); + VariantInternal::initialize(iterator, Variant::STRING); + *VariantInternal::get_string(iterator) = str->substr(0, 1); + + // Skip regular iterate. + ip += 5; + } else { + // Jump to end of loop. + int jumpto = _code_ptr[ip + 4]; + GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; + } + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ITERATE_BEGIN_DICTIONARY) { + CHECK_SPACE(8); // Check space for iterate instruction too. + + GET_INSTRUCTION_ARG(counter, 0); + GET_INSTRUCTION_ARG(container, 1); + + Dictionary *dict = VariantInternal::get_dictionary(container); + const Variant *next = dict->next(nullptr); + *counter = *next; + + if (!dict->empty()) { + GET_INSTRUCTION_ARG(iterator, 2); + *iterator = *next; + + // Skip regular iterate. + ip += 5; + } else { + // Jump to end of loop. + int jumpto = _code_ptr[ip + 4]; + GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; + } + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ITERATE_BEGIN_ARRAY) { + CHECK_SPACE(8); // Check space for iterate instruction too. + + GET_INSTRUCTION_ARG(counter, 0); + GET_INSTRUCTION_ARG(container, 1); + + Array *array = VariantInternal::get_array(container); + + VariantInternal::initialize(counter, Variant::INT); + *VariantInternal::get_int(counter) = 0; + + if (!array->empty()) { + GET_INSTRUCTION_ARG(iterator, 2); + *iterator = array->get(0); + + // Skip regular iterate. + ip += 5; + } else { + // Jump to end of loop. + int jumpto = _code_ptr[ip + 4]; + GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; + } + } + DISPATCH_OPCODE; + +#define OPCODE_ITERATE_BEGIN_PACKED_ARRAY(m_var_type, m_elem_type, m_get_func, m_var_ret_type, m_ret_type, m_ret_get_func) \ + OPCODE(OPCODE_ITERATE_BEGIN_PACKED_##m_var_type##_ARRAY) { \ + CHECK_SPACE(8); \ + GET_INSTRUCTION_ARG(counter, 0); \ + GET_INSTRUCTION_ARG(container, 1); \ + Vector<m_elem_type> *array = VariantInternal::m_get_func(container); \ + VariantInternal::initialize(counter, Variant::INT); \ + *VariantInternal::get_int(counter) = 0; \ + if (!array->empty()) { \ + GET_INSTRUCTION_ARG(iterator, 2); \ + VariantInternal::initialize(iterator, Variant::m_var_ret_type); \ + m_ret_type *it = VariantInternal::m_ret_get_func(iterator); \ + *it = array->get(0); \ + ip += 5; \ + } else { \ + int jumpto = _code_ptr[ip + 4]; \ + GD_ERR_BREAK(jumpto<0 || jumpto> _code_size); \ + ip = jumpto; \ + } \ + } \ + DISPATCH_OPCODE + + OPCODE_ITERATE_BEGIN_PACKED_ARRAY(BYTE, uint8_t, get_byte_array, INT, int64_t, get_int); + OPCODE_ITERATE_BEGIN_PACKED_ARRAY(INT32, int32_t, get_int32_array, INT, int64_t, get_int); + OPCODE_ITERATE_BEGIN_PACKED_ARRAY(INT64, int64_t, get_int64_array, INT, int64_t, get_int); + OPCODE_ITERATE_BEGIN_PACKED_ARRAY(FLOAT32, float, get_float32_array, FLOAT, double, get_float); + OPCODE_ITERATE_BEGIN_PACKED_ARRAY(FLOAT64, double, get_float64_array, FLOAT, double, get_float); + OPCODE_ITERATE_BEGIN_PACKED_ARRAY(STRING, String, get_string_array, STRING, String, get_string); + OPCODE_ITERATE_BEGIN_PACKED_ARRAY(VECTOR2, Vector2, get_vector2_array, VECTOR2, Vector2, get_vector2); + OPCODE_ITERATE_BEGIN_PACKED_ARRAY(VECTOR3, Vector3, get_vector3_array, VECTOR3, Vector3, get_vector3); + OPCODE_ITERATE_BEGIN_PACKED_ARRAY(COLOR, Color, get_color_array, COLOR, Color, get_color); + + OPCODE(OPCODE_ITERATE_BEGIN_OBJECT) { + CHECK_SPACE(4); + + GET_INSTRUCTION_ARG(counter, 0); + GET_INSTRUCTION_ARG(container, 1); + +#ifdef DEBUG_ENABLED + bool freed = false; + Object *obj = container->get_validated_object_with_check(freed); + if (freed) { + err_text = "Trying to iterate on a previously freed object."; + OPCODE_BREAK; + } else if (!obj) { + err_text = "Trying to iterate on a null value."; + OPCODE_BREAK; + } +#else + Object *obj = *VariantInternal::get_object(container); +#endif + Array ref; + ref.push_back(*counter); + Variant vref; + VariantInternal::initialize(&vref, Variant::ARRAY); + *VariantInternal::get_array(&vref) = ref; + + Variant **args = instruction_args; // Overriding an instruction argument, but we don't need access to that anymore. + args[0] = &vref; + + Callable::CallError ce; + Variant has_next = obj->call(CoreStringNames::get_singleton()->_iter_init, (const Variant **)args, 1, ce); + +#ifdef DEBUG_ENABLED + if (ce.error != Callable::CallError::CALL_OK) { + err_text = vformat(R"(There was an error calling "_iter_next" on iterator object of type %s.)", *container); + OPCODE_BREAK; + } +#endif + if (!has_next.booleanize()) { + int jumpto = _code_ptr[ip + 4]; + GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; + } else { + GET_INSTRUCTION_ARG(iterator, 2); + *iterator = obj->call(CoreStringNames::get_singleton()->_iter_get, (const Variant **)args, 1, ce); +#ifdef DEBUG_ENABLED + if (ce.error != Callable::CallError::CALL_OK) { + err_text = vformat(R"(There was an error calling "_iter_get" on iterator object of type %s.)", *container); + OPCODE_BREAK; + } +#endif + + ip += 5; // Loop again. + } + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ITERATE) { + CHECK_SPACE(4); + + GET_INSTRUCTION_ARG(counter, 0); + GET_INSTRUCTION_ARG(container, 1); + + bool valid; + if (!container->iter_next(*counter, valid)) { +#ifdef DEBUG_ENABLED + if (!valid) { + err_text = "Unable to iterate on object of type '" + Variant::get_type_name(container->get_type()) + "' (type changed since first iteration?)."; + OPCODE_BREAK; + } +#endif + int jumpto = _code_ptr[ip + 4]; + GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; + } else { + GET_INSTRUCTION_ARG(iterator, 2); + + *iterator = container->iter_get(*counter, valid); +#ifdef DEBUG_ENABLED + if (!valid) { + err_text = "Unable to obtain iterator object of type '" + Variant::get_type_name(container->get_type()) + "' (but was obtained on first iteration?)."; + OPCODE_BREAK; + } +#endif + ip += 5; //loop again + } + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ITERATE_INT) { + CHECK_SPACE(4); + + GET_INSTRUCTION_ARG(counter, 0); + GET_INSTRUCTION_ARG(container, 1); + + int64_t size = *VariantInternal::get_int(container); + int64_t *count = VariantInternal::get_int(counter); + + (*count)++; + + if (*count >= size) { + int jumpto = _code_ptr[ip + 4]; + GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; + } else { + GET_INSTRUCTION_ARG(iterator, 2); + *VariantInternal::get_int(iterator) = *count; + + ip += 5; // Loop again. + } + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ITERATE_FLOAT) { + CHECK_SPACE(4); + + GET_INSTRUCTION_ARG(counter, 0); + GET_INSTRUCTION_ARG(container, 1); + + double size = *VariantInternal::get_float(container); + double *count = VariantInternal::get_float(counter); + + (*count)++; + + if (*count >= size) { + int jumpto = _code_ptr[ip + 4]; + GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; + } else { + GET_INSTRUCTION_ARG(iterator, 2); + *VariantInternal::get_float(iterator) = *count; + + ip += 5; // Loop again. + } + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ITERATE_VECTOR2) { + CHECK_SPACE(4); + + GET_INSTRUCTION_ARG(counter, 0); + GET_INSTRUCTION_ARG(container, 1); + + const Vector2 *bounds = VariantInternal::get_vector2((const Variant *)container); + double *count = VariantInternal::get_float(counter); + + (*count)++; + + if (*count >= bounds->y) { + int jumpto = _code_ptr[ip + 4]; + GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; + } else { + GET_INSTRUCTION_ARG(iterator, 2); + *VariantInternal::get_float(iterator) = *count; + + ip += 5; // Loop again. + } + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ITERATE_VECTOR2I) { + CHECK_SPACE(4); + + GET_INSTRUCTION_ARG(counter, 0); + GET_INSTRUCTION_ARG(container, 1); + + const Vector2i *bounds = VariantInternal::get_vector2i((const Variant *)container); + int64_t *count = VariantInternal::get_int(counter); + + (*count)++; + + if (*count >= bounds->y) { + int jumpto = _code_ptr[ip + 4]; + GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; + } else { + GET_INSTRUCTION_ARG(iterator, 2); + *VariantInternal::get_int(iterator) = *count; + + ip += 5; // Loop again. + } + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ITERATE_VECTOR3) { + CHECK_SPACE(4); + + GET_INSTRUCTION_ARG(counter, 0); + GET_INSTRUCTION_ARG(container, 1); + + const Vector3 *bounds = VariantInternal::get_vector3((const Variant *)container); + double *count = VariantInternal::get_float(counter); + + *count += bounds->z; + + if ((bounds->z < 0 && *count <= bounds->y) || (bounds->z > 0 && *count >= bounds->y)) { + int jumpto = _code_ptr[ip + 4]; + GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; + } else { + GET_INSTRUCTION_ARG(iterator, 2); + *VariantInternal::get_float(iterator) = *count; + + ip += 5; // Loop again. + } + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ITERATE_VECTOR3I) { + CHECK_SPACE(4); + + GET_INSTRUCTION_ARG(counter, 0); + GET_INSTRUCTION_ARG(container, 1); + + const Vector3i *bounds = VariantInternal::get_vector3i((const Variant *)container); + int64_t *count = VariantInternal::get_int(counter); + + *count += bounds->z; + + if ((bounds->z < 0 && *count <= bounds->y) || (bounds->z > 0 && *count >= bounds->y)) { + int jumpto = _code_ptr[ip + 4]; + GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; + } else { + GET_INSTRUCTION_ARG(iterator, 2); + *VariantInternal::get_int(iterator) = *count; + + ip += 5; // Loop again. + } + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ITERATE_STRING) { + CHECK_SPACE(4); + + GET_INSTRUCTION_ARG(counter, 0); + GET_INSTRUCTION_ARG(container, 1); + + const String *str = VariantInternal::get_string((const Variant *)container); + int64_t *idx = VariantInternal::get_int(counter); + (*idx)++; + + if (*idx >= str->length()) { + int jumpto = _code_ptr[ip + 4]; + GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; + } else { + GET_INSTRUCTION_ARG(iterator, 2); + *VariantInternal::get_string(iterator) = str->substr(*idx, 1); + + ip += 5; // Loop again. + } + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ITERATE_DICTIONARY) { + CHECK_SPACE(4); + + GET_INSTRUCTION_ARG(counter, 0); + GET_INSTRUCTION_ARG(container, 1); + + const Dictionary *dict = VariantInternal::get_dictionary((const Variant *)container); + const Variant *next = dict->next(counter); + + if (!next) { + int jumpto = _code_ptr[ip + 4]; + GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; + } else { + GET_INSTRUCTION_ARG(iterator, 2); + *counter = *next; + *iterator = *next; + + ip += 5; // Loop again. + } + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ITERATE_ARRAY) { + CHECK_SPACE(4); + + GET_INSTRUCTION_ARG(counter, 0); + GET_INSTRUCTION_ARG(container, 1); + + const Array *array = VariantInternal::get_array((const Variant *)container); + int64_t *idx = VariantInternal::get_int(counter); + (*idx)++; + + if (*idx >= array->size()) { + int jumpto = _code_ptr[ip + 4]; + GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; + } else { + GET_INSTRUCTION_ARG(iterator, 2); + *iterator = array->get(*idx); + + ip += 5; // Loop again. + } + } + DISPATCH_OPCODE; + +#define OPCODE_ITERATE_PACKED_ARRAY(m_var_type, m_elem_type, m_get_func, m_ret_get_func) \ + OPCODE(OPCODE_ITERATE_PACKED_##m_var_type##_ARRAY) { \ + CHECK_SPACE(4); \ + GET_INSTRUCTION_ARG(counter, 0); \ + GET_INSTRUCTION_ARG(container, 1); \ + const Vector<m_elem_type> *array = VariantInternal::m_get_func((const Variant *)container); \ + int64_t *idx = VariantInternal::get_int(counter); \ + (*idx)++; \ + if (*idx >= array->size()) { \ + int jumpto = _code_ptr[ip + 4]; \ + GD_ERR_BREAK(jumpto<0 || jumpto> _code_size); \ + ip = jumpto; \ + } else { \ + GET_INSTRUCTION_ARG(iterator, 2); \ + *VariantInternal::m_ret_get_func(iterator) = array->get(*idx); \ + ip += 5; \ + } \ + } \ + DISPATCH_OPCODE + + OPCODE_ITERATE_PACKED_ARRAY(BYTE, uint8_t, get_byte_array, get_int); + OPCODE_ITERATE_PACKED_ARRAY(INT32, int32_t, get_int32_array, get_int); + OPCODE_ITERATE_PACKED_ARRAY(INT64, int64_t, get_int64_array, get_int); + OPCODE_ITERATE_PACKED_ARRAY(FLOAT32, float, get_float32_array, get_float); + OPCODE_ITERATE_PACKED_ARRAY(FLOAT64, double, get_float64_array, get_float); + OPCODE_ITERATE_PACKED_ARRAY(STRING, String, get_string_array, get_string); + OPCODE_ITERATE_PACKED_ARRAY(VECTOR2, Vector2, get_vector2_array, get_vector2); + OPCODE_ITERATE_PACKED_ARRAY(VECTOR3, Vector3, get_vector3_array, get_vector3); + OPCODE_ITERATE_PACKED_ARRAY(COLOR, Color, get_color_array, get_color); + + OPCODE(OPCODE_ITERATE_OBJECT) { + CHECK_SPACE(4); + + GET_INSTRUCTION_ARG(counter, 0); + GET_INSTRUCTION_ARG(container, 1); + +#ifdef DEBUG_ENABLED + bool freed = false; + Object *obj = container->get_validated_object_with_check(freed); + if (freed) { + err_text = "Trying to iterate on a previously freed object."; + OPCODE_BREAK; + } else if (!obj) { + err_text = "Trying to iterate on a null value."; + OPCODE_BREAK; + } +#else + Object *obj = *VariantInternal::get_object(container); +#endif + Array ref; + ref.push_back(*counter); + Variant vref; + VariantInternal::initialize(&vref, Variant::ARRAY); + *VariantInternal::get_array(&vref) = ref; + + Variant **args = instruction_args; // Overriding an instruction argument, but we don't need access to that anymore. + args[0] = &vref; + + Callable::CallError ce; + Variant has_next = obj->call(CoreStringNames::get_singleton()->_iter_next, (const Variant **)args, 1, ce); + +#ifdef DEBUG_ENABLED + if (ce.error != Callable::CallError::CALL_OK) { + err_text = vformat(R"(There was an error calling "_iter_next" on iterator object of type %s.)", *container); + OPCODE_BREAK; + } +#endif + if (!has_next.booleanize()) { + int jumpto = _code_ptr[ip + 4]; + GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; + } else { + GET_INSTRUCTION_ARG(iterator, 2); + *iterator = obj->call(CoreStringNames::get_singleton()->_iter_get, (const Variant **)args, 1, ce); +#ifdef DEBUG_ENABLED + if (ce.error != Callable::CallError::CALL_OK) { + err_text = vformat(R"(There was an error calling "_iter_get" on iterator object of type %s.)", *container); + OPCODE_BREAK; + } +#endif + + ip += 5; // Loop again. + } + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ASSERT) { + CHECK_SPACE(3); + +#ifdef DEBUG_ENABLED + GET_INSTRUCTION_ARG(test, 0); + bool result = test->booleanize(); + + if (!result) { + String message_str; + if (_code_ptr[ip + 2] != 0) { + GET_INSTRUCTION_ARG(message, 1); + message_str = *message; + } + if (message_str.empty()) { + err_text = "Assertion failed."; + } else { + err_text = "Assertion failed: " + message_str; + } + OPCODE_BREAK; + } + +#endif + ip += 3; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_BREAKPOINT) { +#ifdef DEBUG_ENABLED + if (EngineDebugger::is_active()) { + GDScriptLanguage::get_singleton()->debug_break("Breakpoint Statement", true); + } +#endif + ip += 1; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_LINE) { + CHECK_SPACE(2); + + line = _code_ptr[ip + 1]; + ip += 2; + + if (EngineDebugger::is_active()) { + // line + bool do_break = false; + + if (EngineDebugger::get_script_debugger()->get_lines_left() > 0) { + if (EngineDebugger::get_script_debugger()->get_depth() <= 0) { + EngineDebugger::get_script_debugger()->set_lines_left(EngineDebugger::get_script_debugger()->get_lines_left() - 1); + } + if (EngineDebugger::get_script_debugger()->get_lines_left() <= 0) { + do_break = true; + } + } + + if (EngineDebugger::get_script_debugger()->is_breakpoint(line, source)) { + do_break = true; + } + + if (do_break) { + GDScriptLanguage::get_singleton()->debug_break("Breakpoint", true); + } + + EngineDebugger::get_singleton()->line_poll(); + } + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_END) { +#ifdef DEBUG_ENABLED + exit_ok = true; +#endif + OPCODE_BREAK; + } + +#if 0 // Enable for debugging. + default: { + err_text = "Illegal opcode " + itos(_code_ptr[ip]) + " at address " + itos(ip); + OPCODE_BREAK; + } +#endif + } + + OPCODES_END +#ifdef DEBUG_ENABLED + if (exit_ok) { + OPCODE_OUT; + } + //error + // function, file, line, error, explanation + String err_file; + if (p_instance && ObjectDB::get_instance(p_instance->owner_id) != nullptr && p_instance->script->is_valid() && p_instance->script->path != "") { + err_file = p_instance->script->path; + } else if (script) { + err_file = script->path; + } + if (err_file == "") { + err_file = "<built-in>"; + } + String err_func = name; + if (p_instance && ObjectDB::get_instance(p_instance->owner_id) != nullptr && p_instance->script->is_valid() && p_instance->script->name != "") { + err_func = p_instance->script->name + "." + err_func; + } + int err_line = line; + if (err_text == "") { + err_text = "Internal Script Error! - opcode #" + itos(last_opcode) + " (report please)."; + } + + if (!GDScriptLanguage::get_singleton()->debug_break(err_text, false)) { + // debugger break did not happen + + _err_print_error(err_func.utf8().get_data(), err_file.utf8().get_data(), err_line, err_text.utf8().get_data(), ERR_HANDLER_SCRIPT); + } + +#endif + OPCODE_OUT; + } + + OPCODES_OUT +#ifdef DEBUG_ENABLED + if (GDScriptLanguage::get_singleton()->profiling) { + uint64_t time_taken = OS::get_singleton()->get_ticks_usec() - function_start_time; + profile.total_time += time_taken; + profile.self_time += time_taken - function_call_time; + profile.frame_total_time += time_taken; + profile.frame_self_time += time_taken - function_call_time; + GDScriptLanguage::get_singleton()->script_frame_time += time_taken - function_call_time; + } + + // Check if this is the last time the function is resuming from await + // Will be true if never awaited as well + // When it's the last resume it will postpone the exit from stack, + // so the debugger knows which function triggered the resume of the next function (if any) + if (!p_state || awaited) { + if (EngineDebugger::is_active()) { + GDScriptLanguage::get_singleton()->exit_function(); + } +#endif + + if (_stack_size) { + //free stack + for (int i = 0; i < _stack_size; i++) { + stack[i].~Variant(); + } + } + +#ifdef DEBUG_ENABLED + } +#endif + + return retvalue; +} diff --git a/modules/gdscript/language_server/lsp.hpp b/modules/gdscript/language_server/lsp.hpp index bf32c1c978..288fd41c87 100644 --- a/modules/gdscript/language_server/lsp.hpp +++ b/modules/gdscript/language_server/lsp.hpp @@ -1781,7 +1781,6 @@ static String marked_documentation(const String &p_bbcode) { } return markdown; } - } // namespace lsp #endif diff --git a/modules/gdscript/register_types.cpp b/modules/gdscript/register_types.cpp index 065f01e654..6c2af66c65 100644 --- a/modules/gdscript/register_types.cpp +++ b/modules/gdscript/register_types.cpp @@ -112,7 +112,6 @@ static void _editor_init() { void register_gdscript_types() { ClassDB::register_class<GDScript>(); - ClassDB::register_virtual_class<GDScriptFunctionState>(); script_language_gd = memnew(GDScriptLanguage); ScriptServer::register_language(script_language_gd); diff --git a/modules/gdscript/tests/test_gdscript.cpp b/modules/gdscript/tests/test_gdscript.cpp index 50b3783388..643c2f10a2 100644 --- a/modules/gdscript/tests/test_gdscript.cpp +++ b/modules/gdscript/tests/test_gdscript.cpp @@ -303,5 +303,4 @@ void test(TestType p_type) { ScriptServer::finish_languages(); memdelete(packed_data); } - } // namespace TestGDScript diff --git a/modules/gdscript/tests/test_gdscript.h b/modules/gdscript/tests/test_gdscript.h index 5aa962dcf8..6182629802 100644 --- a/modules/gdscript/tests/test_gdscript.h +++ b/modules/gdscript/tests/test_gdscript.h @@ -41,7 +41,6 @@ enum TestType { }; void test(TestType p_type); - } // namespace TestGDScript #endif // TEST_GDSCRIPT_H diff --git a/modules/gridmap/grid_map_editor_plugin.h b/modules/gridmap/grid_map_editor_plugin.h index ee17a52d31..69c8d999fd 100644 --- a/modules/gridmap/grid_map_editor_plugin.h +++ b/modules/gridmap/grid_map_editor_plugin.h @@ -41,12 +41,10 @@ class GridMapEditor : public VBoxContainer { GDCLASS(GridMapEditor, VBoxContainer); enum { - GRID_CURSOR_SIZE = 50 }; enum InputAction { - INPUT_NONE, INPUT_PAINT, INPUT_ERASE, @@ -56,7 +54,6 @@ class GridMapEditor : public VBoxContainer { }; enum ClipMode { - CLIP_DISABLED, CLIP_ABOVE, CLIP_BELOW @@ -158,7 +155,6 @@ class GridMapEditor : public VBoxContainer { int cursor_rot; enum Menu { - MENU_OPTION_NEXT_LEVEL, MENU_OPTION_PREV_LEVEL, MENU_OPTION_LOCK_VIEW, diff --git a/modules/mono/build_scripts/make_android_mono_config.py b/modules/mono/build_scripts/make_android_mono_config.py index d276d7d886..04f8c80243 100644 --- a/modules/mono/build_scripts/make_android_mono_config.py +++ b/modules/mono/build_scripts/make_android_mono_config.py @@ -32,7 +32,6 @@ namespace { static const int config_compressed_size = %d; static const int config_uncompressed_size = %d; static const unsigned char config_compressed_data[] = { %s }; - } // namespace String get_godot_android_mono_config() { diff --git a/modules/mono/config.py b/modules/mono/config.py index d060ae9b28..c4a6b408e6 100644 --- a/modules/mono/config.py +++ b/modules/mono/config.py @@ -11,7 +11,6 @@ def configure(env): if platform not in supported_platforms: raise RuntimeError("This module does not currently support building for this platform") - env.use_ptrcall = True env.add_module_version_string("mono") from SCons.Script import BoolVariable, PathVariable, Variables, Help diff --git a/modules/mono/editor/code_completion.cpp b/modules/mono/editor/code_completion.cpp index 9defd65190..2d37b1306c 100644 --- a/modules/mono/editor/code_completion.cpp +++ b/modules/mono/editor/code_completion.cpp @@ -228,6 +228,18 @@ PackedStringArray get_code_completion(CompletionKind p_kind, const String &p_scr } } } break; + case CompletionKind::THEME_FONT_SIZES: { + Ref<Script> script = ResourceLoader::load(p_script_file.simplify_path()); + Node *base = _try_find_owner_node_in_tree(script); + if (base && Object::cast_to<Control>(base)) { + List<StringName> sn; + Theme::get_default()->get_font_size_list(base->get_class(), &sn); + + for (List<StringName>::Element *E = sn.front(); E; E = E->next()) { + suggestions.push_back(quoted(E->get())); + } + } + } break; case CompletionKind::THEME_STYLES: { Ref<Script> script = ResourceLoader::load(p_script_file.simplify_path()); Node *base = _try_find_owner_node_in_tree(script); @@ -246,5 +258,4 @@ PackedStringArray get_code_completion(CompletionKind p_kind, const String &p_scr return suggestions; } - } // namespace gdmono diff --git a/modules/mono/editor/code_completion.h b/modules/mono/editor/code_completion.h index b9d22de0b3..e38768612b 100644 --- a/modules/mono/editor/code_completion.h +++ b/modules/mono/editor/code_completion.h @@ -46,11 +46,11 @@ enum class CompletionKind { THEME_COLORS, THEME_CONSTANTS, THEME_FONTS, + THEME_FONT_SIZES, THEME_STYLES }; PackedStringArray get_code_completion(CompletionKind p_kind, const String &p_script_file); - } // namespace gdmono #endif // CODE_COMPLETION_H diff --git a/modules/mono/editor/godotsharp_export.cpp b/modules/mono/editor/godotsharp_export.cpp index 4fa753ab8b..1a0d5743ae 100644 --- a/modules/mono/editor/godotsharp_export.cpp +++ b/modules/mono/editor/godotsharp_export.cpp @@ -141,5 +141,4 @@ Error get_exported_assembly_dependencies(const Dictionary &p_initial_assemblies, return OK; } - } // namespace GodotSharpExport diff --git a/modules/mono/editor/godotsharp_export.h b/modules/mono/editor/godotsharp_export.h index bd0f86a74b..586d4e5a0c 100644 --- a/modules/mono/editor/godotsharp_export.h +++ b/modules/mono/editor/godotsharp_export.h @@ -43,7 +43,6 @@ Error get_assembly_dependencies(GDMonoAssembly *p_assembly, const Vector<String> Error get_exported_assembly_dependencies(const Dictionary &p_initial_assemblies, const String &p_build_config, const String &p_custom_lib_dir, Dictionary &r_assembly_dependencies); - } // namespace GodotSharpExport #endif // GODOTSHARP_EXPORT_H diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Color.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Color.cs index d0add835c0..90141928ca 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Color.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Color.cs @@ -337,8 +337,8 @@ namespace Godot } /// <summary> - /// Returns the color's 32-bit integer in ABGR format - /// (each byte represents a component of the ABGR profile). + /// Returns the color converted to an unsigned 32-bit integer in ABGR + /// format (each byte represents a color channel). /// ABGR is the reversed version of the default format. /// </summary> /// <returns>A uint representing this color in ABGR32 format.</returns> @@ -356,8 +356,8 @@ namespace Godot } /// <summary> - /// Returns the color's 64-bit integer in ABGR format - /// (each word represents a component of the ABGR profile). + /// Returns the color converted to an unsigned 64-bit integer in ABGR + /// format (each word represents a color channel). /// ABGR is the reversed version of the default format. /// </summary> /// <returns>A ulong representing this color in ABGR64 format.</returns> @@ -375,8 +375,8 @@ namespace Godot } /// <summary> - /// Returns the color's 32-bit integer in ARGB format - /// (each byte represents a component of the ARGB profile). + /// Returns the color converted to an unsigned 32-bit integer in ARGB + /// format (each byte represents a color channel). /// ARGB is more compatible with DirectX, but not used much in Godot. /// </summary> /// <returns>A uint representing this color in ARGB32 format.</returns> @@ -394,8 +394,8 @@ namespace Godot } /// <summary> - /// Returns the color's 64-bit integer in ARGB format - /// (each word represents a component of the ARGB profile). + /// Returns the color converted to an unsigned 64-bit integer in ARGB + /// format (each word represents a color channel). /// ARGB is more compatible with DirectX, but not used much in Godot. /// </summary> /// <returns>A ulong representing this color in ARGB64 format.</returns> @@ -413,8 +413,8 @@ namespace Godot } /// <summary> - /// Returns the color's 32-bit integer in RGBA format - /// (each byte represents a component of the RGBA profile). + /// Returns the color converted to an unsigned 32-bit integer in RGBA + /// format (each byte represents a color channel). /// RGBA is Godot's default and recommended format. /// </summary> /// <returns>A uint representing this color in RGBA32 format.</returns> @@ -432,8 +432,8 @@ namespace Godot } /// <summary> - /// Returns the color's 64-bit integer in RGBA format - /// (each word represents a component of the RGBA profile). + /// Returns the color converted to an unsigned 64-bit integer in RGBA + /// format (each word represents a color channel). /// RGBA is Godot's default and recommended format. /// </summary> /// <returns>A ulong representing this color in RGBA64 format.</returns> @@ -472,7 +472,7 @@ namespace Godot } /// <summary> - /// Constructs a color from RGBA values on the range of 0 to 1. + /// Constructs a color from RGBA values, typically on the range of 0 to 1. /// </summary> /// <param name="r">The color's red component, typically on the range of 0 to 1.</param> /// <param name="g">The color's green component, typically on the range of 0 to 1.</param> @@ -500,8 +500,8 @@ namespace Godot } /// <summary> - /// Constructs a color from a 32-bit integer - /// (each byte represents a component of the RGBA profile). + /// Constructs a color from an unsigned 32-bit integer in RGBA format + /// (each byte represents a color channel). /// </summary> /// <param name="rgba">The uint representing the color.</param> public Color(uint rgba) @@ -516,8 +516,8 @@ namespace Godot } /// <summary> - /// Constructs a color from a 64-bit integer - /// (each word represents a component of the RGBA profile). + /// Constructs a color from an unsigned 64-bit integer in RGBA format + /// (each word represents a color channel). /// </summary> /// <param name="rgba">The ulong representing the color.</param> public Color(ulong rgba) @@ -777,31 +777,10 @@ namespace Godot return ParseCol4(str, ofs) * 16 + ParseCol4(str, ofs + 1); } - private String ToHex32(float val) + private string ToHex32(float val) { - int v = Mathf.RoundToInt(Mathf.Clamp(val * 255, 0, 255)); - - var ret = string.Empty; - - for (int i = 0; i < 2; i++) - { - char c; - int lv = v & 0xF; - - if (lv < 10) - { - c = (char)('0' + lv); - } - else - { - c = (char)('a' + lv - 10); - } - - v >>= 4; - ret = c + ret; - } - - return ret; + byte b = (byte)Mathf.RoundToInt(Mathf.Clamp(val * 255, 0, 255)); + return b.HexEncode(); } internal static bool HtmlIsValid(string color) diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs index d63db0f905..0700f197ff 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs @@ -322,6 +322,15 @@ namespace Godot return instance.IndexOf(what, from, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase); } + /// <summary>Find the first occurrence of a char. Optionally, the search starting position can be passed.</summary> + /// <returns>The first instance of the char, or -1 if not found.</returns> + public static int Find(this string instance, char what, int from = 0, bool caseSensitive = true) + { + // TODO: Could be more efficient if we get a char version of `IndexOf`. + // See https://github.com/dotnet/runtime/issues/44116 + return instance.IndexOf(what.ToString(), from, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase); + } + /// <summary>Find the last occurrence of a substring.</summary> /// <returns>The starting position of the substring, or -1 if not found.</returns> public static int FindLast(this string instance, string what, bool caseSensitive = true) @@ -437,6 +446,53 @@ namespace Godot return hashv; } + /// <summary> + /// Returns a hexadecimal representation of this byte as a string. + /// </summary> + /// <param name="bytes">The byte to encode.</param> + /// <returns>The hexadecimal representation of this byte.</returns> + internal static string HexEncode(this byte b) + { + var ret = string.Empty; + + for (int i = 0; i < 2; i++) + { + char c; + int lv = b & 0xF; + + if (lv < 10) + { + c = (char)('0' + lv); + } + else + { + c = (char)('a' + lv - 10); + } + + b >>= 4; + ret = c + ret; + } + + return ret; + } + + /// <summary> + /// Returns a hexadecimal representation of this byte array as a string. + /// </summary> + /// <param name="bytes">The byte array to encode.</param> + /// <returns>The hexadecimal representation of this byte array.</returns> + public static string HexEncode(this byte[] bytes) + { + var ret = string.Empty; + + foreach (byte b in bytes) + { + ret += b.HexEncode(); + } + + return ret; + } + // <summary> // Convert a string containing an hexadecimal number into an int. // </summary> @@ -659,6 +715,33 @@ namespace Godot } /// <summary> + /// Returns a copy of the string with characters removed from the left. + /// </summary> + /// <param name="instance">The string to remove characters from.</param> + /// <param name="chars">The characters to be removed.</param> + /// <returns>A copy of the string with characters removed from the left.</returns> + public static string LStrip(this string instance, string chars) + { + int len = instance.Length; + int beg; + + for (beg = 0; beg < len; beg++) + { + if (chars.Find(instance[beg]) == -1) + { + break; + } + } + + if (beg == 0) + { + return instance; + } + + return instance.Substr(beg, len - beg); + } + + /// <summary> /// Do a simple expression match, where '*' matches zero or more arbitrary characters and '?' matches any single character except '.'. /// </summary> private static bool ExprMatch(this string instance, string expr, bool caseSensitive) @@ -886,6 +969,33 @@ namespace Godot return instance.Substring(pos, instance.Length - pos); } + /// <summary> + /// Returns a copy of the string with characters removed from the right. + /// </summary> + /// <param name="instance">The string to remove characters from.</param> + /// <param name="chars">The characters to be removed.</param> + /// <returns>A copy of the string with characters removed from the right.</returns> + public static string RStrip(this string instance, string chars) + { + int len = instance.Length; + int end; + + for (end = len - 1; end >= 0; end--) + { + if (chars.Find(instance[end]) == -1) + { + break; + } + } + + if (end == len - 1) + { + return instance; + } + + return instance.Substr(0, end + 1); + } + public static byte[] SHA256Buffer(this string instance) { return godot_icall_String_sha256_buffer(instance); diff --git a/modules/mono/godotsharp_dirs.cpp b/modules/mono/godotsharp_dirs.cpp index 4233732bff..093a935288 100644 --- a/modules/mono/godotsharp_dirs.cpp +++ b/modules/mono/godotsharp_dirs.cpp @@ -322,5 +322,4 @@ String get_data_mono_bin_dir() { return _GodotSharpDirs::get_singleton().data_mono_bin_dir; } #endif - } // namespace GodotSharpDirs diff --git a/modules/mono/godotsharp_dirs.h b/modules/mono/godotsharp_dirs.h index 6391616419..85be506c28 100644 --- a/modules/mono/godotsharp_dirs.h +++ b/modules/mono/godotsharp_dirs.h @@ -66,7 +66,6 @@ String get_data_mono_lib_dir(); #ifdef WINDOWS_ENABLED String get_data_mono_bin_dir(); #endif - } // namespace GodotSharpDirs #endif // GODOTSHARP_DIRS_H diff --git a/modules/mono/mono_gc_handle.h b/modules/mono/mono_gc_handle.h index 5c3a210e97..b85dc70af3 100644 --- a/modules/mono/mono_gc_handle.h +++ b/modules/mono/mono_gc_handle.h @@ -42,7 +42,6 @@ enum class GCHandleType : char { STRONG_HANDLE, WEAK_HANDLE }; - } // Manual release of the GC handle must be done when using this struct diff --git a/modules/mono/mono_gd/gd_mono.cpp b/modules/mono/mono_gd/gd_mono.cpp index 0e335b3349..772961291c 100644 --- a/modules/mono/mono_gd/gd_mono.cpp +++ b/modules/mono/mono_gd/gd_mono.cpp @@ -201,7 +201,6 @@ MonoDomain *gd_initialize_mono_runtime() { return mono_jit_init_version("GodotEngine.RootDomain", runtime_version); } #endif - } // namespace void GDMono::add_mono_shared_libs_dir_to_path() { diff --git a/modules/mono/mono_gd/gd_mono.h b/modules/mono/mono_gd/gd_mono.h index 18f7418049..969296c44d 100644 --- a/modules/mono/mono_gd/gd_mono.h +++ b/modules/mono/mono_gd/gd_mono.h @@ -283,7 +283,6 @@ public: } } }; - } // namespace gdmono #define _GDMONO_SCOPE_DOMAIN_(m_mono_domain) \ diff --git a/modules/mono/mono_gd/gd_mono_cache.cpp b/modules/mono/mono_gd/gd_mono_cache.cpp index 29aef6e609..3f51c6523b 100644 --- a/modules/mono/mono_gd/gd_mono_cache.cpp +++ b/modules/mono/mono_gd/gd_mono_cache.cpp @@ -316,5 +316,4 @@ void update_godot_api_cache() { cached_data.godot_api_cache_updated = true; } - } // namespace GDMonoCache diff --git a/modules/mono/mono_gd/gd_mono_cache.h b/modules/mono/mono_gd/gd_mono_cache.h index a7bbc763a7..9dfa5769be 100644 --- a/modules/mono/mono_gd/gd_mono_cache.h +++ b/modules/mono/mono_gd/gd_mono_cache.h @@ -181,7 +181,6 @@ inline void clear_corlib_cache() { inline void clear_godot_api_cache() { cached_data.clear_godot_api_cache(); } - } // namespace GDMonoCache #define CACHED_CLASS(m_class) (GDMonoCache::cached_data.class_##m_class) diff --git a/modules/mono/mono_gd/gd_mono_internals.cpp b/modules/mono/mono_gd/gd_mono_internals.cpp index 0ed9e441ef..82f916e8c5 100644 --- a/modules/mono/mono_gd/gd_mono_internals.cpp +++ b/modules/mono/mono_gd/gd_mono_internals.cpp @@ -127,5 +127,4 @@ void unhandled_exception(MonoException *p_exc) { #endif } } - } // namespace GDMonoInternals diff --git a/modules/mono/mono_gd/gd_mono_internals.h b/modules/mono/mono_gd/gd_mono_internals.h index d1d5eca263..0fd6250785 100644 --- a/modules/mono/mono_gd/gd_mono_internals.h +++ b/modules/mono/mono_gd/gd_mono_internals.h @@ -46,7 +46,6 @@ void tie_managed_to_unmanaged(MonoObject *managed, Object *unmanaged); * Use GDMonoUtils::debug_unhandled_exception(MonoException *) instead. */ void unhandled_exception(MonoException *p_exc); - } // namespace GDMonoInternals #endif // GD_MONO_INTERNALS_H diff --git a/modules/mono/mono_gd/gd_mono_marshal.cpp b/modules/mono/mono_gd/gd_mono_marshal.cpp index 9d193ab8ab..eee880ba60 100644 --- a/modules/mono/mono_gd/gd_mono_marshal.cpp +++ b/modules/mono/mono_gd/gd_mono_marshal.cpp @@ -1536,5 +1536,4 @@ M_SignalInfo signal_info_to_managed(const Signal &p_signal) { MonoObject *name_string_name_managed = GDMonoUtils::create_managed_from(p_signal.get_name()); return { owner_managed, name_string_name_managed }; } - } // namespace GDMonoMarshal diff --git a/modules/mono/mono_gd/gd_mono_marshal.h b/modules/mono/mono_gd/gd_mono_marshal.h index d2c564d67d..d1d5f1f202 100644 --- a/modules/mono/mono_gd/gd_mono_marshal.h +++ b/modules/mono/mono_gd/gd_mono_marshal.h @@ -271,7 +271,6 @@ static_assert(MATCHES_Vector2 && MATCHES_Rect2 && MATCHES_Transform2D && MATCHES MATCHES_Plane && MATCHES_Vector2i && MATCHES_Rect2i && MATCHES_Vector3i); /* clang-format on */ #endif - } // namespace InteropLayout #pragma pack(push, 1) @@ -517,7 +516,6 @@ DECL_TYPE_MARSHAL_TEMPLATES(Plane) #define MARSHALLED_IN(m_type, m_from_ptr) (GDMonoMarshal::marshalled_in_##m_type(m_from_ptr)) #define MARSHALLED_OUT(m_type, m_from) (GDMonoMarshal::marshalled_out_##m_type(m_from)) - } // namespace GDMonoMarshal #endif // GDMONOMARSHAL_H diff --git a/modules/mono/mono_gd/gd_mono_utils.cpp b/modules/mono/mono_gd/gd_mono_utils.cpp index 2676165cbc..97fc4c57f9 100644 --- a/modules/mono/mono_gd/gd_mono_utils.cpp +++ b/modules/mono/mono_gd/gd_mono_utils.cpp @@ -659,7 +659,6 @@ GDMonoClass *make_generic_dictionary_type(MonoReflectionType *p_key_reftype, Mon UNHANDLED_EXCEPTION(exc); return GDMono::get_singleton()->get_class(mono_class_from_mono_type(mono_reflection_type_get_type(reftype))); } - } // namespace Marshal ScopeThreadAttach::ScopeThreadAttach() { @@ -679,5 +678,4 @@ StringName get_native_godot_class_name(GDMonoClass *p_class) { StringName *ptr = GDMonoMarshal::unbox<StringName *>(CACHED_FIELD(StringName, ptr)->get_value(native_name_obj)); return ptr ? *ptr : StringName(); } - } // namespace GDMonoUtils diff --git a/modules/mono/mono_gd/gd_mono_utils.h b/modules/mono/mono_gd/gd_mono_utils.h index 7088385c4f..71c131f77c 100644 --- a/modules/mono/mono_gd/gd_mono_utils.h +++ b/modules/mono/mono_gd/gd_mono_utils.h @@ -64,7 +64,6 @@ void dictionary_get_key_value_types(MonoReflectionType *p_dict_reftype, MonoRefl GDMonoClass *make_generic_array_type(MonoReflectionType *p_elem_reftype); GDMonoClass *make_generic_dictionary_type(MonoReflectionType *p_key_reftype, MonoReflectionType *p_value_reftype); - } // namespace Marshal _FORCE_INLINE_ void hash_combine(uint32_t &p_hash, const uint32_t &p_with_hash) { @@ -156,7 +155,6 @@ private: }; StringName get_native_godot_class_name(GDMonoClass *p_class); - } // namespace GDMonoUtils #define NATIVE_GDMONOCLASS_NAME(m_class) (GDMonoUtils::get_native_godot_class_name(m_class)) diff --git a/modules/mono/mono_gd/support/android_support.cpp b/modules/mono/mono_gd/support/android_support.cpp index 386e0576b3..18daf859b5 100644 --- a/modules/mono/mono_gd/support/android_support.cpp +++ b/modules/mono/mono_gd/support/android_support.cpp @@ -387,7 +387,6 @@ void cleanup() { certStore = nullptr; } } - } // namespace support } // namespace android } // namespace gdmono diff --git a/modules/mono/mono_gd/support/android_support.h b/modules/mono/mono_gd/support/android_support.h index 5947395a99..df51100bef 100755 --- a/modules/mono/mono_gd/support/android_support.h +++ b/modules/mono/mono_gd/support/android_support.h @@ -45,7 +45,6 @@ void initialize(); void cleanup(); void register_internal_calls(); - } // namespace support } // namespace android } // namespace gdmono diff --git a/modules/mono/mono_gd/support/ios_support.h b/modules/mono/mono_gd/support/ios_support.h index ed251cb23a..48cef890d6 100755 --- a/modules/mono/mono_gd/support/ios_support.h +++ b/modules/mono/mono_gd/support/ios_support.h @@ -41,7 +41,6 @@ namespace support { void initialize(); void cleanup(); - } // namespace support } // namespace ios } // namespace gdmono diff --git a/modules/mono/mono_gd/support/ios_support.mm b/modules/mono/mono_gd/support/ios_support.mm index dc23c06eba..e6e09c4146 100644 --- a/modules/mono/mono_gd/support/ios_support.mm +++ b/modules/mono/mono_gd/support/ios_support.mm @@ -72,7 +72,6 @@ void initialize() { void cleanup() { } - } // namespace support } // namespace ios } // namespace gdmono diff --git a/modules/mono/utils/macros.h b/modules/mono/utils/macros.h index c76619cca4..60c9b9718a 100644 --- a/modules/mono/utils/macros.h +++ b/modules/mono/utils/macros.h @@ -64,7 +64,6 @@ public: template <typename F> ScopeExit<F> operator+(F p_exit_func) { return ScopeExit<F>(p_exit_func); } }; - } // namespace gdmono #define SCOPE_EXIT \ diff --git a/modules/mono/utils/mono_reg_utils.cpp b/modules/mono/utils/mono_reg_utils.cpp index a619f0b975..9902744743 100644 --- a/modules/mono/utils/mono_reg_utils.cpp +++ b/modules/mono/utils/mono_reg_utils.cpp @@ -225,7 +225,6 @@ cleanup: return msbuild_tools_path; } - } // namespace MonoRegUtils #endif // WINDOWS_ENABLED diff --git a/modules/mono/utils/path_utils.cpp b/modules/mono/utils/path_utils.cpp index eb0ba8c700..a24097924e 100644 --- a/modules/mono/utils/path_utils.cpp +++ b/modules/mono/utils/path_utils.cpp @@ -194,5 +194,4 @@ String relative_to(const String &p_path, const String &p_relative_to) { return relative_to_impl(path_abs_norm, relative_to_abs_norm); } - } // namespace path diff --git a/modules/mono/utils/path_utils.h b/modules/mono/utils/path_utils.h index 458d1bb849..c19cb3bc8b 100644 --- a/modules/mono/utils/path_utils.h +++ b/modules/mono/utils/path_utils.h @@ -56,7 +56,6 @@ String abspath(const String &p_path); String realpath(const String &p_path); String relative_to(const String &p_path, const String &p_relative_to); - } // namespace path #endif // PATH_UTILS_H diff --git a/modules/mono/utils/string_utils.cpp b/modules/mono/utils/string_utils.cpp index 65da4328f6..d70004657c 100644 --- a/modules/mono/utils/string_utils.cpp +++ b/modules/mono/utils/string_utils.cpp @@ -84,7 +84,6 @@ int sfind(const String &p_text, int p_from) { return -1; } - } // namespace String sformat(const String &p_text, const Variant &p1, const Variant &p2, const Variant &p3, const Variant &p4, const Variant &p5) { diff --git a/modules/pvr/texture_loader_pvr.cpp b/modules/pvr/texture_loader_pvr.cpp index 050dce1aab..0923714387 100644 --- a/modules/pvr/texture_loader_pvr.cpp +++ b/modules/pvr/texture_loader_pvr.cpp @@ -38,7 +38,6 @@ static void _pvrtc_decompress(Image *p_img); enum PVRFLags { - PVR_HAS_MIPMAPS = 0x00000100, PVR_TWIDDLED = 0x00000200, PVR_NORMAL_MAP = 0x00000400, @@ -48,7 +47,6 @@ enum PVRFLags { PVR_VOLUME_TEXTURES = 0x00004000, PVR_HAS_ALPHA = 0x00008000, PVR_VFLIP = 0x00010000 - }; RES ResourceFormatPVR::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, bool p_no_cache) { diff --git a/modules/regex/regex.h b/modules/regex/regex.h index 8cf19e1ca6..5b4798b65a 100644 --- a/modules/regex/regex.h +++ b/modules/regex/regex.h @@ -83,7 +83,6 @@ protected: public: void clear(); Error compile(const String &p_pattern); - void _init(const String &p_pattern = ""); Ref<RegExMatch> search(const String &p_subject, int p_offset = 0, int p_end = -1) const; Array search_all(const String &p_subject, int p_offset = 0, int p_end = -1) const; diff --git a/modules/regex/tests/test_regex.h b/modules/regex/tests/test_regex.h new file mode 100644 index 0000000000..4b9e7e18eb --- /dev/null +++ b/modules/regex/tests/test_regex.h @@ -0,0 +1,164 @@ +/*************************************************************************/ +/* test_regex.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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. */ +/*************************************************************************/ + +#ifndef TEST_REGEX_H +#define TEST_REGEX_H + +#include "core/string/ustring.h" +#include "modules/regex/regex.h" + +#include "tests/test_macros.h" + +namespace TestRegEx { + +TEST_CASE("[RegEx] Initialization") { + const String pattern = "(?<vowel>[aeiou])"; + + RegEx re1(pattern); + CHECK(re1.is_valid()); + CHECK(re1.get_pattern() == pattern); + CHECK(re1.get_group_count() == 1); + + Array names = re1.get_names(); + CHECK(names.size() == 1); + CHECK(names[0] == "vowel"); + + RegEx re2; + CHECK(re2.is_valid() == false); + CHECK(re2.compile(pattern) == OK); + CHECK(re2.is_valid()); + + CHECK(re1.get_pattern() == re2.get_pattern()); + CHECK(re1.get_group_count() == re2.get_group_count()); + + names = re2.get_names(); + CHECK(names.size() == 1); + CHECK(names[0] == "vowel"); +} + +TEST_CASE("[RegEx] Clearing") { + RegEx re("Godot"); + REQUIRE(re.is_valid()); + re.clear(); + CHECK(re.is_valid() == false); +} + +TEST_CASE("[RegEx] Searching") { + const String s = "Searching"; + const String vowels = "[aeiou]{1,2}"; + const String numerics = "\\d"; + + RegEx re(vowels); + REQUIRE(re.is_valid()); + + Ref<RegExMatch> match = re.search(s); + REQUIRE(match != nullptr); + CHECK(match->get_string(0) == "ea"); + + match = re.search(s, 2, 4); + REQUIRE(match != nullptr); + CHECK(match->get_string(0) == "a"); + + const Array all_results = re.search_all(s); + CHECK(all_results.size() == 2); + match = all_results[0]; + REQUIRE(match != nullptr); + CHECK(match->get_string(0) == "ea"); + match = all_results[1]; + REQUIRE(match != nullptr); + CHECK(match->get_string(0) == "i"); + + CHECK(re.compile(numerics) == OK); + CHECK(re.is_valid()); + CHECK(re.search(s) == nullptr); + CHECK(re.search_all(s).size() == 0); +} + +TEST_CASE("[RegEx] Substitution") { + String s = "Double all the vowels."; + + RegEx re("(?<vowel>[aeiou])"); + REQUIRE(re.is_valid()); + CHECK(re.sub(s, "$0$vowel", true) == "Doouublee aall thee vooweels."); +} + +TEST_CASE("[RegEx] Uninitialized use") { + const String s = "Godot"; + + RegEx re; + ERR_PRINT_OFF; + CHECK(re.search(s) == nullptr); + CHECK(re.search_all(s).size() == 0); + CHECK(re.sub(s, "") == ""); + CHECK(re.get_group_count() == 0); + CHECK(re.get_names().size() == 0); + ERR_PRINT_ON +} + +TEST_CASE("[RegEx] Empty Pattern") { + const String s = "Godot"; + + RegEx re; + CHECK(re.compile("") == OK); + CHECK(re.is_valid()); +} + +TEST_CASE("[RegEx] Invalid offset") { + const String s = "Godot"; + + RegEx re("o"); + REQUIRE(re.is_valid()); + CHECK(re.search(s, -1) == nullptr); + CHECK(re.search_all(s, -1).size() == 0); + CHECK(re.sub(s, "", true, -1) == ""); +} + +TEST_CASE("[RegEx] Invalid end position") { + const String s = "Godot"; + + RegEx re("o"); + REQUIRE(re.is_valid()); + Ref<RegExMatch> match = re.search(s, 0, 10); + CHECK(match->get_string(0) == "o"); + + const Array all_results = re.search_all(s, 0, 10); + CHECK(all_results.size() == 2); + match = all_results[0]; + REQUIRE(match != nullptr); + CHECK(match->get_string(0) == String("o")); + match = all_results[1]; + REQUIRE(match != nullptr); + CHECK(match->get_string(0) == String("o")); + + CHECK(re.sub(s, "", true, 0, 10) == "Gdt"); +} +} // namespace TestRegEx + +#endif // TEST_REGEX_H diff --git a/modules/text_server_adv/SCsub b/modules/text_server_adv/SCsub new file mode 100644 index 0000000000..7403b01a4c --- /dev/null +++ b/modules/text_server_adv/SCsub @@ -0,0 +1,489 @@ +#!/usr/bin/env python + +Import("env") +Import("env_modules") + +env_text_server_adv = env_modules.Clone() + + +def make_icu_data(target, source, env): + import os + + dst = target[0].srcnode().abspath + + g = open(dst, "w", encoding="utf-8") + + g.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n") + g.write("/* (C) 2016 and later: Unicode, Inc. and others. */\n") + g.write("/* License & terms of use: http://www.unicode.org/copyright.html */\n") + g.write("#ifndef _ICU_DATA_H\n") + g.write("#define _ICU_DATA_H\n") + g.write('#include "unicode/utypes.h"\n') + g.write('#include "unicode/udata.h"\n') + g.write('#include "unicode/uversion.h"\n') + + f = open(source[0].srcnode().abspath, "rb") + buf = f.read() + import os.path + + g.write('extern "C" U_EXPORT const size_t U_ICUDATA_SIZE = ' + str(len(buf)) + ";\n") + g.write('extern "C" U_EXPORT const unsigned char U_ICUDATA_ENTRY_POINT[] = {\n') + for i in range(len(buf)): + g.write("\t" + str(buf[i]) + ",\n") + + g.write("};\n") + g.write("#endif") + + +if env["builtin_harfbuzz"]: + env_harfbuzz = env_modules.Clone() + + # Thirdparty source files + thirdparty_dir = "#thirdparty/harfbuzz/" + thirdparty_sources = [ + "src/hb-aat-layout.cc", + "src/hb-aat-map.cc", + "src/hb-blob.cc", + "src/hb-buffer-serialize.cc", + "src/hb-buffer.cc", + "src/hb-common.cc", + #'src/hb-coretext.cc', + #'src/hb-directwrite.cc', + "src/hb-draw.cc", + "src/hb-face.cc", + "src/hb-fallback-shape.cc", + "src/hb-font.cc", + "src/hb-ft.cc", + #'src/hb-gdi.cc', + #'src/hb-glib.cc', + #'src/hb-gobject-structs.cc', + "src/hb-graphite2.cc", + "src/hb-icu.cc", + "src/hb-map.cc", + "src/hb-number.cc", + "src/hb-ot-cff1-table.cc", + "src/hb-ot-cff2-table.cc", + "src/hb-ot-color.cc", + "src/hb-ot-face.cc", + "src/hb-ot-font.cc", + "src/hb-ot-layout.cc", + "src/hb-ot-map.cc", + "src/hb-ot-math.cc", + "src/hb-ot-meta.cc", + "src/hb-ot-metrics.cc", + "src/hb-ot-name.cc", + "src/hb-ot-shape-complex-arabic.cc", + "src/hb-ot-shape-complex-default.cc", + "src/hb-ot-shape-complex-hangul.cc", + "src/hb-ot-shape-complex-hebrew.cc", + "src/hb-ot-shape-complex-indic-table.cc", + "src/hb-ot-shape-complex-indic.cc", + "src/hb-ot-shape-complex-khmer.cc", + "src/hb-ot-shape-complex-myanmar.cc", + "src/hb-ot-shape-complex-thai.cc", + "src/hb-ot-shape-complex-use-table.cc", + "src/hb-ot-shape-complex-use.cc", + "src/hb-ot-shape-complex-vowel-constraints.cc", + "src/hb-ot-shape-fallback.cc", + "src/hb-ot-shape-normalize.cc", + "src/hb-ot-shape.cc", + "src/hb-ot-tag.cc", + "src/hb-ot-var.cc", + "src/hb-set.cc", + "src/hb-shape-plan.cc", + "src/hb-shape.cc", + "src/hb-shaper.cc", + "src/hb-static.cc", + "src/hb-style.cc", + "src/hb-subset-cff-common.cc", + "src/hb-subset-cff1.cc", + "src/hb-subset-cff2.cc", + "src/hb-subset-input.cc", + "src/hb-subset-plan.cc", + "src/hb-subset.cc", + "src/hb-ucd.cc", + "src/hb-unicode.cc", + #'src/hb-uniscribe.cc' + ] + thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] + + if env["platform"] == "android" or env["platform"] == "linuxbsd" or env["platform"] == "server": + env_harfbuzz.Append(CCFLAGS=["-DHAVE_PTHREAD"]) + + if env["platform"] == "javascript": + if env["threads_enabled"]: + env_harfbuzz.Append(CCFLAGS=["-DHAVE_PTHREAD"]) + else: + env_harfbuzz.Append(CCFLAGS=["-DHB_NO_MT"]) + + env_harfbuzz.Append( + CPPPATH=[ + "#thirdparty/harfbuzz/src", + "#thirdparty/freetype/include", + "#thirdparty/graphite/include", + "#thirdparty/icu4c/common/", + ] + ) + env_harfbuzz.Append( + CCFLAGS=[ + "-DHAVE_ICU_BUILTIN", + "-DHAVE_ICU", + "-DHAVE_FREETYPE", + "-DHAVE_GRAPHITE2", + "-DGRAPHITE2_STATIC", + ] + ) + env_harfbuzz.disable_warnings() + env_thirdparty = env_harfbuzz.Clone() + env_thirdparty.disable_warnings() + lib = env_thirdparty.add_library("harfbuzz_builtin", thirdparty_sources) + + # Needs to be appended to arrive after libscene in the linker call, + # but we don't want it to arrive *after* system libs, so manual hack + # LIBS contains first SCons Library objects ("SCons.Node.FS.File object") + # and then plain strings for system library. We insert between the two. + inserted = False + for idx, linklib in enumerate(env["LIBS"]): + if isinstance(linklib, (str, bytes)): # first system lib such as "X11", otherwise SCons lib object + env["LIBS"].insert(idx, lib) + inserted = True + break + if not inserted: + env.Append(LIBS=[lib]) + +if env["builtin_graphite"]: + env_graphite = env_modules.Clone() + + # Thirdparty source files + thirdparty_dir = "#thirdparty/graphite/" + thirdparty_sources = [ + "src/gr_char_info.cpp", + "src/gr_face.cpp", + "src/gr_features.cpp", + "src/gr_font.cpp", + "src/gr_logging.cpp", + "src/gr_segment.cpp", + "src/gr_slot.cpp", + "src/CmapCache.cpp", + "src/Code.cpp", + "src/Collider.cpp", + "src/Decompressor.cpp", + "src/Face.cpp", + #'src/FileFace.cpp', + "src/FeatureMap.cpp", + "src/Font.cpp", + "src/GlyphCache.cpp", + "src/GlyphFace.cpp", + "src/Intervals.cpp", + "src/Justifier.cpp", + "src/NameTable.cpp", + "src/Pass.cpp", + "src/Position.cpp", + "src/Segment.cpp", + "src/Silf.cpp", + "src/Slot.cpp", + "src/Sparse.cpp", + "src/TtfUtil.cpp", + "src/UtfCodec.cpp", + "src/FileFace.cpp", + "src/json.cpp", + ] + if not env_graphite.msvc: + thirdparty_sources += ["src/direct_machine.cpp"] + else: + thirdparty_sources += ["src/call_machine.cpp"] + + thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] + + env_graphite.Append(CPPPATH=["#thirdparty/graphite/src", "#thirdparty/graphite/include"]) + env_graphite.Append( + CCFLAGS=[ + "-DGRAPHITE2_STATIC", + "-DGRAPHITE2_NTRACING", + "-DGRAPHITE2_NFILEFACE", + ] + ) + env_graphite.disable_warnings() + env_thirdparty = env_graphite.Clone() + env_thirdparty.disable_warnings() + lib = env_thirdparty.add_library("graphite_builtin", thirdparty_sources) + + # Needs to be appended to arrive after libscene in the linker call, + # but we don't want it to arrive *after* system libs, so manual hack + # LIBS contains first SCons Library objects ("SCons.Node.FS.File object") + # and then plain strings for system library. We insert between the two. + inserted = False + for idx, linklib in enumerate(env["LIBS"]): + if isinstance(linklib, (str, bytes)): # first system lib such as "X11", otherwise SCons lib object + env["LIBS"].insert(idx, lib) + inserted = True + break + if not inserted: + env.Append(LIBS=[lib]) + +if env["builtin_icu"]: + env_icu = env_modules.Clone() + + # Thirdparty source files + thirdparty_dir = "#thirdparty/icu4c/" + # Thirdparty source files + thirdparty_sources = [ + "common/appendable.cpp", + "common/bmpset.cpp", + "common/brkeng.cpp", + "common/brkiter.cpp", + "common/bytesinkutil.cpp", + "common/bytestream.cpp", + "common/bytestrie.cpp", + "common/bytestriebuilder.cpp", + "common/bytestrieiterator.cpp", + "common/caniter.cpp", + "common/characterproperties.cpp", + "common/chariter.cpp", + "common/charstr.cpp", + "common/cmemory.cpp", + "common/cstr.cpp", + "common/cstring.cpp", + "common/cwchar.cpp", + "common/dictbe.cpp", + "common/dictionarydata.cpp", + "common/dtintrv.cpp", + "common/edits.cpp", + "common/errorcode.cpp", + "common/filteredbrk.cpp", + "common/filterednormalizer2.cpp", + "common/icudataver.cpp", + "common/icuplug.cpp", + "common/loadednormalizer2impl.cpp", + "common/localebuilder.cpp", + "common/localematcher.cpp", + "common/localeprioritylist.cpp", + "common/locavailable.cpp", + "common/locbased.cpp", + "common/locdispnames.cpp", + "common/locdistance.cpp", + "common/locdspnm.cpp", + "common/locid.cpp", + "common/loclikely.cpp", + "common/loclikelysubtags.cpp", + "common/locmap.cpp", + "common/locresdata.cpp", + "common/locutil.cpp", + "common/lsr.cpp", + "common/messagepattern.cpp", + "common/normalizer2.cpp", + "common/normalizer2impl.cpp", + "common/normlzr.cpp", + "common/parsepos.cpp", + "common/patternprops.cpp", + "common/pluralmap.cpp", + "common/propname.cpp", + "common/propsvec.cpp", + "common/punycode.cpp", + "common/putil.cpp", + "common/rbbi.cpp", + "common/rbbi_cache.cpp", + "common/rbbidata.cpp", + "common/rbbinode.cpp", + "common/rbbirb.cpp", + "common/rbbiscan.cpp", + "common/rbbisetb.cpp", + "common/rbbistbl.cpp", + "common/rbbitblb.cpp", + "common/resbund.cpp", + "common/resbund_cnv.cpp", + "common/resource.cpp", + "common/restrace.cpp", + "common/ruleiter.cpp", + "common/schriter.cpp", + "common/serv.cpp", + "common/servlk.cpp", + "common/servlkf.cpp", + "common/servls.cpp", + "common/servnotf.cpp", + "common/servrbf.cpp", + "common/servslkf.cpp", + "common/sharedobject.cpp", + "common/simpleformatter.cpp", + "common/static_unicode_sets.cpp", + "common/stringpiece.cpp", + "common/stringtriebuilder.cpp", + "common/uarrsort.cpp", + "common/ubidi.cpp", + "common/ubidi_props.cpp", + "common/ubidiln.cpp", + "common/ubiditransform.cpp", + "common/ubidiwrt.cpp", + "common/ubrk.cpp", + "common/ucase.cpp", + "common/ucasemap.cpp", + "common/ucasemap_titlecase_brkiter.cpp", + "common/ucat.cpp", + "common/uchar.cpp", + "common/ucharstrie.cpp", + "common/ucharstriebuilder.cpp", + "common/ucharstrieiterator.cpp", + "common/uchriter.cpp", + "common/ucln_cmn.cpp", + "common/ucmndata.cpp", + "common/ucnv.cpp", + "common/ucnv2022.cpp", + "common/ucnv_bld.cpp", + "common/ucnv_cb.cpp", + "common/ucnv_cnv.cpp", + "common/ucnv_ct.cpp", + "common/ucnv_err.cpp", + "common/ucnv_ext.cpp", + "common/ucnv_io.cpp", + "common/ucnv_lmb.cpp", + "common/ucnv_set.cpp", + "common/ucnv_u16.cpp", + "common/ucnv_u32.cpp", + "common/ucnv_u7.cpp", + "common/ucnv_u8.cpp", + "common/ucnvbocu.cpp", + "common/ucnvdisp.cpp", + "common/ucnvhz.cpp", + "common/ucnvisci.cpp", + "common/ucnvlat1.cpp", + "common/ucnvmbcs.cpp", + "common/ucnvscsu.cpp", + "common/ucnvsel.cpp", + "common/ucol_swp.cpp", + "common/ucptrie.cpp", + "common/ucurr.cpp", + "common/udata.cpp", + "common/udatamem.cpp", + "common/udataswp.cpp", + "common/uenum.cpp", + "common/uhash.cpp", + "common/uhash_us.cpp", + "common/uidna.cpp", + "common/uinit.cpp", + "common/uinvchar.cpp", + "common/uiter.cpp", + "common/ulist.cpp", + "common/uloc.cpp", + "common/uloc_keytype.cpp", + "common/uloc_tag.cpp", + "common/umapfile.cpp", + "common/umath.cpp", + "common/umutablecptrie.cpp", + "common/umutex.cpp", + "common/unames.cpp", + "common/unifiedcache.cpp", + "common/unifilt.cpp", + "common/unifunct.cpp", + "common/uniset.cpp", + "common/uniset_closure.cpp", + "common/uniset_props.cpp", + "common/unisetspan.cpp", + "common/unistr.cpp", + "common/unistr_case.cpp", + "common/unistr_case_locale.cpp", + "common/unistr_cnv.cpp", + "common/unistr_props.cpp", + "common/unistr_titlecase_brkiter.cpp", + "common/unorm.cpp", + "common/unormcmp.cpp", + "common/uobject.cpp", + "common/uprops.cpp", + "common/ures_cnv.cpp", + "common/uresbund.cpp", + "common/uresdata.cpp", + "common/usc_impl.cpp", + "common/uscript.cpp", + "common/uscript_props.cpp", + "common/uset.cpp", + "common/uset_props.cpp", + "common/usetiter.cpp", + # "common/ushape.cpp", + "common/usprep.cpp", + "common/ustack.cpp", + "common/ustr_cnv.cpp", + "common/ustr_titlecase_brkiter.cpp", + "common/ustr_wcs.cpp", + "common/ustrcase.cpp", + "common/ustrcase_locale.cpp", + "common/ustrenum.cpp", + "common/ustrfmt.cpp", + "common/ustring.cpp", + "common/ustrtrns.cpp", + "common/utext.cpp", + "common/utf_impl.cpp", + "common/util.cpp", + "common/util_props.cpp", + "common/utrace.cpp", + "common/utrie.cpp", + "common/utrie2.cpp", + "common/utrie2_builder.cpp", + "common/utrie_swap.cpp", + "common/uts46.cpp", + "common/utypes.cpp", + "common/uvector.cpp", + "common/uvectr32.cpp", + "common/uvectr64.cpp", + "common/wintz.cpp", + ] + thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] + + icu_data_name = "icudt68l.dat" + + if env_icu["tools"]: + env_icu.Depends("#thirdparty/icu4c/icudata.gen.h", "#thirdparty/icu4c/" + icu_data_name) + env_icu.Command("#thirdparty/icu4c/icudata.gen.h", "#thirdparty/icu4c/" + icu_data_name, make_icu_data) + else: + thirdparty_sources += ["icu_data/icudata_stub.cpp"] + + env_icu.Append(CPPPATH=["#thirdparty/icu4c/common/"]) + env_icu.Append( + CXXFLAGS=[ + "-DU_STATIC_IMPLEMENTATION", + "-DU_COMMON_IMPLEMENTATION", + "-DUCONFIG_NO_COLLATION", + "-DUCONFIG_NO_CONVERSION", + "-DUCONFIG_NO_FORMATTING", + "-DUCONFIG_NO_SERVICE", + "-DUCONFIG_NO_IDNA", + "-DUCONFIG_NO_FILE_IO", + "-DUCONFIG_NO_TRANSLITERATION", + "-DPKGDATA_MODE=static", + "-DICU_DATA_NAME=" + icu_data_name, + ] + ) + env_text_server_adv.Append( + CXXFLAGS=[ + "-DICU_DATA_NAME=" + icu_data_name, + ] + ) + + env_icu.disable_warnings() + env_thirdparty = env_icu.Clone() + env_thirdparty.disable_warnings() + lib = env_thirdparty.add_library("icu_builtin", thirdparty_sources) + + # Needs to be appended to arrive after libscene in the linker call, + # but we don't want it to arrive *after* system libs, so manual hack + # LIBS contains first SCons Library objects ("SCons.Node.FS.File object") + # and then plain strings for system library. We insert between the two. + inserted = False + for idx, linklib in enumerate(env["LIBS"]): + if isinstance(linklib, (str, bytes)): # first system lib such as "X11", otherwise SCons lib object + env["LIBS"].insert(idx, lib) + inserted = True + break + if not inserted: + env.Append(LIBS=[lib]) + +if env_text_server_adv["tools"]: + env_text_server_adv.Append(CXXFLAGS=["-DICU_STATIC_DATA"]) + +env_text_server_adv.Append( + CPPPATH=[ + "#thirdparty/harfbuzz/src", + "#thirdparty/freetype/include", + "#thirdparty/graphite/include", + "#thirdparty/icu4c/common/", + ] +) +env_text_server_adv.add_source_files(env.modules_sources, "*.cpp") diff --git a/modules/text_server_adv/bitmap_font_adv.cpp b/modules/text_server_adv/bitmap_font_adv.cpp new file mode 100644 index 0000000000..10c3732fd7 --- /dev/null +++ b/modules/text_server_adv/bitmap_font_adv.cpp @@ -0,0 +1,575 @@ +/*************************************************************************/ +/* bitmap_font_adv.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 "bitmap_font_adv.h" + +/*************************************************************************/ +/* hb_bmp_font_t HarfBuzz Bitmap font interface */ +/*************************************************************************/ + +struct hb_bmp_font_t { + BitmapFontDataAdvanced *face = nullptr; + float font_size = 0; + bool unref = false; /* Whether to destroy bm_face when done. */ +}; + +static hb_bmp_font_t *_hb_bmp_font_create(BitmapFontDataAdvanced *p_face, float p_font_size, bool p_unref) { + hb_bmp_font_t *bm_font = reinterpret_cast<hb_bmp_font_t *>(calloc(1, sizeof(hb_bmp_font_t))); + + if (!bm_font) { + return nullptr; + } + + bm_font->face = p_face; + bm_font->font_size = p_font_size; + bm_font->unref = p_unref; + + return bm_font; +} + +static void _hb_bmp_font_destroy(void *data) { + hb_bmp_font_t *bm_font = reinterpret_cast<hb_bmp_font_t *>(data); + free(bm_font); +} + +static hb_bool_t hb_bmp_get_nominal_glyph(hb_font_t *font, void *font_data, hb_codepoint_t unicode, hb_codepoint_t *glyph, void *user_data) { + const hb_bmp_font_t *bm_font = reinterpret_cast<const hb_bmp_font_t *>(font_data); + + if (!bm_font->face) { + return false; + } + + if (!bm_font->face->has_char(unicode)) { + if (bm_font->face->has_char(0xF000u + unicode)) { + *glyph = 0xF000u + unicode; + return true; + } else { + return false; + } + } + + *glyph = unicode; + return true; +} + +static hb_position_t hb_bmp_get_glyph_h_advance(hb_font_t *font, void *font_data, hb_codepoint_t glyph, void *user_data) { + const hb_bmp_font_t *bm_font = reinterpret_cast<const hb_bmp_font_t *>(font_data); + + if (!bm_font->face) { + return 0; + } + + if (!bm_font->face->has_char(glyph)) { + return 0; + } + + return bm_font->face->get_advance(glyph, bm_font->font_size).x * 64; +} + +static hb_position_t hb_bmp_get_glyph_v_advance(hb_font_t *font, void *font_data, hb_codepoint_t glyph, void *user_data) { + const hb_bmp_font_t *bm_font = reinterpret_cast<const hb_bmp_font_t *>(font_data); + + if (!bm_font->face) { + return 0; + } + + if (!bm_font->face->has_char(glyph)) { + return 0; + } + + return -bm_font->face->get_advance(glyph, bm_font->font_size).y * 64; +} + +static hb_position_t hb_bmp_get_glyph_h_kerning(hb_font_t *font, void *font_data, hb_codepoint_t left_glyph, hb_codepoint_t right_glyph, void *user_data) { + const hb_bmp_font_t *bm_font = reinterpret_cast<const hb_bmp_font_t *>(font_data); + + if (!bm_font->face) { + return 0; + } + + if (!bm_font->face->has_char(left_glyph)) { + return 0; + } + + if (!bm_font->face->has_char(right_glyph)) { + return 0; + } + + return bm_font->face->get_kerning(left_glyph, right_glyph, bm_font->font_size).x * 64; +} + +static hb_bool_t hb_bmp_get_glyph_v_origin(hb_font_t *font, void *font_data, hb_codepoint_t glyph, hb_position_t *x, hb_position_t *y, void *user_data) { + const hb_bmp_font_t *bm_font = reinterpret_cast<const hb_bmp_font_t *>(font_data); + + if (!bm_font->face) { + return false; + } + + if (!bm_font->face->has_char(glyph)) { + return false; + } + + *x = bm_font->face->get_advance(glyph, bm_font->font_size).x * 32; + *y = bm_font->face->get_ascent(bm_font->font_size) * 64; + + return true; +} + +static hb_bool_t hb_bmp_get_glyph_extents(hb_font_t *font, void *font_data, hb_codepoint_t glyph, hb_glyph_extents_t *extents, void *user_data) { + const hb_bmp_font_t *bm_font = reinterpret_cast<const hb_bmp_font_t *>(font_data); + + if (!bm_font->face) { + return false; + } + + if (!bm_font->face->has_char(glyph)) { + return false; + } + + extents->x_bearing = 0; + extents->y_bearing = 0; + extents->width = bm_font->face->get_size(glyph, bm_font->font_size).x * 64; + extents->height = bm_font->face->get_size(glyph, bm_font->font_size).y * 64; + + return true; +} + +static hb_bool_t hb_bmp_get_font_h_extents(hb_font_t *font, void *font_data, hb_font_extents_t *metrics, void *user_data) { + const hb_bmp_font_t *bm_font = reinterpret_cast<const hb_bmp_font_t *>(font_data); + + if (!bm_font->face) { + return false; + } + + metrics->ascender = bm_font->face->get_ascent(bm_font->font_size); + metrics->descender = bm_font->face->get_descent(bm_font->font_size); + metrics->line_gap = 0; + + return true; +} + +static hb_font_funcs_t *_hb_bmp_get_font_funcs() { + hb_font_funcs_t *funcs = hb_font_funcs_create(); + + hb_font_funcs_set_font_h_extents_func(funcs, hb_bmp_get_font_h_extents, nullptr, nullptr); + //hb_font_funcs_set_font_v_extents_func (funcs, hb_bmp_get_font_v_extents, nullptr, nullptr); + hb_font_funcs_set_nominal_glyph_func(funcs, hb_bmp_get_nominal_glyph, nullptr, nullptr); + //hb_font_funcs_set_variation_glyph_func (funcs, hb_bmp_get_variation_glyph, nullptr, nullptr); + hb_font_funcs_set_glyph_h_advance_func(funcs, hb_bmp_get_glyph_h_advance, nullptr, nullptr); + hb_font_funcs_set_glyph_v_advance_func(funcs, hb_bmp_get_glyph_v_advance, nullptr, nullptr); + //hb_font_funcs_set_glyph_h_origin_func(funcs, hb_bmp_get_glyph_h_origin, nullptr, nullptr); + hb_font_funcs_set_glyph_v_origin_func(funcs, hb_bmp_get_glyph_v_origin, nullptr, nullptr); + hb_font_funcs_set_glyph_h_kerning_func(funcs, hb_bmp_get_glyph_h_kerning, nullptr, nullptr); + //hb_font_funcs_set_glyph_v_kerning_func (funcs, hb_bmp_get_glyph_v_kerning, nullptr, nullptr); + hb_font_funcs_set_glyph_extents_func(funcs, hb_bmp_get_glyph_extents, nullptr, nullptr); + //hb_font_funcs_set_glyph_contour_point_func (funcs, hb_bmp_get_glyph_contour_point, nullptr, nullptr); + //hb_font_funcs_set_glyph_name_func (funcs, hb_bmp_get_glyph_name, nullptr, nullptr); + //hb_font_funcs_set_glyph_from_name_func (funcs, hb_bmp_get_glyph_from_name, nullptr, nullptr); + + hb_font_funcs_make_immutable(funcs); + + return funcs; +} + +static void _hb_bmp_font_set_funcs(hb_font_t *p_font, BitmapFontDataAdvanced *p_face, int p_size, bool p_unref) { + hb_font_set_funcs(p_font, _hb_bmp_get_font_funcs(), _hb_bmp_font_create(p_face, p_size, p_unref), _hb_bmp_font_destroy); +} + +hb_font_t *hb_bmp_font_create(BitmapFontDataAdvanced *p_face, int p_size, hb_destroy_func_t p_destroy) { + hb_font_t *font; + hb_face_t *face = hb_face_create(nullptr, 0); + + font = hb_font_create(face); + hb_face_destroy(face); + _hb_bmp_font_set_funcs(font, p_face, p_size, false); + return font; +} + +/*************************************************************************/ +/* BitmapFontDataAdvanced */ +/*************************************************************************/ + +Error BitmapFontDataAdvanced::load_from_file(const String &p_filename, int p_base_size) { + _THREAD_SAFE_METHOD_ + //fnt format used by angelcode bmfont + //http://www.angelcode.com/products/bmfont/ + + FileAccess *f = FileAccess::open(p_filename, FileAccess::READ); + ERR_FAIL_COND_V_MSG(!f, ERR_FILE_NOT_FOUND, "Can't open font: " + p_filename + "."); + + while (true) { + String line = f->get_line(); + + int delimiter = line.find(" "); + String type = line.substr(0, delimiter); + int pos = delimiter + 1; + Map<String, String> keys; + + while (pos < line.size() && line[pos] == ' ') { + pos++; + } + + while (pos < line.size()) { + int eq = line.find("=", pos); + if (eq == -1) { + break; + } + String key = line.substr(pos, eq - pos); + int end = -1; + String value; + if (line[eq + 1] == '"') { + end = line.find("\"", eq + 2); + if (end == -1) { + break; + } + value = line.substr(eq + 2, end - 1 - eq - 1); + pos = end + 1; + } else { + end = line.find(" ", eq + 1); + if (end == -1) { + end = line.size(); + } + value = line.substr(eq + 1, end - eq); + pos = end; + } + + while (pos < line.size() && line[pos] == ' ') { + pos++; + } + + keys[key] = value; + } + + if (type == "info") { + if (keys.has("size")) { + base_size = keys["size"].to_int(); + } + } else if (type == "common") { + if (keys.has("lineHeight")) { + height = keys["lineHeight"].to_int(); + } + if (keys.has("base")) { + ascent = keys["base"].to_int(); + } + } else if (type == "page") { + if (keys.has("file")) { + String base_dir = p_filename.get_base_dir(); + String file = base_dir.plus_file(keys["file"]); + if (RenderingServer::get_singleton() != nullptr) { + Ref<Texture2D> tex = ResourceLoader::load(file); + if (tex.is_null()) { + ERR_PRINT("Can't load font texture!"); + } else { + ERR_FAIL_COND_V_MSG(tex.is_null(), ERR_FILE_CANT_READ, "It's not a reference to a valid Texture object."); + textures.push_back(tex); + } + } + } + } else if (type == "char") { + Character c; + char32_t idx = 0; + if (keys.has("id")) { + idx = keys["id"].to_int(); + } + if (keys.has("x")) { + c.rect.position.x = keys["x"].to_int(); + } + if (keys.has("y")) { + c.rect.position.y = keys["y"].to_int(); + } + if (keys.has("width")) { + c.rect.size.width = keys["width"].to_int(); + } + if (keys.has("height")) { + c.rect.size.height = keys["height"].to_int(); + } + if (keys.has("xoffset")) { + c.align.x = keys["xoffset"].to_int(); + } + if (keys.has("yoffset")) { + c.align.y = keys["yoffset"].to_int(); + } + if (keys.has("page")) { + c.texture_idx = keys["page"].to_int(); + } + if (keys.has("xadvance")) { + c.advance.x = keys["xadvance"].to_int(); + } + if (keys.has("yadvance")) { + c.advance.x = keys["yadvance"].to_int(); + } + if (c.advance.x < 0) { + c.advance.x = c.rect.size.width + 1; + } + if (c.advance.y < 0) { + c.advance.y = c.rect.size.height + 1; + } + char_map[idx] = c; + } else if (type == "kerning") { + KerningPairKey kpk; + float k = 0; + if (keys.has("first")) { + kpk.A = keys["first"].to_int(); + } + if (keys.has("second")) { + kpk.B = keys["second"].to_int(); + } + if (keys.has("amount")) { + k = keys["amount"].to_int(); + } + kerning_map[kpk] = k; + } + + if (f->eof_reached()) { + break; + } + } + if (base_size == 0) { + base_size = height; + } + + valid = true; + + memdelete(f); + return OK; +} + +Error BitmapFontDataAdvanced::load_from_memory(const uint8_t *p_data, size_t p_size, int p_base_size) { + _THREAD_SAFE_METHOD_ + ERR_FAIL_COND_V(p_data == nullptr, ERR_CANT_CREATE); + ERR_FAIL_COND_V(p_size != sizeof(TextServer::BitmapFontData), ERR_CANT_CREATE); + + const TextServer::BitmapFontData *data = (const TextServer::BitmapFontData *)p_data; + + if (RenderingServer::get_singleton() != nullptr) { + Ref<Image> image = memnew(Image(data->img)); + Ref<ImageTexture> tex = memnew(ImageTexture); + tex->create_from_image(image); + + textures.push_back(tex); + } + + for (int i = 0; i < data->charcount; i++) { + const int *c = &data->char_rects[i * 8]; + + Character chr; + chr.rect.position.x = c[1]; + chr.rect.position.y = c[2]; + chr.rect.size.x = c[3]; + chr.rect.size.y = c[4]; + chr.texture_idx = 0; + if (c[7] < 0) { + chr.advance.x = c[3]; + } else { + chr.advance.x = c[7]; + } + chr.align = Vector2(c[6], c[5]); + char_map[c[0]] = chr; + } + + for (int i = 0; i < data->kerning_count; i++) { + KerningPairKey kpk; + kpk.A = data->kernings[i * 3 + 0]; + kpk.B = data->kernings[i * 3 + 1]; + + if (data->kernings[i * 3 + 2] == 0 && kerning_map.has(kpk)) { + kerning_map.erase(kpk); + } else { + kerning_map[kpk] = data->kernings[i * 3 + 2]; + } + } + + height = data->height; + ascent = data->ascent; + + base_size = p_base_size; + if (base_size == 0) { + base_size = height; + } + + valid = true; + + return OK; +} + +float BitmapFontDataAdvanced::get_height(int p_size) const { + ERR_FAIL_COND_V(!valid, 0.f); + return height * (float(p_size) / float(base_size)); +} + +float BitmapFontDataAdvanced::get_ascent(int p_size) const { + ERR_FAIL_COND_V(!valid, 0.f); + return ascent * (float(p_size) / float(base_size)); +} + +float BitmapFontDataAdvanced::get_descent(int p_size) const { + ERR_FAIL_COND_V(!valid, 0.f); + return (height - ascent) * (float(p_size) / float(base_size)); +} + +float BitmapFontDataAdvanced::get_underline_position(int p_size) const { + ERR_FAIL_COND_V(!valid, 0.f); + return 2 * (float(p_size) / float(base_size)); +} + +float BitmapFontDataAdvanced::get_underline_thickness(int p_size) const { + ERR_FAIL_COND_V(!valid, 0.f); + return 1 * (float(p_size) / float(base_size)); +} + +void BitmapFontDataAdvanced::set_distance_field_hint(bool p_distance_field) { + distance_field_hint = p_distance_field; +} + +bool BitmapFontDataAdvanced::get_distance_field_hint() const { + return distance_field_hint; +} + +float BitmapFontDataAdvanced::get_base_size() const { + return base_size; +} + +hb_font_t *BitmapFontDataAdvanced::get_hb_handle(int p_size) { + _THREAD_SAFE_METHOD_ + ERR_FAIL_COND_V(!valid, nullptr); + if (!cache.has(p_size)) { + cache[p_size] = hb_bmp_font_create(this, p_size, nullptr); + } + return cache[p_size]; +} + +bool BitmapFontDataAdvanced::has_char(char32_t p_char) const { + _THREAD_SAFE_METHOD_ + ERR_FAIL_COND_V(!valid, false); + return char_map.has(p_char); +} + +String BitmapFontDataAdvanced::get_supported_chars() const { + _THREAD_SAFE_METHOD_ + ERR_FAIL_COND_V(!valid, String()); + String chars; + const uint32_t *k = nullptr; + while ((k = char_map.next(k))) { + chars += char32_t(*k); + } + return chars; +} + +Vector2 BitmapFontDataAdvanced::get_advance(uint32_t p_char, int p_size) const { + _THREAD_SAFE_METHOD_ + ERR_FAIL_COND_V(!valid, Vector2()); + const Character *c = char_map.getptr(p_char); + ERR_FAIL_COND_V(c == nullptr, Vector2()); + + return c->advance * (float(p_size) / float(base_size)); +} + +Vector2 BitmapFontDataAdvanced::get_align(uint32_t p_char, int p_size) const { + _THREAD_SAFE_METHOD_ + ERR_FAIL_COND_V(!valid, Vector2()); + const Character *c = char_map.getptr(p_char); + ERR_FAIL_COND_V(c == nullptr, Vector2()); + + return c->align * (float(p_size) / float(base_size)); +} + +Vector2 BitmapFontDataAdvanced::get_size(uint32_t p_char, int p_size) const { + _THREAD_SAFE_METHOD_ + ERR_FAIL_COND_V(!valid, Vector2()); + const Character *c = char_map.getptr(p_char); + ERR_FAIL_COND_V(c == nullptr, Vector2()); + + return c->rect.size * (float(p_size) / float(base_size)); +} + +Vector2 BitmapFontDataAdvanced::get_kerning(uint32_t p_char, uint32_t p_next, int p_size) const { + _THREAD_SAFE_METHOD_ + ERR_FAIL_COND_V(!valid, Vector2()); + KerningPairKey kpk; + kpk.A = p_char; + kpk.B = p_next; + + const Map<KerningPairKey, int>::Element *E = kerning_map.find(kpk); + if (E) { + return Vector2(-E->get() * (float(p_size) / float(base_size)), 0.f); + } else { + return Vector2(); + } +} + +Vector2 BitmapFontDataAdvanced::draw_glyph(RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const { + _THREAD_SAFE_METHOD_ + if (p_index == 0) { + return Vector2(); + } + ERR_FAIL_COND_V(!valid, Vector2()); + const Character *c = char_map.getptr(p_index); + + ERR_FAIL_COND_V(c == nullptr, Vector2()); + ERR_FAIL_COND_V(c->texture_idx < -1 || c->texture_idx >= textures.size(), Vector2()); + if (c->texture_idx != -1) { + Point2 cpos = p_pos; + cpos += c->align * (float(p_size) / float(base_size)); + cpos.y -= ascent * (float(p_size) / float(base_size)); + if (RenderingServer::get_singleton() != nullptr) { + //if (distance_field_hint) { // Not implemented. + // RenderingServer::get_singleton()->canvas_item_set_distance_field_mode(p_canvas, true); + //} + RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, Rect2(cpos, c->rect.size * (float(p_size) / float(base_size))), textures[c->texture_idx]->get_rid(), c->rect, p_color, false, false); + //if (distance_field_hint) { + // RenderingServer::get_singleton()->canvas_item_set_distance_field_mode(p_canvas, false); + //} + } + } + + return c->advance * (float(p_size) / float(base_size)); +} + +Vector2 BitmapFontDataAdvanced::draw_glyph_outline(RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const { + _THREAD_SAFE_METHOD_ + if (p_index == 0) { + return Vector2(); + } + ERR_FAIL_COND_V(!valid, Vector2()); + const Character *c = char_map.getptr(p_index); + + ERR_FAIL_COND_V(c == nullptr, Vector2()); + ERR_FAIL_COND_V(c->texture_idx < -1 || c->texture_idx >= textures.size(), Vector2()); + + // Not supported, return advance for compatibility. + + return c->advance * (float(p_size) / float(base_size)); +} + +BitmapFontDataAdvanced::~BitmapFontDataAdvanced() { + for (Map<float, hb_font_t *>::Element *E = cache.front(); E; E = E->next()) { + hb_font_destroy(E->get()); + } +} diff --git a/modules/text_server_adv/bitmap_font_adv.h b/modules/text_server_adv/bitmap_font_adv.h new file mode 100644 index 0000000000..b2fe7f43af --- /dev/null +++ b/modules/text_server_adv/bitmap_font_adv.h @@ -0,0 +1,115 @@ +/*************************************************************************/ +/* bitmap_font_adv.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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. */ +/*************************************************************************/ + +#ifndef BITMAP_FONT_ADV_H +#define BITMAP_FONT_ADV_H + +#include "font_adv.h" + +struct BitmapFontDataAdvanced : public FontDataAdvanced { + _THREAD_SAFE_CLASS_ + +private: + Vector<Ref<Texture2D>> textures; + + struct Character { + int texture_idx = 0; + Rect2 rect; + Vector2 align; + Vector2 advance = Vector2(-1, -1); + }; + + struct KerningPairKey { + union { + struct { + uint32_t A, B; + }; + + uint64_t pair = 0; + }; + + _FORCE_INLINE_ bool operator<(const KerningPairKey &p_r) const { return pair < p_r.pair; } + }; + + HashMap<uint32_t, Character> char_map; + Map<KerningPairKey, int> kerning_map; + Map<float, hb_font_t *> cache; + + float height = 0.f; + float ascent = 0.f; + float base_size = 0.f; + bool distance_field_hint = false; + +public: + virtual void clear_cache() override{}; + + virtual Error load_from_file(const String &p_filename, int p_base_size) override; + virtual Error load_from_memory(const uint8_t *p_data, size_t p_size, int p_base_size) override; + + virtual float get_height(int p_size) const override; + virtual float get_ascent(int p_size) const override; + virtual float get_descent(int p_size) const override; + + virtual float get_underline_position(int p_size) const override; + virtual float get_underline_thickness(int p_size) const override; + + virtual void set_antialiased(bool p_antialiased) override{}; + virtual bool get_antialiased() const override { return false; }; + + virtual void set_hinting(TextServer::Hinting p_hinting) override{}; + virtual TextServer::Hinting get_hinting() const override { return TextServer::HINTING_NONE; }; + + virtual void set_distance_field_hint(bool p_distance_field) override; + virtual bool get_distance_field_hint() const override; + + virtual void set_force_autohinter(bool p_enabeld) override{}; + virtual bool get_force_autohinter() const override { return false; }; + + virtual bool has_outline() const override { return false; }; + virtual float get_base_size() const override; + + virtual hb_font_t *get_hb_handle(int p_size) override; + + virtual bool has_char(char32_t p_char) const override; + virtual String get_supported_chars() const override; + + virtual Vector2 get_advance(uint32_t p_char, int p_size) const override; + Vector2 get_align(uint32_t p_char, int p_size) const; + Vector2 get_size(uint32_t p_char, int p_size) const; + virtual Vector2 get_kerning(uint32_t p_char, uint32_t p_next, int p_size) const override; + virtual uint32_t get_glyph_index(char32_t p_char, char32_t p_variation_selector) const override { return (uint32_t)p_char; }; + + virtual Vector2 draw_glyph(RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const override; + virtual Vector2 draw_glyph_outline(RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const override; + + virtual ~BitmapFontDataAdvanced(); +}; + +#endif // BITMAP_FONT_ADV_H diff --git a/modules/text_server_adv/config.py b/modules/text_server_adv/config.py new file mode 100644 index 0000000000..22482fce24 --- /dev/null +++ b/modules/text_server_adv/config.py @@ -0,0 +1,6 @@ +def can_build(env, platform): + return env.module_check_dependencies("text_server_adv", ["freetype"]) + + +def configure(env): + pass diff --git a/modules/text_server_adv/dynamic_font_adv.cpp b/modules/text_server_adv/dynamic_font_adv.cpp new file mode 100644 index 0000000000..90e5cc8831 --- /dev/null +++ b/modules/text_server_adv/dynamic_font_adv.cpp @@ -0,0 +1,973 @@ +/*************************************************************************/ +/* dynamic_font_adv.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 "dynamic_font_adv.h" + +#include FT_STROKER_H +#include FT_ADVANCES_H + +HashMap<String, Vector<uint8_t>> DynamicFontDataAdvanced::font_mem_cache; + +DynamicFontDataAdvanced::DataAtSize *DynamicFontDataAdvanced::get_data_for_size(int p_size, int p_outline_size) { + ERR_FAIL_COND_V(!valid, nullptr); + ERR_FAIL_COND_V(p_size < 0 || p_size > UINT16_MAX, nullptr); + ERR_FAIL_COND_V(p_outline_size < 0 || p_outline_size > UINT16_MAX, nullptr); + + CacheID id; + id.size = p_size; + id.outline_size = p_outline_size; + + DataAtSize *fds = nullptr; + Map<CacheID, DataAtSize *>::Element *E = nullptr; + if (p_outline_size != 0) { + E = size_cache_outline.find(id); + } else { + E = size_cache.find(id); + } + + if (E != nullptr) { + fds = E->get(); + } else { + // FT_OPEN_STREAM is extremely slow only on Android. + if (OS::get_singleton()->get_name() == "Android" && font_mem == nullptr && font_path != String()) { + if (font_mem_cache.has(font_path)) { + font_mem = font_mem_cache[font_path].ptr(); + font_mem_size = font_mem_cache[font_path].size(); + } else { + FileAccess *f = FileAccess::open(font_path, FileAccess::READ); + if (!f) { + ERR_FAIL_V_MSG(nullptr, "Cannot open font file '" + font_path + "'."); + } + + size_t len = f->get_len(); + font_mem_cache[font_path] = Vector<uint8_t>(); + Vector<uint8_t> &fontdata = font_mem_cache[font_path]; + fontdata.resize(len); + f->get_buffer(fontdata.ptrw(), len); + font_mem = fontdata.ptr(); + font_mem_size = len; + f->close(); + } + } + + int error = 0; + fds = memnew(DataAtSize); + if (font_mem == nullptr && font_path != String()) { + FileAccess *f = FileAccess::open(font_path, FileAccess::READ); + if (!f) { + memdelete(fds); + ERR_FAIL_V_MSG(nullptr, "Cannot open font file '" + font_path + "'."); + } + + memset(&fds->stream, 0, sizeof(FT_StreamRec)); + fds->stream.base = nullptr; + fds->stream.size = f->get_len(); + fds->stream.pos = 0; + fds->stream.descriptor.pointer = f; + fds->stream.read = _ft_stream_io; + fds->stream.close = _ft_stream_close; + + FT_Open_Args fargs; + memset(&fargs, 0, sizeof(FT_Open_Args)); + fargs.flags = FT_OPEN_STREAM; + fargs.stream = &fds->stream; + error = FT_Open_Face(library, &fargs, 0, &fds->face); + } else if (font_mem) { + memset(&fds->stream, 0, sizeof(FT_StreamRec)); + fds->stream.base = (unsigned char *)font_mem; + fds->stream.size = font_mem_size; + fds->stream.pos = 0; + + FT_Open_Args fargs; + memset(&fargs, 0, sizeof(FT_Open_Args)); + fargs.memory_base = (unsigned char *)font_mem; + fargs.memory_size = font_mem_size; + fargs.flags = FT_OPEN_MEMORY; + fargs.stream = &fds->stream; + error = FT_Open_Face(library, &fargs, 0, &fds->face); + + } else { + memdelete(fds); + ERR_FAIL_V_MSG(nullptr, "DynamicFont uninitialized."); + } + + if (error == FT_Err_Unknown_File_Format) { + memdelete(fds); + ERR_FAIL_V_MSG(nullptr, "Unknown font format."); + } else if (error) { + memdelete(fds); + ERR_FAIL_V_MSG(nullptr, "Error loading font."); + } + + oversampling = TS->font_get_oversampling(); + + if (FT_HAS_COLOR(fds->face) && fds->face->num_fixed_sizes > 0) { + int best_match = 0; + int diff = ABS(p_size - ((int64_t)fds->face->available_sizes[0].width)); + fds->scale_color_font = float(p_size * oversampling) / fds->face->available_sizes[0].width; + for (int i = 1; i < fds->face->num_fixed_sizes; i++) { + int ndiff = ABS(p_size - ((int64_t)fds->face->available_sizes[i].width)); + if (ndiff < diff) { + best_match = i; + diff = ndiff; + fds->scale_color_font = float(p_size * oversampling) / fds->face->available_sizes[i].width; + } + } + FT_Select_Size(fds->face, best_match); + } else { + FT_Set_Pixel_Sizes(fds->face, 0, p_size * oversampling); + } + + fds->size = p_size; + fds->ascent = (fds->face->size->metrics.ascender / 64.0) / oversampling * fds->scale_color_font; + fds->descent = (-fds->face->size->metrics.descender / 64.0) / oversampling * fds->scale_color_font; + fds->underline_position = -fds->face->underline_position / 64.0 / oversampling * fds->scale_color_font; + fds->underline_thickness = fds->face->underline_thickness / 64.0 / oversampling * fds->scale_color_font; + + //Load os2 TTF pable + fds->os2 = (TT_OS2 *)FT_Get_Sfnt_Table(fds->face, FT_SFNT_OS2); + + fds->hb_handle = hb_ft_font_create(fds->face, nullptr); + if (fds->hb_handle == nullptr) { + memdelete(fds); + ERR_FAIL_V_MSG(nullptr, "Error loading HB font."); + } + if (p_outline_size != 0) { + size_cache_outline[id] = fds; + } else { + size_cache[id] = fds; + } + } + + return fds; +} + +unsigned long DynamicFontDataAdvanced::_ft_stream_io(FT_Stream stream, unsigned long offset, unsigned char *buffer, unsigned long count) { + FileAccess *f = (FileAccess *)stream->descriptor.pointer; + + if (f->get_position() != offset) { + f->seek(offset); + } + if (count == 0) { + return 0; + } + + return f->get_buffer(buffer, count); +} + +void DynamicFontDataAdvanced::_ft_stream_close(FT_Stream stream) { + FileAccess *f = (FileAccess *)stream->descriptor.pointer; + f->close(); + memdelete(f); +} + +Dictionary DynamicFontDataAdvanced::get_feature_list() const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(base_size); + if (fds == nullptr) { + return Dictionary(); + } + + Dictionary out; + // Read feature flags. + unsigned int count = hb_ot_layout_table_get_feature_tags(hb_font_get_face(fds->hb_handle), HB_OT_TAG_GSUB, 0, NULL, NULL); + if (count != 0) { + hb_tag_t *feature_tags = (hb_tag_t *)memalloc(count * sizeof(hb_tag_t)); + hb_ot_layout_table_get_feature_tags(hb_font_get_face(fds->hb_handle), HB_OT_TAG_GSUB, 0, &count, feature_tags); + for (unsigned int i = 0; i < count; i++) { + out[feature_tags[i]] = 1; + } + memfree(feature_tags); + } + count = hb_ot_layout_table_get_feature_tags(hb_font_get_face(fds->hb_handle), HB_OT_TAG_GPOS, 0, NULL, NULL); + if (count != 0) { + hb_tag_t *feature_tags = (hb_tag_t *)memalloc(count * sizeof(hb_tag_t)); + hb_ot_layout_table_get_feature_tags(hb_font_get_face(fds->hb_handle), HB_OT_TAG_GPOS, 0, &count, feature_tags); + for (unsigned int i = 0; i < count; i++) { + out[feature_tags[i]] = 1; + } + memfree(feature_tags); + } + + return out; +} + +DynamicFontDataAdvanced::TexturePosition DynamicFontDataAdvanced::find_texture_pos_for_glyph(DynamicFontDataAdvanced::DataAtSize *p_data, int p_color_size, Image::Format p_image_format, int p_width, int p_height) { + TexturePosition ret; + ret.index = -1; + ret.x = 0; + ret.y = 0; + + int mw = p_width; + int mh = p_height; + + for (int i = 0; i < p_data->textures.size(); i++) { + const CharTexture &ct = p_data->textures[i]; + + if (RenderingServer::get_singleton() != nullptr) { + if (ct.texture->get_format() != p_image_format) { + continue; + } + } + + if (mw > ct.texture_size || mh > ct.texture_size) { //too big for this texture + continue; + } + + ret.y = 0x7FFFFFFF; + ret.x = 0; + + for (int j = 0; j < ct.texture_size - mw; j++) { + int max_y = 0; + + for (int k = j; k < j + mw; k++) { + int y = ct.offsets[k]; + if (y > max_y) { + max_y = y; + } + } + + if (max_y < ret.y) { + ret.y = max_y; + ret.x = j; + } + } + + if (ret.y == 0x7FFFFFFF || ret.y + mh > ct.texture_size) { + continue; //fail, could not fit it here + } + + ret.index = i; + break; + } + + if (ret.index == -1) { + //could not find texture to fit, create one + ret.x = 0; + ret.y = 0; + + int texsize = MAX(p_data->size * oversampling * 8, 256); + if (mw > texsize) { + texsize = mw; //special case, adapt to it? + } + if (mh > texsize) { + texsize = mh; //special case, adapt to it? + } + + texsize = next_power_of_2(texsize); + + texsize = MIN(texsize, 4096); + + CharTexture tex; + tex.texture_size = texsize; + tex.imgdata.resize(texsize * texsize * p_color_size); //grayscale alpha + + { + //zero texture + uint8_t *w = tex.imgdata.ptrw(); + ERR_FAIL_COND_V(texsize * texsize * p_color_size > tex.imgdata.size(), ret); + // Initialize the texture to all-white pixels to prevent artifacts when the + // font is displayed at a non-default scale with filtering enabled. + if (p_color_size == 2) { + for (int i = 0; i < texsize * texsize * p_color_size; i += 2) { // FORMAT_LA8 + w[i + 0] = 255; + w[i + 1] = 0; + } + } else if (p_color_size == 4) { + for (int i = 0; i < texsize * texsize * p_color_size; i += 4) { // FORMAT_RGBA8 + w[i + 0] = 255; + w[i + 1] = 255; + w[i + 2] = 255; + w[i + 3] = 0; + } + } else { + ERR_FAIL_V(ret); + } + } + tex.offsets.resize(texsize); + for (int i = 0; i < texsize; i++) { //zero offsets + tex.offsets.write[i] = 0; + } + + p_data->textures.push_back(tex); + ret.index = p_data->textures.size() - 1; + } + + return ret; +} + +DynamicFontDataAdvanced::Character DynamicFontDataAdvanced::Character::not_found() { + Character ch; + return ch; +} + +DynamicFontDataAdvanced::Character DynamicFontDataAdvanced::bitmap_to_character(DynamicFontDataAdvanced::DataAtSize *p_data, FT_Bitmap bitmap, int yofs, int xofs, const Vector2 &advance) { + int w = bitmap.width; + int h = bitmap.rows; + + int mw = w + rect_margin * 2; + int mh = h + rect_margin * 2; + + ERR_FAIL_COND_V(mw > 4096, Character::not_found()); + ERR_FAIL_COND_V(mh > 4096, Character::not_found()); + + int color_size = bitmap.pixel_mode == FT_PIXEL_MODE_BGRA ? 4 : 2; + Image::Format require_format = color_size == 4 ? Image::FORMAT_RGBA8 : Image::FORMAT_LA8; + + TexturePosition tex_pos = find_texture_pos_for_glyph(p_data, color_size, require_format, mw, mh); + ERR_FAIL_COND_V(tex_pos.index < 0, Character::not_found()); + + //fit character in char texture + + CharTexture &tex = p_data->textures.write[tex_pos.index]; + + { + uint8_t *wr = tex.imgdata.ptrw(); + + for (int i = 0; i < h; i++) { + for (int j = 0; j < w; j++) { + int ofs = ((i + tex_pos.y + rect_margin) * tex.texture_size + j + tex_pos.x + rect_margin) * color_size; + ERR_FAIL_COND_V(ofs >= tex.imgdata.size(), Character::not_found()); + switch (bitmap.pixel_mode) { + case FT_PIXEL_MODE_MONO: { + int byte = i * bitmap.pitch + (j >> 3); + int bit = 1 << (7 - (j % 8)); + wr[ofs + 0] = 255; //grayscale as 1 + wr[ofs + 1] = (bitmap.buffer[byte] & bit) ? 255 : 0; + } break; + case FT_PIXEL_MODE_GRAY: + wr[ofs + 0] = 255; //grayscale as 1 + wr[ofs + 1] = bitmap.buffer[i * bitmap.pitch + j]; + break; + case FT_PIXEL_MODE_BGRA: { + int ofs_color = i * bitmap.pitch + (j << 2); + wr[ofs + 2] = bitmap.buffer[ofs_color + 0]; + wr[ofs + 1] = bitmap.buffer[ofs_color + 1]; + wr[ofs + 0] = bitmap.buffer[ofs_color + 2]; + wr[ofs + 3] = bitmap.buffer[ofs_color + 3]; + } break; + // TODO: FT_PIXEL_MODE_LCD + default: + ERR_FAIL_V_MSG(Character::not_found(), "Font uses unsupported pixel format: " + itos(bitmap.pixel_mode) + "."); + break; + } + } + } + } + + //blit to image and texture + { + if (RenderingServer::get_singleton() != nullptr) { + Ref<Image> img = memnew(Image(tex.texture_size, tex.texture_size, 0, require_format, tex.imgdata)); + + if (tex.texture.is_null()) { + tex.texture.instance(); + tex.texture->create_from_image(img); + } else { + tex.texture->update(img); //update + } + } + } + + // update height array + for (int k = tex_pos.x; k < tex_pos.x + mw; k++) { + tex.offsets.write[k] = tex_pos.y + mh; + } + + Character chr; + chr.align = Vector2(xofs, -yofs) * p_data->scale_color_font / oversampling; + chr.advance = advance * p_data->scale_color_font / oversampling; + chr.texture_idx = tex_pos.index; + chr.found = true; + + chr.rect_uv = Rect2(tex_pos.x + rect_margin, tex_pos.y + rect_margin, w, h); + chr.rect = chr.rect_uv; + chr.rect.position /= oversampling; + chr.rect.size *= (p_data->scale_color_font / oversampling); + return chr; +} + +void DynamicFontDataAdvanced::update_glyph(int p_size, uint32_t p_index) { + DataAtSize *fds = get_data_for_size(p_size, false); + ERR_FAIL_COND(fds == nullptr); + + if (fds->glyph_map.has(p_index)) { + return; + } + + Character character = Character::not_found(); + FT_GlyphSlot slot = fds->face->glyph; + + if (p_index == 0) { + fds->glyph_map[p_index] = character; + return; + } + + int ft_hinting; + switch (hinting) { + case TextServer::HINTING_NONE: + ft_hinting = FT_LOAD_NO_HINTING; + break; + case TextServer::HINTING_LIGHT: + ft_hinting = FT_LOAD_TARGET_LIGHT; + break; + default: + ft_hinting = FT_LOAD_TARGET_NORMAL; + break; + } + + FT_Fixed v, h; + FT_Get_Advance(fds->face, p_index, FT_HAS_COLOR(fds->face) ? FT_LOAD_COLOR : FT_LOAD_DEFAULT | (force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0) | ft_hinting, &h); + FT_Get_Advance(fds->face, p_index, FT_HAS_COLOR(fds->face) ? FT_LOAD_COLOR : FT_LOAD_DEFAULT | (force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0) | ft_hinting | FT_LOAD_VERTICAL_LAYOUT, &v); + + int error = FT_Load_Glyph(fds->face, p_index, FT_HAS_COLOR(fds->face) ? FT_LOAD_COLOR : FT_LOAD_DEFAULT | (force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0) | ft_hinting); + if (error) { + fds->glyph_map[p_index] = character; + return; + } + + error = FT_Render_Glyph(fds->face->glyph, antialiased ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO); + if (!error) { + character = bitmap_to_character(fds, slot->bitmap, slot->bitmap_top, slot->bitmap_left, Vector2((h + (1 << 9)) >> 10, (v + (1 << 9)) >> 10) / 64.0); + } + + fds->glyph_map[p_index] = character; +} + +void DynamicFontDataAdvanced::update_glyph_outline(int p_size, int p_outline_size, uint32_t p_index) { + DataAtSize *fds = get_data_for_size(p_size, p_outline_size); + ERR_FAIL_COND(fds == nullptr); + + if (fds->glyph_map.has(p_index)) { + return; + } + + Character character = Character::not_found(); + if (p_index == 0) { + fds->glyph_map[p_index] = character; + return; + } + + int error = FT_Load_Glyph(fds->face, p_index, FT_LOAD_NO_BITMAP | (force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0)); + if (error) { + fds->glyph_map[p_index] = character; + return; + } + + FT_Stroker stroker; + if (FT_Stroker_New(library, &stroker) != 0) { + fds->glyph_map[p_index] = character; + return; + } + + FT_Stroker_Set(stroker, (int)(p_outline_size * oversampling * 64.0), FT_STROKER_LINECAP_BUTT, FT_STROKER_LINEJOIN_ROUND, 0); + FT_Glyph glyph; + FT_BitmapGlyph glyph_bitmap; + + if (FT_Get_Glyph(fds->face->glyph, &glyph) != 0) { + goto cleanup_stroker; + } + if (FT_Glyph_Stroke(&glyph, stroker, 1) != 0) { + goto cleanup_glyph; + } + if (FT_Glyph_To_Bitmap(&glyph, antialiased ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO, nullptr, 1) != 0) { + goto cleanup_glyph; + } + + glyph_bitmap = (FT_BitmapGlyph)glyph; + character = bitmap_to_character(fds, glyph_bitmap->bitmap, glyph_bitmap->top, glyph_bitmap->left, Vector2()); + +cleanup_glyph: + FT_Done_Glyph(glyph); +cleanup_stroker: + FT_Stroker_Done(stroker); + + fds->glyph_map[p_index] = character; +} + +void DynamicFontDataAdvanced::clear_cache() { + _THREAD_SAFE_METHOD_ + for (Map<CacheID, DataAtSize *>::Element *E = size_cache.front(); E; E = E->next()) { + memdelete(E->get()); + } + size_cache.clear(); + for (Map<CacheID, DataAtSize *>::Element *E = size_cache_outline.front(); E; E = E->next()) { + memdelete(E->get()); + } + size_cache_outline.clear(); +} + +Error DynamicFontDataAdvanced::load_from_file(const String &p_filename, int p_base_size) { + _THREAD_SAFE_METHOD_ + if (library == nullptr) { + int error = FT_Init_FreeType(&library); + ERR_FAIL_COND_V_MSG(error != 0, ERR_CANT_CREATE, "Error initializing FreeType."); + } + clear_cache(); + + font_path = p_filename; + base_size = p_base_size; + + valid = true; + DataAtSize *fds = get_data_for_size(base_size); // load base size. + if (fds == nullptr) { + valid = false; + ERR_FAIL_V(ERR_CANT_CREATE); + } + + return OK; +} + +Error DynamicFontDataAdvanced::load_from_memory(const uint8_t *p_data, size_t p_size, int p_base_size) { + _THREAD_SAFE_METHOD_ + if (library == nullptr) { + int error = FT_Init_FreeType(&library); + ERR_FAIL_COND_V_MSG(error != 0, ERR_CANT_CREATE, "Error initializing FreeType."); + } + clear_cache(); + + font_mem = p_data; + font_mem_size = p_size; + base_size = p_base_size; + + valid = true; + DataAtSize *fds = get_data_for_size(base_size); // load base size. + if (fds == nullptr) { + valid = false; + ERR_FAIL_V(ERR_CANT_CREATE); + } + + return OK; +} + +float DynamicFontDataAdvanced::get_height(int p_size) const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(p_size); + ERR_FAIL_COND_V(fds == nullptr, 0.f); + return fds->ascent + fds->descent; +} + +float DynamicFontDataAdvanced::get_ascent(int p_size) const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(p_size); + ERR_FAIL_COND_V(fds == nullptr, 0.f); + return fds->ascent; +} + +float DynamicFontDataAdvanced::get_descent(int p_size) const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(p_size); + ERR_FAIL_COND_V(fds == nullptr, 0.f); + return fds->descent; +} + +float DynamicFontDataAdvanced::get_underline_position(int p_size) const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(p_size); + ERR_FAIL_COND_V(fds == nullptr, 0.f); + return fds->underline_position; +} + +float DynamicFontDataAdvanced::get_underline_thickness(int p_size) const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(p_size); + ERR_FAIL_COND_V(fds == nullptr, 0.f); + return fds->underline_thickness; +} + +bool DynamicFontDataAdvanced::is_script_supported(uint32_t p_script) const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(base_size); + ERR_FAIL_COND_V(fds == nullptr, false); + + unsigned int count = hb_ot_layout_table_get_script_tags(hb_font_get_face(fds->hb_handle), HB_OT_TAG_GSUB, 0, NULL, NULL); + if (count != 0) { + hb_tag_t *script_tags = (hb_tag_t *)memalloc(count * sizeof(hb_tag_t)); + hb_ot_layout_table_get_script_tags(hb_font_get_face(fds->hb_handle), HB_OT_TAG_GSUB, 0, &count, script_tags); + for (unsigned int i = 0; i < count; i++) { + if (p_script == script_tags[i]) { + memfree(script_tags); + return true; + } + } + memfree(script_tags); + } + count = hb_ot_layout_table_get_script_tags(hb_font_get_face(fds->hb_handle), HB_OT_TAG_GPOS, 0, NULL, NULL); + if (count != 0) { + hb_tag_t *script_tags = (hb_tag_t *)memalloc(count * sizeof(hb_tag_t)); + hb_ot_layout_table_get_script_tags(hb_font_get_face(fds->hb_handle), HB_OT_TAG_GPOS, 0, &count, script_tags); + for (unsigned int i = 0; i < count; i++) { + if (p_script == script_tags[i]) { + memfree(script_tags); + return true; + } + } + memfree(script_tags); + } + + if (!fds->os2) { + return false; + } + + switch (p_script) { + case HB_SCRIPT_COMMON: + return (fds->os2->ulUnicodeRange1 & 1L << 4) || (fds->os2->ulUnicodeRange1 & 1L << 5) || (fds->os2->ulUnicodeRange1 & 1L << 6) || (fds->os2->ulUnicodeRange1 & 1L << 31) || (fds->os2->ulUnicodeRange2 & 1L << 0) || (fds->os2->ulUnicodeRange2 & 1L << 1) || (fds->os2->ulUnicodeRange2 & 1L << 2) || (fds->os2->ulUnicodeRange2 & 1L << 3) || (fds->os2->ulUnicodeRange2 & 1L << 4) || (fds->os2->ulUnicodeRange2 & 1L << 5) || (fds->os2->ulUnicodeRange2 & 1L << 6) || (fds->os2->ulUnicodeRange2 & 1L << 7) || (fds->os2->ulUnicodeRange2 & 1L << 8) || (fds->os2->ulUnicodeRange2 & 1L << 9) || (fds->os2->ulUnicodeRange2 & 1L << 10) || (fds->os2->ulUnicodeRange2 & 1L << 11) || (fds->os2->ulUnicodeRange2 & 1L << 12) || (fds->os2->ulUnicodeRange2 & 1L << 13) || (fds->os2->ulUnicodeRange2 & 1L << 14) || (fds->os2->ulUnicodeRange2 & 1L << 15) || (fds->os2->ulUnicodeRange2 & 1L << 30) || (fds->os2->ulUnicodeRange3 & 1L << 0) || (fds->os2->ulUnicodeRange3 & 1L << 1) || (fds->os2->ulUnicodeRange3 & 1L << 2) || (fds->os2->ulUnicodeRange3 & 1L << 4) || (fds->os2->ulUnicodeRange3 & 1L << 5) || (fds->os2->ulUnicodeRange3 & 1L << 18) || (fds->os2->ulUnicodeRange3 & 1L << 24) || (fds->os2->ulUnicodeRange3 & 1L << 25) || (fds->os2->ulUnicodeRange3 & 1L << 26) || (fds->os2->ulUnicodeRange3 & 1L << 27) || (fds->os2->ulUnicodeRange3 & 1L << 28) || (fds->os2->ulUnicodeRange4 & 1L << 3) || (fds->os2->ulUnicodeRange4 & 1L << 6) || (fds->os2->ulUnicodeRange4 & 1L << 15) || (fds->os2->ulUnicodeRange4 & 1L << 23) || (fds->os2->ulUnicodeRange4 & 1L << 24) || (fds->os2->ulUnicodeRange4 & 1L << 26); + case HB_SCRIPT_LATIN: + return (fds->os2->ulUnicodeRange1 & 1L << 0) || (fds->os2->ulUnicodeRange1 & 1L << 1) || (fds->os2->ulUnicodeRange1 & 1L << 2) || (fds->os2->ulUnicodeRange1 & 1L << 3) || (fds->os2->ulUnicodeRange1 & 1L << 29); + case HB_SCRIPT_GREEK: + return (fds->os2->ulUnicodeRange1 & 1L << 7) || (fds->os2->ulUnicodeRange1 & 1L << 30); + case HB_SCRIPT_COPTIC: + return (fds->os2->ulUnicodeRange1 & 1L << 8); + case HB_SCRIPT_CYRILLIC: + return (fds->os2->ulUnicodeRange1 & 1L << 9); + case HB_SCRIPT_ARMENIAN: + return (fds->os2->ulUnicodeRange1 & 1L << 10); + case HB_SCRIPT_HEBREW: + return (fds->os2->ulUnicodeRange1 & 1L << 11); + case HB_SCRIPT_VAI: + return (fds->os2->ulUnicodeRange1 & 1L << 12); + case HB_SCRIPT_ARABIC: + return (fds->os2->ulUnicodeRange1 & 1L << 13) || (fds->os2->ulUnicodeRange2 & 1L << 31) || (fds->os2->ulUnicodeRange3 & 1L << 3); + case HB_SCRIPT_NKO: + return (fds->os2->ulUnicodeRange1 & 1L << 14); + case HB_SCRIPT_DEVANAGARI: + return (fds->os2->ulUnicodeRange1 & 1L << 15); + case HB_SCRIPT_BENGALI: + return (fds->os2->ulUnicodeRange1 & 1L << 16); + case HB_SCRIPT_GURMUKHI: + return (fds->os2->ulUnicodeRange1 & 1L << 17); + case HB_SCRIPT_GUJARATI: + return (fds->os2->ulUnicodeRange1 & 1L << 18); + case HB_SCRIPT_ORIYA: + return (fds->os2->ulUnicodeRange1 & 1L << 19); + case HB_SCRIPT_TAMIL: + return (fds->os2->ulUnicodeRange1 & 1L << 20); + case HB_SCRIPT_TELUGU: + return (fds->os2->ulUnicodeRange1 & 1L << 21); + case HB_SCRIPT_KANNADA: + return (fds->os2->ulUnicodeRange1 & 1L << 22); + case HB_SCRIPT_MALAYALAM: + return (fds->os2->ulUnicodeRange1 & 1L << 23); + case HB_SCRIPT_THAI: + return (fds->os2->ulUnicodeRange1 & 1L << 24); + case HB_SCRIPT_LAO: + return (fds->os2->ulUnicodeRange1 & 1L << 25); + case HB_SCRIPT_GEORGIAN: + return (fds->os2->ulUnicodeRange1 & 1L << 26); + case HB_SCRIPT_BALINESE: + return (fds->os2->ulUnicodeRange1 & 1L << 27); + case HB_SCRIPT_HANGUL: + return (fds->os2->ulUnicodeRange1 & 1L << 28) || (fds->os2->ulUnicodeRange2 & 1L << 20) || (fds->os2->ulUnicodeRange2 & 1L << 24); + case HB_SCRIPT_HAN: + return (fds->os2->ulUnicodeRange2 & 1L << 21) || (fds->os2->ulUnicodeRange2 & 1L << 22) || (fds->os2->ulUnicodeRange2 & 1L << 23) || (fds->os2->ulUnicodeRange2 & 1L << 26) || (fds->os2->ulUnicodeRange2 & 1L << 27) || (fds->os2->ulUnicodeRange2 & 1L << 29); + case HB_SCRIPT_HIRAGANA: + return (fds->os2->ulUnicodeRange2 & 1L << 17); + case HB_SCRIPT_KATAKANA: + return (fds->os2->ulUnicodeRange2 & 1L << 18); + case HB_SCRIPT_BOPOMOFO: + return (fds->os2->ulUnicodeRange2 & 1L << 19); + case HB_SCRIPT_TIBETAN: + return (fds->os2->ulUnicodeRange3 & 1L << 6); + case HB_SCRIPT_SYRIAC: + return (fds->os2->ulUnicodeRange3 & 1L << 7); + case HB_SCRIPT_THAANA: + return (fds->os2->ulUnicodeRange3 & 1L << 8); + case HB_SCRIPT_SINHALA: + return (fds->os2->ulUnicodeRange3 & 1L << 9); + case HB_SCRIPT_MYANMAR: + return (fds->os2->ulUnicodeRange3 & 1L << 10); + case HB_SCRIPT_ETHIOPIC: + return (fds->os2->ulUnicodeRange3 & 1L << 11); + case HB_SCRIPT_CHEROKEE: + return (fds->os2->ulUnicodeRange3 & 1L << 12); + case HB_SCRIPT_CANADIAN_SYLLABICS: + return (fds->os2->ulUnicodeRange3 & 1L << 13); + case HB_SCRIPT_OGHAM: + return (fds->os2->ulUnicodeRange3 & 1L << 14); + case HB_SCRIPT_RUNIC: + return (fds->os2->ulUnicodeRange3 & 1L << 15); + case HB_SCRIPT_KHMER: + return (fds->os2->ulUnicodeRange3 & 1L << 16); + case HB_SCRIPT_MONGOLIAN: + return (fds->os2->ulUnicodeRange3 & 1L << 17); + case HB_SCRIPT_YI: + return (fds->os2->ulUnicodeRange3 & 1L << 19); + case HB_SCRIPT_HANUNOO: + case HB_SCRIPT_TAGBANWA: + case HB_SCRIPT_BUHID: + case HB_SCRIPT_TAGALOG: + return (fds->os2->ulUnicodeRange3 & 1L << 20); + case HB_SCRIPT_OLD_ITALIC: + return (fds->os2->ulUnicodeRange3 & 1L << 21); + case HB_SCRIPT_GOTHIC: + return (fds->os2->ulUnicodeRange3 & 1L << 22); + case HB_SCRIPT_DESERET: + return (fds->os2->ulUnicodeRange3 & 1L << 23); + case HB_SCRIPT_LIMBU: + return (fds->os2->ulUnicodeRange3 & 1L << 29); + case HB_SCRIPT_TAI_LE: + return (fds->os2->ulUnicodeRange3 & 1L << 30); + case HB_SCRIPT_NEW_TAI_LUE: + return (fds->os2->ulUnicodeRange3 & 1L << 31); + case HB_SCRIPT_BUGINESE: + return (fds->os2->ulUnicodeRange4 & 1L << 0); + case HB_SCRIPT_GLAGOLITIC: + return (fds->os2->ulUnicodeRange4 & 1L << 1); + case HB_SCRIPT_TIFINAGH: + return (fds->os2->ulUnicodeRange4 & 1L << 2); + case HB_SCRIPT_SYLOTI_NAGRI: + return (fds->os2->ulUnicodeRange4 & 1L << 4); + case HB_SCRIPT_LINEAR_B: + return (fds->os2->ulUnicodeRange4 & 1L << 5); + case HB_SCRIPT_UGARITIC: + return (fds->os2->ulUnicodeRange4 & 1L << 7); + case HB_SCRIPT_OLD_PERSIAN: + return (fds->os2->ulUnicodeRange4 & 1L << 8); + case HB_SCRIPT_SHAVIAN: + return (fds->os2->ulUnicodeRange4 & 1L << 9); + case HB_SCRIPT_OSMANYA: + return (fds->os2->ulUnicodeRange4 & 1L << 10); + case HB_SCRIPT_CYPRIOT: + return (fds->os2->ulUnicodeRange4 & 1L << 11); + case HB_SCRIPT_KHAROSHTHI: + return (fds->os2->ulUnicodeRange4 & 1L << 12); + case HB_SCRIPT_TAI_VIET: + return (fds->os2->ulUnicodeRange4 & 1L << 13); + case HB_SCRIPT_CUNEIFORM: + return (fds->os2->ulUnicodeRange4 & 1L << 14); + case HB_SCRIPT_SUNDANESE: + return (fds->os2->ulUnicodeRange4 & 1L << 16); + case HB_SCRIPT_LEPCHA: + return (fds->os2->ulUnicodeRange4 & 1L << 17); + case HB_SCRIPT_OL_CHIKI: + return (fds->os2->ulUnicodeRange4 & 1L << 18); + case HB_SCRIPT_SAURASHTRA: + return (fds->os2->ulUnicodeRange4 & 1L << 19); + case HB_SCRIPT_KAYAH_LI: + return (fds->os2->ulUnicodeRange4 & 1L << 20); + case HB_SCRIPT_REJANG: + return (fds->os2->ulUnicodeRange4 & 1L << 21); + case HB_SCRIPT_CHAM: + return (fds->os2->ulUnicodeRange4 & 1L << 22); + case HB_SCRIPT_ANATOLIAN_HIEROGLYPHS: + return (fds->os2->ulUnicodeRange4 & 1L << 25); + default: + return false; + }; +} + +void DynamicFontDataAdvanced::set_antialiased(bool p_antialiased) { + if (antialiased != p_antialiased) { + clear_cache(); + antialiased = p_antialiased; + } +} + +bool DynamicFontDataAdvanced::get_antialiased() const { + return antialiased; +} + +void DynamicFontDataAdvanced::set_force_autohinter(bool p_enabled) { + if (force_autohinter != p_enabled) { + clear_cache(); + force_autohinter = p_enabled; + } +} + +bool DynamicFontDataAdvanced::get_force_autohinter() const { + return force_autohinter; +} + +void DynamicFontDataAdvanced::set_hinting(TextServer::Hinting p_hinting) { + if (hinting != p_hinting) { + clear_cache(); + hinting = p_hinting; + } +} + +TextServer::Hinting DynamicFontDataAdvanced::get_hinting() const { + return hinting; +} + +bool DynamicFontDataAdvanced::has_outline() const { + return true; +} + +float DynamicFontDataAdvanced::get_base_size() const { + return base_size; +} + +String DynamicFontDataAdvanced::get_supported_chars() const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(base_size); + ERR_FAIL_COND_V(fds == nullptr, String()); + + String chars; + + FT_UInt gindex; + FT_ULong charcode = FT_Get_First_Char(fds->face, &gindex); + while (gindex != 0) { + if (charcode != 0) { + chars += char32_t(charcode); + } + charcode = FT_Get_Next_Char(fds->face, charcode, &gindex); + } + + return chars; +} + +float DynamicFontDataAdvanced::get_font_scale(int p_size) const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(p_size); + ERR_FAIL_COND_V(fds == nullptr, 1.0f); + + return fds->scale_color_font / oversampling; +} + +bool DynamicFontDataAdvanced::has_char(char32_t p_char) const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(base_size); + ERR_FAIL_COND_V(fds == nullptr, false); + + const_cast<DynamicFontDataAdvanced *>(this)->update_glyph(base_size, FT_Get_Char_Index(fds->face, p_char)); + Character ch = fds->glyph_map[FT_Get_Char_Index(fds->face, p_char)]; + + return (ch.found); +} + +hb_font_t *DynamicFontDataAdvanced::get_hb_handle(int p_size) { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = get_data_for_size(p_size); + ERR_FAIL_COND_V(fds == nullptr, nullptr); + + return fds->hb_handle; +} + +uint32_t DynamicFontDataAdvanced::get_glyph_index(char32_t p_char, char32_t p_variation_selector) const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(base_size); + ERR_FAIL_COND_V(fds == nullptr, 0); + + if (p_variation_selector == 0x0000) { + return FT_Get_Char_Index(fds->face, p_char); + } else { + return FT_Face_GetCharVariantIndex(fds->face, p_char, p_variation_selector); + } +} + +Vector2 DynamicFontDataAdvanced::get_advance(uint32_t p_index, int p_size) const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(p_size); + ERR_FAIL_COND_V(fds == nullptr, Vector2()); + + const_cast<DynamicFontDataAdvanced *>(this)->update_glyph(p_size, p_index); + Character ch = fds->glyph_map[p_index]; + + return ch.advance; +} + +Vector2 DynamicFontDataAdvanced::get_kerning(uint32_t p_char, uint32_t p_next, int p_size) const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(p_size); + ERR_FAIL_COND_V(fds == nullptr, Vector2()); + + FT_Vector delta; + FT_Get_Kerning(fds->face, p_char, p_next, FT_KERNING_DEFAULT, &delta); + return Vector2(delta.x, delta.y); +} + +Vector2 DynamicFontDataAdvanced::draw_glyph(RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(p_size); + ERR_FAIL_COND_V(fds == nullptr, Vector2()); + + const_cast<DynamicFontDataAdvanced *>(this)->update_glyph(p_size, p_index); + Character ch = fds->glyph_map[p_index]; + + Vector2 advance; + if (ch.found) { + ERR_FAIL_COND_V(ch.texture_idx < -1 || ch.texture_idx >= fds->textures.size(), Vector2()); + + if (ch.texture_idx != -1) { + Point2 cpos = p_pos; + cpos += ch.align; + Color modulate = p_color; + if (FT_HAS_COLOR(fds->face)) { + modulate.r = modulate.g = modulate.b = 1.0; + } + if (RenderingServer::get_singleton() != nullptr) { + RID texture = fds->textures[ch.texture_idx].texture->get_rid(); + RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, Rect2(cpos, ch.rect.size), texture, ch.rect_uv, modulate, false, false); + } + } + + advance = ch.advance; + } + + return advance; +} + +Vector2 DynamicFontDataAdvanced::draw_glyph_outline(RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(p_size, p_outline_size); + ERR_FAIL_COND_V(fds == nullptr, Vector2()); + + const_cast<DynamicFontDataAdvanced *>(this)->update_glyph_outline(p_size, p_outline_size, p_index); + Character ch = fds->glyph_map[p_index]; + + Vector2 advance; + if (ch.found) { + ERR_FAIL_COND_V(ch.texture_idx < -1 || ch.texture_idx >= fds->textures.size(), Vector2()); + + if (ch.texture_idx != -1) { + Point2 cpos = p_pos; + cpos += ch.align; + Color modulate = p_color; + if (FT_HAS_COLOR(fds->face)) { + modulate.r = modulate.g = modulate.b = 1.0; + } + if (RenderingServer::get_singleton() != nullptr) { + RID texture = fds->textures[ch.texture_idx].texture->get_rid(); + RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, Rect2(cpos, ch.rect.size), texture, ch.rect_uv, modulate, false, false); + } + } + + advance = ch.advance; + } + + return advance; +} + +DynamicFontDataAdvanced::~DynamicFontDataAdvanced() { + clear_cache(); + if (library != nullptr) { + FT_Done_FreeType(library); + } +} diff --git a/modules/text_server_adv/dynamic_font_adv.h b/modules/text_server_adv/dynamic_font_adv.h new file mode 100644 index 0000000000..61cff3cde9 --- /dev/null +++ b/modules/text_server_adv/dynamic_font_adv.h @@ -0,0 +1,188 @@ +/*************************************************************************/ +/* dynamic_font_adv.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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. */ +/*************************************************************************/ + +#ifndef DYNAMIC_FONT_ADV_H +#define DYNAMIC_FONT_ADV_H + +#include "font_adv.h" + +#include <ft2build.h> +#include FT_FREETYPE_H +#include FT_TRUETYPE_TABLES_H + +#include <hb-ft.h> +#include <hb-ot.h> + +struct DynamicFontDataAdvanced : public FontDataAdvanced { + _THREAD_SAFE_CLASS_ + +private: + struct CharTexture { + Vector<uint8_t> imgdata; + int texture_size = 0; + Vector<int> offsets; + Ref<ImageTexture> texture; + }; + + struct Character { + bool found = false; + int texture_idx = 0; + Rect2 rect; + Rect2 rect_uv; + Vector2 align; + Vector2 advance = Vector2(-1, -1); + + static Character not_found(); + }; + + struct TexturePosition { + int index = 0; + int x = 0; + int y = 0; + }; + + struct CacheID { + union { + struct { + uint32_t size : 16; + uint32_t outline_size : 16; + }; + uint32_t key; + }; + bool operator<(CacheID right) const { + return key < right.key; + } + CacheID() { + key = 0; + } + }; + + struct DataAtSize { + FT_Face face = nullptr; + TT_OS2 *os2 = nullptr; + FT_StreamRec stream; + + int size = 0; + float scale_color_font = 1.f; + float ascent = 0; + float descent = 0; + float underline_position = 0; + float underline_thickness = 0; + + Vector<CharTexture> textures; + HashMap<uint32_t, Character> glyph_map; + + hb_font_t *hb_handle = nullptr; + ~DataAtSize() { + if (hb_handle != nullptr) { + hb_font_destroy(hb_handle); + } + if (face != nullptr) { + FT_Done_Face(face); + } + } + }; + + FT_Library library = nullptr; + + // Source data. + const uint8_t *font_mem = nullptr; + int font_mem_size = 0; + String font_path; + static HashMap<String, Vector<uint8_t>> font_mem_cache; + + float rect_margin = 1.f; + int base_size = 16; + float oversampling = 1.f; + bool antialiased = true; + bool force_autohinter = false; + TextServer::Hinting hinting = TextServer::HINTING_LIGHT; + + Map<CacheID, DataAtSize *> size_cache; + Map<CacheID, DataAtSize *> size_cache_outline; + + static unsigned long _ft_stream_io(FT_Stream stream, unsigned long offset, unsigned char *buffer, unsigned long count); + static void _ft_stream_close(FT_Stream stream); + + DataAtSize *get_data_for_size(int p_size, int p_outline_size = 0); + + TexturePosition find_texture_pos_for_glyph(DataAtSize *p_data, int p_color_size, Image::Format p_image_format, int p_width, int p_height); + Character bitmap_to_character(DataAtSize *p_data, FT_Bitmap bitmap, int yofs, int xofs, const Vector2 &advance); + _FORCE_INLINE_ void update_glyph(int p_size, uint32_t p_index); + _FORCE_INLINE_ void update_glyph_outline(int p_size, int p_outline_size, uint32_t p_index); + +public: + virtual void clear_cache() override; + + virtual Error load_from_file(const String &p_filename, int p_base_size) override; + virtual Error load_from_memory(const uint8_t *p_data, size_t p_size, int p_base_size) override; + + virtual float get_height(int p_size) const override; + virtual float get_ascent(int p_size) const override; + virtual float get_descent(int p_size) const override; + + virtual Dictionary get_feature_list() const override; + + virtual float get_underline_position(int p_size) const override; + virtual float get_underline_thickness(int p_size) const override; + + virtual void set_antialiased(bool p_antialiased) override; + virtual bool get_antialiased() const override; + + virtual void set_hinting(TextServer::Hinting p_hinting) override; + virtual TextServer::Hinting get_hinting() const override; + + virtual void set_force_autohinter(bool p_enabled) override; + virtual bool get_force_autohinter() const override; + + virtual void set_distance_field_hint(bool p_distance_field) override{}; + virtual bool get_distance_field_hint() const override { return false; }; + + virtual bool has_outline() const override; + virtual float get_base_size() const override; + + virtual bool is_script_supported(uint32_t p_script) const override; + + virtual bool has_char(char32_t p_char) const override; + virtual String get_supported_chars() const override; + virtual float get_font_scale(int p_size) const override; + + virtual hb_font_t *get_hb_handle(int p_size) override; + virtual uint32_t get_glyph_index(char32_t p_char, char32_t p_variation_selector) const override; + virtual Vector2 get_advance(uint32_t p_index, int p_size) const override; + virtual Vector2 get_kerning(uint32_t p_char, uint32_t p_next, int p_size) const override; + + virtual Vector2 draw_glyph(RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const override; + virtual Vector2 draw_glyph_outline(RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const override; + + virtual ~DynamicFontDataAdvanced() override; +}; + +#endif // DYNAMIC_FONT_ADV_H diff --git a/modules/text_server_adv/font_adv.h b/modules/text_server_adv/font_adv.h new file mode 100644 index 0000000000..232d6d7d08 --- /dev/null +++ b/modules/text_server_adv/font_adv.h @@ -0,0 +1,90 @@ +/*************************************************************************/ +/* font_adv.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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. */ +/*************************************************************************/ + +#ifndef FONT_ADV_H +#define FONT_ADV_H + +#include "servers/text_server.h" + +#include <hb.h> + +struct FontDataAdvanced { + Map<String, bool> lang_support_overrides; + Map<String, bool> script_support_overrides; + bool valid = false; + + virtual void clear_cache() = 0; + + virtual Error load_from_file(const String &p_filename, int p_base_size) = 0; + virtual Error load_from_memory(const uint8_t *p_data, size_t p_size, int p_base_size) = 0; + + virtual float get_height(int p_size) const = 0; + virtual float get_ascent(int p_size) const = 0; + virtual float get_descent(int p_size) const = 0; + + virtual Dictionary get_feature_list() const { return Dictionary(); }; + + virtual float get_underline_position(int p_size) const = 0; + virtual float get_underline_thickness(int p_size) const = 0; + + virtual void set_antialiased(bool p_antialiased) = 0; + virtual bool get_antialiased() const = 0; + + virtual void set_hinting(TextServer::Hinting p_hinting) = 0; + virtual TextServer::Hinting get_hinting() const = 0; + + virtual void set_distance_field_hint(bool p_distance_field) = 0; + virtual bool get_distance_field_hint() const = 0; + + virtual void set_force_autohinter(bool p_enabeld) = 0; + virtual bool get_force_autohinter() const = 0; + + virtual bool has_outline() const = 0; + virtual float get_base_size() const = 0; + + virtual bool is_lang_supported(const String &p_lang) const { return false; }; + virtual bool is_script_supported(uint32_t p_script) const { return false; }; + + virtual bool has_char(char32_t p_char) const = 0; + virtual String get_supported_chars() const = 0; + virtual float get_font_scale(int p_size) const { return 1.0f; }; + + virtual hb_font_t *get_hb_handle(int p_size) = 0; + virtual uint32_t get_glyph_index(char32_t p_char, char32_t p_variation_selector) const = 0; + virtual Vector2 get_advance(uint32_t p_char, int p_size) const = 0; + virtual Vector2 get_kerning(uint32_t p_char, uint32_t p_next, int p_size) const = 0; + + virtual Vector2 draw_glyph(RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const = 0; + virtual Vector2 draw_glyph_outline(RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const = 0; + + virtual ~FontDataAdvanced(){}; +}; + +#endif // FONT_ADV_H diff --git a/modules/text_server_adv/icu_data/icudata_stub.cpp b/modules/text_server_adv/icu_data/icudata_stub.cpp new file mode 100644 index 0000000000..13f0ac0c50 --- /dev/null +++ b/modules/text_server_adv/icu_data/icudata_stub.cpp @@ -0,0 +1,63 @@ +/*************************************************************************/ +/* icudata_stub.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 "unicode/udata.h" +#include "unicode/utypes.h" +#include "unicode/uversion.h" + +typedef struct { + uint16_t header_size; + uint8_t magic_1, magic_2; + UDataInfo info; + char padding[8]; + uint32_t count, reserved; + int fake_name_and_data[4]; +} ICU_data_header; + +extern "C" U_EXPORT const ICU_data_header U_ICUDATA_ENTRY_POINT = { + 32, + 0xDA, 0x27, + { sizeof(UDataInfo), + 0, +#if U_IS_BIG_ENDIAN + 1, +#else + 0, +#endif + U_CHARSET_FAMILY, + sizeof(UChar), + 0, + { 0x54, 0x6F, 0x43, 0x50 }, + { 1, 0, 0, 0 }, + { 0, 0, 0, 0 } }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + 0, 0, + { 0, 0, 0, 0 } +}; diff --git a/modules/text_server_adv/register_types.cpp b/modules/text_server_adv/register_types.cpp new file mode 100644 index 0000000000..68117e0380 --- /dev/null +++ b/modules/text_server_adv/register_types.cpp @@ -0,0 +1,43 @@ +/*************************************************************************/ +/* register_types.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 "register_types.h" + +#include "text_server_adv.h" + +void preregister_text_server_adv_types() { + TextServerAdvanced::register_server(); +} + +void register_text_server_adv_types() { +} + +void unregister_text_server_adv_types() { +} diff --git a/modules/text_server_adv/register_types.h b/modules/text_server_adv/register_types.h new file mode 100644 index 0000000000..8319ddfd5d --- /dev/null +++ b/modules/text_server_adv/register_types.h @@ -0,0 +1,40 @@ +/*************************************************************************/ +/* register_types.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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. */ +/*************************************************************************/ + +#ifndef TEXT_SERVER_ADV_REGISTER_TYPES_H +#define TEXT_SERVER_ADV_REGISTER_TYPES_H + +#define MODULE_TEXT_SERVER_ADV_HAS_PREREGISTER + +void preregister_text_server_adv_types(); +void register_text_server_adv_types(); +void unregister_text_server_adv_types(); + +#endif // TEXT_SERVER_ADV_REGISTER_TYPES_H diff --git a/modules/text_server_adv/script_iterator.cpp b/modules/text_server_adv/script_iterator.cpp new file mode 100644 index 0000000000..8a2b2cced0 --- /dev/null +++ b/modules/text_server_adv/script_iterator.cpp @@ -0,0 +1,109 @@ +/*************************************************************************/ +/* script_iterator.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 "script_iterator.h" + +bool ScriptIterator::same_script(int32_t p_script_one, int32_t p_script_two) { + return p_script_one <= USCRIPT_INHERITED || p_script_two <= USCRIPT_INHERITED || p_script_one == p_script_two; +} + +ScriptIterator::ScriptIterator(const String &p_string, int p_start, int p_length) { + struct ParenStackEntry { + int pair_index; + UScriptCode script_code; + }; + + if (p_start >= p_length) { + p_start = p_length - 1; + } + + if (p_start < 0) { + p_start = 0; + } + + ParenStackEntry paren_stack[128]; + + int script_start; + int script_end = p_start; + UScriptCode script_code; + int paren_sp = -1; + int start_sp = paren_sp; + UErrorCode err = U_ZERO_ERROR; + + do { + script_code = USCRIPT_COMMON; + for (script_start = script_end; script_end < p_length; script_end++) { + UChar32 ch = p_string[script_end]; + UScriptCode sc = uscript_getScript(ch, &err); + if (U_FAILURE(err)) { + ERR_FAIL_MSG(u_errorName(err)); + } + if (u_getIntPropertyValue(ch, UCHAR_BIDI_PAIRED_BRACKET_TYPE) != U_BPT_NONE) { + if (u_getIntPropertyValue(ch, UCHAR_BIDI_PAIRED_BRACKET_TYPE) == U_BPT_OPEN) { + paren_stack[++paren_sp].pair_index = ch; + paren_stack[paren_sp].script_code = script_code; + } else if (paren_sp >= 0) { + UChar32 paired_ch = u_getBidiPairedBracket(ch); + while (paren_sp >= 0 && paren_stack[paren_sp].pair_index != paired_ch) { + paren_sp -= 1; + } + if (paren_sp < start_sp) + start_sp = paren_sp; + if (paren_sp >= 0) + sc = paren_stack[paren_sp].script_code; + } + } + + if (same_script(script_code, sc)) { + if (script_code <= USCRIPT_INHERITED && sc > USCRIPT_INHERITED) { + script_code = sc; + while (start_sp < paren_sp) { + paren_stack[++start_sp].script_code = script_code; + } + } + if ((u_getIntPropertyValue(ch, UCHAR_BIDI_PAIRED_BRACKET_TYPE) == U_BPT_CLOSE) && paren_sp >= 0) { + paren_sp -= 1; + if (start_sp >= 0) { + start_sp -= 1; + } + } + } else { + break; + } + } + + ScriptRange rng; + rng.script = hb_icu_script_to_script(script_code); + rng.start = script_start; + rng.end = script_end; + + script_ranges.push_back(rng); + } while (script_end < p_length); +} diff --git a/modules/text_server_adv/script_iterator.h b/modules/text_server_adv/script_iterator.h new file mode 100644 index 0000000000..4523aa2767 --- /dev/null +++ b/modules/text_server_adv/script_iterator.h @@ -0,0 +1,61 @@ +/*************************************************************************/ +/* script_iterator.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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. */ +/*************************************************************************/ + +#ifndef SCRIPT_ITERATOR_H +#define SCRIPT_ITERATOR_H + +#include "servers/text_server.h" + +#include <unicode/uchar.h> +#include <unicode/uloc.h> +#include <unicode/uscript.h> +#include <unicode/ustring.h> +#include <unicode/utypes.h> + +#include <hb-icu.h> +#include <hb.h> + +class ScriptIterator { +public: + struct ScriptRange { + int start; + int end; + hb_script_t script; + }; + Vector<ScriptRange> script_ranges; + +private: + static bool same_script(int32_t p_script_one, int32_t p_script_two); + +public: + ScriptIterator(const String &p_string, int p_start, int p_length); +}; + +#endif //SCRIPT_ITERATOR_H diff --git a/modules/text_server_adv/text_server_adv.cpp b/modules/text_server_adv/text_server_adv.cpp new file mode 100644 index 0000000000..e391777eea --- /dev/null +++ b/modules/text_server_adv/text_server_adv.cpp @@ -0,0 +1,2520 @@ +/*************************************************************************/ +/* text_server_adv.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 "text_server_adv.h" +#include "bitmap_font_adv.h" +#include "dynamic_font_adv.h" + +#include "core/string/translation.h" + +#ifdef ICU_STATIC_DATA +#include "thirdparty/icu4c/icudata.gen.h" +#endif + +_FORCE_INLINE_ bool is_ain(char32_t p_chr) { + return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_AIN; +} + +_FORCE_INLINE_ bool is_alef(char32_t p_chr) { + return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_ALEF; +} + +_FORCE_INLINE_ bool is_beh(char32_t p_chr) { + int32_t prop = u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP); + return (prop == U_JG_BEH) || (prop == U_JG_NOON) || (prop == U_JG_AFRICAN_NOON) || (prop == U_JG_NYA) || (prop == U_JG_YEH) || (prop == U_JG_FARSI_YEH); +} + +_FORCE_INLINE_ bool is_dal(char32_t p_chr) { + return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_DAL; +} + +_FORCE_INLINE_ bool is_feh(char32_t p_chr) { + return (u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_FEH) || (u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_AFRICAN_FEH); +} + +_FORCE_INLINE_ bool is_gaf(char32_t p_chr) { + return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_GAF; +} + +_FORCE_INLINE_ bool is_heh(char32_t p_chr) { + return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_HEH; +} + +_FORCE_INLINE_ bool is_kaf(char32_t p_chr) { + return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_KAF; +} + +_FORCE_INLINE_ bool is_lam(char32_t p_chr) { + return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_LAM; +} + +_FORCE_INLINE_ bool is_qaf(char32_t p_chr) { + return (u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_QAF) || (u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_AFRICAN_QAF); +} + +_FORCE_INLINE_ bool is_reh(char32_t p_chr) { + return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_REH; +} + +_FORCE_INLINE_ bool is_seen_sad(char32_t p_chr) { + return (u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_SAD) || (u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_SEEN); +} + +_FORCE_INLINE_ bool is_tah(char32_t p_chr) { + return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_TAH; +} + +_FORCE_INLINE_ bool is_teh_marbuta(char32_t p_chr) { + return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_TEH_MARBUTA; +} + +_FORCE_INLINE_ bool is_yeh(char32_t p_chr) { + int32_t prop = u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP); + return (prop == U_JG_YEH) || (prop == U_JG_FARSI_YEH) || (prop == U_JG_YEH_BARREE) || (prop == U_JG_BURUSHASKI_YEH_BARREE) || (prop == U_JG_YEH_WITH_TAIL); +} + +_FORCE_INLINE_ bool is_waw(char32_t p_chr) { + return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_WAW; +} + +_FORCE_INLINE_ bool is_transparent(char32_t p_chr) { + return u_getIntPropertyValue(p_chr, UCHAR_JOINING_TYPE) == U_JT_TRANSPARENT; +} + +_FORCE_INLINE_ bool is_ligature(char32_t p_chr, char32_t p_nchr) { + return (is_lam(p_chr) && is_alef(p_nchr)); +} + +_FORCE_INLINE_ bool is_connected_to_prev(char32_t p_chr, char32_t p_pchr) { + int32_t prop = u_getIntPropertyValue(p_pchr, UCHAR_JOINING_TYPE); + return (prop != U_JT_RIGHT_JOINING) && (prop != U_JT_NON_JOINING) ? !is_ligature(p_pchr, p_chr) : false; +} + +_FORCE_INLINE_ bool is_control(char32_t p_char) { + return (p_char <= 0x001f) || (p_char >= 0x007f && p_char <= 0x009F); +} + +_FORCE_INLINE_ bool is_whitespace(char32_t p_char) { + return (p_char == 0x0020) || (p_char == 0x00A0) || (p_char == 0x1680) || (p_char >= 0x2000 && p_char <= 0x200a) || (p_char == 0x202f) || (p_char == 0x205f) || (p_char == 0x3000) || (p_char == 0x2028) || (p_char == 0x2029) || (p_char >= 0x0009 && p_char <= 0x000d) || (p_char == 0x0085); +} + +_FORCE_INLINE_ bool is_linebreak(char32_t p_char) { + return (p_char >= 0x000a && p_char <= 0x000d) || (p_char == 0x0085) || (p_char == 0x2028) || (p_char == 0x2029); +} + +/*************************************************************************/ + +String TextServerAdvanced::interface_name = "ICU / HarfBuzz / Graphite"; +uint32_t TextServerAdvanced::interface_features = FEATURE_BIDI_LAYOUT | FEATURE_VERTICAL_LAYOUT | FEATURE_SHAPING | FEATURE_KASHIDA_JUSTIFICATION | FEATURE_BREAK_ITERATORS | FEATURE_USE_SUPPORT_DATA; + +bool TextServerAdvanced::has_feature(Feature p_feature) { + return (interface_features & p_feature) == p_feature; +} + +String TextServerAdvanced::get_name() const { + return interface_name; +} + +void TextServerAdvanced::free(RID p_rid) { + _THREAD_SAFE_METHOD_ + if (font_owner.owns(p_rid)) { + FontDataAdvanced *fd = font_owner.getornull(p_rid); + font_owner.free(p_rid); + memdelete(fd); + } else if (shaped_owner.owns(p_rid)) { + ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_rid); + shaped_owner.free(p_rid); + memdelete(sd); + } +} + +bool TextServerAdvanced::has(RID p_rid) { + _THREAD_SAFE_METHOD_ + return font_owner.owns(p_rid) || shaped_owner.owns(p_rid); +} + +bool TextServerAdvanced::load_support_data(const String &p_filename) { + _THREAD_SAFE_METHOD_ + +#ifdef ICU_STATIC_DATA + if (icu_data == nullptr) { + UErrorCode err = U_ZERO_ERROR; + u_init(&err); // Do not check for errors, since we only load part the of data. + icu_data = (uint8_t *)&U_ICUDATA_ENTRY_POINT; + } +#else + if (icu_data == nullptr) { + String filename = (p_filename.empty()) ? String("res://") + _MKSTR(ICU_DATA_NAME) : p_filename; + + FileAccess *f = FileAccess::open(filename, FileAccess::READ); + if (!f) { + return false; + } + + UErrorCode err = U_ZERO_ERROR; + + // ICU data found. + size_t len = f->get_len(); + icu_data = (uint8_t *)memalloc(len); + f->get_buffer(icu_data, len); + f->close(); + memdelete(f); + + udata_setCommonData(icu_data, &err); + if (U_FAILURE(err)) { + memfree(icu_data); + icu_data = nullptr; + ERR_FAIL_V_MSG(false, u_errorName(err)); + } + + err = U_ZERO_ERROR; + u_init(&err); + if (U_FAILURE(err)) { + memfree(icu_data); + icu_data = nullptr; + ERR_FAIL_V_MSG(false, u_errorName(err)); + } + } +#endif + return true; +} + +#ifdef TOOLS_ENABLED + +bool TextServerAdvanced::save_support_data(const String &p_filename) { + _THREAD_SAFE_METHOD_ +#ifdef ICU_STATIC_DATA + + // Store data to the res file if it's available. + FileAccess *f = FileAccess::open(p_filename, FileAccess::WRITE); + if (!f) { + return false; + } + f->store_buffer(U_ICUDATA_ENTRY_POINT, U_ICUDATA_SIZE); + f->close(); + memdelete(f); + return true; + +#else + return false; +#endif +} + +#endif + +bool TextServerAdvanced::is_locale_right_to_left(const String &p_locale) { + String l = p_locale.get_slicec('_', 0); + if ((l == "ar") || (l == "dv") || (l == "he") || (l == "fa") || (l == "ff") || (l == "ku") || (l == "ur")) { + return true; + } else { + return false; + } +} + +struct FeatureInfo { + int32_t tag; + String name; +}; + +static FeatureInfo feature_set[] = { + // Registred OpenType feature tags. + { HB_TAG('a', 'a', 'l', 't'), "access_all_alternates" }, + { HB_TAG('a', 'b', 'v', 'f'), "above_base_forms" }, + { HB_TAG('a', 'b', 'v', 'm'), "above_base_mark_positioning" }, + { HB_TAG('a', 'b', 'v', 's'), "above_base_substitutions" }, + { HB_TAG('a', 'f', 'r', 'c'), "alternative_fractions" }, + { HB_TAG('a', 'k', 'h', 'n'), "akhands" }, + { HB_TAG('b', 'l', 'w', 'f'), "below_base_forms" }, + { HB_TAG('b', 'l', 'w', 'm'), "below_base_mark_positioning" }, + { HB_TAG('b', 'l', 'w', 's'), "below_base_substitutions" }, + { HB_TAG('c', 'a', 'l', 't'), "contextual_alternates" }, + { HB_TAG('c', 'a', 's', 'e'), "case_sensitive_forms" }, + { HB_TAG('c', 'c', 'm', 'p'), "glyph_composition" }, + { HB_TAG('c', 'f', 'a', 'r'), "conjunct_form_after_ro" }, + { HB_TAG('c', 'j', 'c', 't'), "conjunct_forms" }, + { HB_TAG('c', 'l', 'i', 'g'), "contextual_ligatures" }, + { HB_TAG('c', 'p', 'c', 't'), "centered_cjk_punctuation" }, + { HB_TAG('c', 'p', 's', 'p'), "capital_spacing" }, + { HB_TAG('c', 's', 'w', 'h'), "contextual_swash" }, + { HB_TAG('c', 'u', 'r', 's'), "cursive_positioning" }, + { HB_TAG('c', 'v', '0', '1'), "character_variant_01" }, + { HB_TAG('c', 'v', '0', '2'), "character_variant_02" }, + { HB_TAG('c', 'v', '0', '3'), "character_variant_03" }, + { HB_TAG('c', 'v', '0', '4'), "character_variant_04" }, + { HB_TAG('c', 'v', '0', '5'), "character_variant_05" }, + { HB_TAG('c', 'v', '0', '6'), "character_variant_06" }, + { HB_TAG('c', 'v', '0', '7'), "character_variant_07" }, + { HB_TAG('c', 'v', '0', '8'), "character_variant_08" }, + { HB_TAG('c', 'v', '0', '9'), "character_variant_09" }, + { HB_TAG('c', 'v', '1', '0'), "character_variant_10" }, + { HB_TAG('c', 'v', '1', '1'), "character_variant_11" }, + { HB_TAG('c', 'v', '1', '2'), "character_variant_12" }, + { HB_TAG('c', 'v', '1', '3'), "character_variant_13" }, + { HB_TAG('c', 'v', '1', '4'), "character_variant_14" }, + { HB_TAG('c', 'v', '1', '5'), "character_variant_15" }, + { HB_TAG('c', 'v', '1', '6'), "character_variant_16" }, + { HB_TAG('c', 'v', '1', '7'), "character_variant_17" }, + { HB_TAG('c', 'v', '1', '8'), "character_variant_18" }, + { HB_TAG('c', 'v', '1', '9'), "character_variant_19" }, + { HB_TAG('c', 'v', '2', '0'), "character_variant_20" }, + { HB_TAG('c', 'v', '2', '1'), "character_variant_21" }, + { HB_TAG('c', 'v', '2', '2'), "character_variant_22" }, + { HB_TAG('c', 'v', '2', '3'), "character_variant_23" }, + { HB_TAG('c', 'v', '2', '4'), "character_variant_24" }, + { HB_TAG('c', 'v', '2', '5'), "character_variant_25" }, + { HB_TAG('c', 'v', '2', '6'), "character_variant_26" }, + { HB_TAG('c', 'v', '2', '7'), "character_variant_27" }, + { HB_TAG('c', 'v', '2', '8'), "character_variant_28" }, + { HB_TAG('c', 'v', '2', '9'), "character_variant_29" }, + { HB_TAG('c', 'v', '3', '0'), "character_variant_30" }, + { HB_TAG('c', 'v', '3', '1'), "character_variant_31" }, + { HB_TAG('c', 'v', '3', '2'), "character_variant_32" }, + { HB_TAG('c', 'v', '3', '3'), "character_variant_33" }, + { HB_TAG('c', 'v', '3', '4'), "character_variant_34" }, + { HB_TAG('c', 'v', '3', '5'), "character_variant_35" }, + { HB_TAG('c', 'v', '3', '6'), "character_variant_36" }, + { HB_TAG('c', 'v', '3', '7'), "character_variant_37" }, + { HB_TAG('c', 'v', '3', '8'), "character_variant_38" }, + { HB_TAG('c', 'v', '3', '9'), "character_variant_39" }, + { HB_TAG('c', 'v', '4', '0'), "character_variant_40" }, + { HB_TAG('c', 'v', '4', '1'), "character_variant_41" }, + { HB_TAG('c', 'v', '4', '2'), "character_variant_42" }, + { HB_TAG('c', 'v', '4', '3'), "character_variant_43" }, + { HB_TAG('c', 'v', '4', '4'), "character_variant_44" }, + { HB_TAG('c', 'v', '4', '5'), "character_variant_45" }, + { HB_TAG('c', 'v', '4', '6'), "character_variant_46" }, + { HB_TAG('c', 'v', '4', '7'), "character_variant_47" }, + { HB_TAG('c', 'v', '4', '8'), "character_variant_48" }, + { HB_TAG('c', 'v', '4', '9'), "character_variant_49" }, + { HB_TAG('c', 'v', '5', '0'), "character_variant_50" }, + { HB_TAG('c', 'v', '5', '1'), "character_variant_51" }, + { HB_TAG('c', 'v', '5', '2'), "character_variant_52" }, + { HB_TAG('c', 'v', '5', '3'), "character_variant_53" }, + { HB_TAG('c', 'v', '5', '4'), "character_variant_54" }, + { HB_TAG('c', 'v', '5', '5'), "character_variant_55" }, + { HB_TAG('c', 'v', '5', '6'), "character_variant_56" }, + { HB_TAG('c', 'v', '5', '7'), "character_variant_57" }, + { HB_TAG('c', 'v', '5', '8'), "character_variant_58" }, + { HB_TAG('c', 'v', '5', '9'), "character_variant_59" }, + { HB_TAG('c', 'v', '6', '0'), "character_variant_60" }, + { HB_TAG('c', 'v', '6', '1'), "character_variant_61" }, + { HB_TAG('c', 'v', '6', '2'), "character_variant_62" }, + { HB_TAG('c', 'v', '6', '3'), "character_variant_63" }, + { HB_TAG('c', 'v', '6', '4'), "character_variant_64" }, + { HB_TAG('c', 'v', '6', '5'), "character_variant_65" }, + { HB_TAG('c', 'v', '6', '6'), "character_variant_66" }, + { HB_TAG('c', 'v', '6', '7'), "character_variant_67" }, + { HB_TAG('c', 'v', '6', '8'), "character_variant_68" }, + { HB_TAG('c', 'v', '6', '9'), "character_variant_69" }, + { HB_TAG('c', 'v', '7', '0'), "character_variant_70" }, + { HB_TAG('c', 'v', '7', '1'), "character_variant_71" }, + { HB_TAG('c', 'v', '7', '2'), "character_variant_72" }, + { HB_TAG('c', 'v', '7', '3'), "character_variant_73" }, + { HB_TAG('c', 'v', '7', '4'), "character_variant_74" }, + { HB_TAG('c', 'v', '7', '5'), "character_variant_75" }, + { HB_TAG('c', 'v', '7', '6'), "character_variant_76" }, + { HB_TAG('c', 'v', '7', '7'), "character_variant_77" }, + { HB_TAG('c', 'v', '7', '8'), "character_variant_78" }, + { HB_TAG('c', 'v', '7', '9'), "character_variant_79" }, + { HB_TAG('c', 'v', '8', '0'), "character_variant_80" }, + { HB_TAG('c', 'v', '8', '1'), "character_variant_81" }, + { HB_TAG('c', 'v', '8', '2'), "character_variant_82" }, + { HB_TAG('c', 'v', '8', '3'), "character_variant_83" }, + { HB_TAG('c', 'v', '8', '4'), "character_variant_84" }, + { HB_TAG('c', 'v', '8', '5'), "character_variant_85" }, + { HB_TAG('c', 'v', '8', '6'), "character_variant_86" }, + { HB_TAG('c', 'v', '8', '7'), "character_variant_87" }, + { HB_TAG('c', 'v', '8', '8'), "character_variant_88" }, + { HB_TAG('c', 'v', '8', '9'), "character_variant_89" }, + { HB_TAG('c', 'v', '9', '0'), "character_variant_90" }, + { HB_TAG('c', 'v', '9', '1'), "character_variant_91" }, + { HB_TAG('c', 'v', '9', '2'), "character_variant_92" }, + { HB_TAG('c', 'v', '9', '3'), "character_variant_93" }, + { HB_TAG('c', 'v', '9', '4'), "character_variant_94" }, + { HB_TAG('c', 'v', '9', '5'), "character_variant_95" }, + { HB_TAG('c', 'v', '9', '6'), "character_variant_96" }, + { HB_TAG('c', 'v', '9', '7'), "character_variant_97" }, + { HB_TAG('c', 'v', '9', '8'), "character_variant_98" }, + { HB_TAG('c', 'v', '9', '9'), "character_variant_99" }, + { HB_TAG('c', '2', 'p', 'c'), "petite_capitals_from_capitals" }, + { HB_TAG('c', '2', 's', 'c'), "small_capitals_from_capitals" }, + { HB_TAG('d', 'i', 's', 't'), "distances" }, + { HB_TAG('d', 'l', 'i', 'g'), "discretionary_ligatures" }, + { HB_TAG('d', 'n', 'o', 'm'), "denominators" }, + { HB_TAG('d', 't', 'l', 's'), "dotless_forms" }, + { HB_TAG('e', 'x', 'p', 't'), "expert_forms" }, + { HB_TAG('f', 'a', 'l', 't'), "final_glyph_on_line_alternates" }, + { HB_TAG('f', 'i', 'n', '2'), "terminal_forms_2" }, + { HB_TAG('f', 'i', 'n', '3'), "terminal_forms_3" }, + { HB_TAG('f', 'i', 'n', 'a'), "terminal_forms" }, + { HB_TAG('f', 'l', 'a', 'c'), "flattened_accent_forms" }, + { HB_TAG('f', 'r', 'a', 'c'), "fractions" }, + { HB_TAG('f', 'w', 'i', 'd'), "full_widths" }, + { HB_TAG('h', 'a', 'l', 'f'), "half_forms" }, + { HB_TAG('h', 'a', 'l', 'n'), "halant_forms" }, + { HB_TAG('h', 'a', 'l', 't'), "alternate_half_widths" }, + { HB_TAG('h', 'i', 's', 't'), "historical_forms" }, + { HB_TAG('h', 'k', 'n', 'a'), "horizontal_kana_alternates" }, + { HB_TAG('h', 'l', 'i', 'g'), "historical_ligatures" }, + { HB_TAG('h', 'n', 'g', 'l'), "hangul" }, + { HB_TAG('h', 'o', 'j', 'o'), "hojo_kanji_forms" }, + { HB_TAG('h', 'w', 'i', 'd'), "half_widths" }, + { HB_TAG('i', 'n', 'i', 't'), "initial_forms" }, + { HB_TAG('i', 's', 'o', 'l'), "isolated_forms" }, + { HB_TAG('i', 't', 'a', 'l'), "italics" }, + { HB_TAG('j', 'a', 'l', 't'), "justification_alternates" }, + { HB_TAG('j', 'p', '7', '8'), "jis78_forms" }, + { HB_TAG('j', 'p', '8', '3'), "jis83_forms" }, + { HB_TAG('j', 'p', '9', '0'), "jis90_forms" }, + { HB_TAG('j', 'p', '0', '4'), "jis2004_forms" }, + { HB_TAG('k', 'e', 'r', 'n'), "kerning" }, + { HB_TAG('l', 'f', 'b', 'd'), "left_bounds" }, + { HB_TAG('l', 'i', 'g', 'a'), "standard_ligatures" }, + { HB_TAG('l', 'j', 'm', 'o'), "leading_jamo_forms" }, + { HB_TAG('l', 'n', 'u', 'm'), "lining_figures" }, + { HB_TAG('l', 'o', 'c', 'l'), "localized_forms" }, + { HB_TAG('l', 't', 'r', 'a'), "left_to_right_alternates" }, + { HB_TAG('l', 't', 'r', 'm'), "left_to_right_mirrored_forms" }, + { HB_TAG('m', 'a', 'r', 'k'), "mark_positioning" }, + { HB_TAG('m', 'e', 'd', '2'), "medial_forms_2" }, + { HB_TAG('m', 'e', 'd', 'i'), "medial_forms" }, + { HB_TAG('m', 'g', 'r', 'k'), "mathematical_greek" }, + { HB_TAG('m', 'k', 'm', 'k'), "mark_to_mark_positioning" }, + { HB_TAG('m', 's', 'e', 't'), "mark_positioning_via_substitution" }, + { HB_TAG('n', 'a', 'l', 't'), "alternate_annotation_forms" }, + { HB_TAG('n', 'l', 'c', 'k'), "nlc_kanji_forms" }, + { HB_TAG('n', 'u', 'k', 't'), "nukta_forms" }, + { HB_TAG('n', 'u', 'm', 'r'), "numerators" }, + { HB_TAG('o', 'n', 'u', 'm'), "oldstyle_figures" }, + { HB_TAG('o', 'p', 'b', 'd'), "optical_bounds" }, + { HB_TAG('o', 'r', 'd', 'n'), "ordinals" }, + { HB_TAG('o', 'r', 'n', 'm'), "ornaments" }, + { HB_TAG('p', 'a', 'l', 't'), "proportional_alternate_widths" }, + { HB_TAG('p', 'c', 'a', 'p'), "petite_capitals" }, + { HB_TAG('p', 'k', 'n', 'a'), "proportional_kana" }, + { HB_TAG('p', 'n', 'u', 'm'), "proportional_figures" }, + { HB_TAG('p', 'r', 'e', 'f'), "pre_base_forms" }, + { HB_TAG('p', 'r', 'e', 's'), "pre_base_substitutions" }, + { HB_TAG('p', 's', 't', 'f'), "post_base_forms" }, + { HB_TAG('p', 's', 't', 's'), "post_base_substitutions" }, + { HB_TAG('p', 'w', 'i', 'd'), "proportional_widths" }, + { HB_TAG('q', 'w', 'i', 'd'), "quarter_widths" }, + { HB_TAG('r', 'a', 'n', 'd'), "randomize" }, + { HB_TAG('r', 'c', 'l', 't'), "required_contextual_alternates" }, + { HB_TAG('r', 'k', 'r', 'f'), "rakar_forms" }, + { HB_TAG('r', 'l', 'i', 'g'), "required_ligatures" }, + { HB_TAG('r', 'p', 'h', 'f'), "reph_forms" }, + { HB_TAG('r', 't', 'b', 'd'), "right_bounds" }, + { HB_TAG('r', 't', 'l', 'a'), "right_to_left_alternates" }, + { HB_TAG('r', 't', 'l', 'm'), "right_to_left_mirrored_forms" }, + { HB_TAG('r', 'u', 'b', 'y'), "ruby_notation_forms" }, + { HB_TAG('r', 'v', 'r', 'n'), "required_variation_alternates" }, + { HB_TAG('s', 'a', 'l', 't'), "stylistic_alternates" }, + { HB_TAG('s', 'i', 'n', 'f'), "scientific_inferiors" }, + { HB_TAG('s', 'i', 'z', 'e'), "optical_size" }, + { HB_TAG('s', 'm', 'c', 'p'), "small_capitals" }, + { HB_TAG('s', 'm', 'p', 'l'), "simplified_forms" }, + { HB_TAG('s', 's', '0', '1'), "stylistic_set_01" }, + { HB_TAG('s', 's', '0', '2'), "stylistic_set_02" }, + { HB_TAG('s', 's', '0', '3'), "stylistic_set_03" }, + { HB_TAG('s', 's', '0', '4'), "stylistic_set_04" }, + { HB_TAG('s', 's', '0', '5'), "stylistic_set_05" }, + { HB_TAG('s', 's', '0', '6'), "stylistic_set_06" }, + { HB_TAG('s', 's', '0', '7'), "stylistic_set_07" }, + { HB_TAG('s', 's', '0', '8'), "stylistic_set_08" }, + { HB_TAG('s', 's', '0', '9'), "stylistic_set_09" }, + { HB_TAG('s', 's', '1', '0'), "stylistic_set_10" }, + { HB_TAG('s', 's', '1', '1'), "stylistic_set_11" }, + { HB_TAG('s', 's', '1', '2'), "stylistic_set_12" }, + { HB_TAG('s', 's', '1', '3'), "stylistic_set_13" }, + { HB_TAG('s', 's', '1', '4'), "stylistic_set_14" }, + { HB_TAG('s', 's', '1', '5'), "stylistic_set_15" }, + { HB_TAG('s', 's', '1', '6'), "stylistic_set_16" }, + { HB_TAG('s', 's', '1', '7'), "stylistic_set_17" }, + { HB_TAG('s', 's', '1', '8'), "stylistic_set_18" }, + { HB_TAG('s', 's', '1', '9'), "stylistic_set_19" }, + { HB_TAG('s', 's', '2', '0'), "stylistic_set_20" }, + { HB_TAG('s', 's', 't', 'y'), "math_script_style_alternates" }, + { HB_TAG('s', 't', 'c', 'h'), "stretching_glyph_decomposition" }, + { HB_TAG('s', 'u', 'b', 's'), "subscript" }, + { HB_TAG('s', 'u', 'p', 's'), "superscript" }, + { HB_TAG('s', 'w', 's', 'h'), "swash" }, + { HB_TAG('t', 'i', 't', 'l'), "titling" }, + { HB_TAG('t', 'j', 'm', 'o'), "trailing_jamo_forms" }, + { HB_TAG('t', 'n', 'a', 'm'), "traditional_name_forms" }, + { HB_TAG('t', 'n', 'u', 'm'), "tabular_figures" }, + { HB_TAG('t', 'r', 'a', 'd'), "traditional_forms" }, + { HB_TAG('t', 'w', 'i', 'd'), "third_widths" }, + { HB_TAG('u', 'n', 'i', 'c'), "unicase" }, + { HB_TAG('v', 'a', 'l', 't'), "alternate_vertical_metrics" }, + { HB_TAG('v', 'a', 't', 'u'), "vattu_variants" }, + { HB_TAG('v', 'e', 'r', 't'), "vertical_writing" }, + { HB_TAG('v', 'h', 'a', 'l'), "alternate_vertical_half_metrics" }, + { HB_TAG('v', 'j', 'm', 'o'), "vowel_jamo_forms" }, + { HB_TAG('v', 'k', 'n', 'a'), "vertical_kana_alternates" }, + { HB_TAG('v', 'k', 'r', 'n'), "vertical_kerning" }, + { HB_TAG('v', 'p', 'a', 'l'), "proportional_alternate_vertical_metrics" }, + { HB_TAG('v', 'r', 't', '2'), "vertical_alternates_and_rotation" }, + { HB_TAG('v', 'r', 't', 'r'), "vertical_alternates_for_rotation" }, + { HB_TAG('z', 'e', 'r', 'o'), "slashed_zero" }, + // Registred OpenType variation tags. + { HB_TAG('i', 't', 'a', 'l'), "italic" }, + { HB_TAG('o', 'p', 's', 'z'), "optical_size" }, + { HB_TAG('s', 'l', 'n', 't'), "slant" }, + { HB_TAG('w', 'd', 't', 'h'), "width" }, + { HB_TAG('w', 'g', 'h', 't'), "weight" }, + { 0, String() }, +}; + +int32_t TextServerAdvanced::name_to_tag(const String &p_name) { + for (int i = 0; feature_set[i].tag != 0; i++) { + if (feature_set[i].name == p_name) { + return feature_set[i].tag; + } + } + + // No readable name, use tag string. + return hb_tag_from_string(p_name.replace("custom_", "").ascii().get_data(), -1); +} + +String TextServerAdvanced::tag_to_name(int32_t p_tag) { + for (int i = 0; feature_set[i].tag != 0; i++) { + if (feature_set[i].tag == p_tag) { + return feature_set[i].name; + } + } + + // No readable name, use tag string. + char name[5]; + memset(name, 0, 5); + hb_tag_to_string(p_tag, name); + return String("custom_") + String(name); +} + +/*************************************************************************/ +/* Font interface */ +/*************************************************************************/ + +RID TextServerAdvanced::create_font_system(const String &p_name, int p_base_size) { + ERR_FAIL_V_MSG(RID(), "System fonts are not supported by this text server."); +} + +RID TextServerAdvanced::create_font_resource(const String &p_filename, int p_base_size) { + _THREAD_SAFE_METHOD_ + FontDataAdvanced *fd = nullptr; + if (p_filename.get_extension() == "ttf" || p_filename.get_extension() == "otf" || p_filename.get_extension() == "woff") { + fd = memnew(DynamicFontDataAdvanced); + } else if (p_filename.get_extension() == "fnt" || p_filename.get_extension() == "font") { + fd = memnew(BitmapFontDataAdvanced); + } else { + return RID(); + } + + Error err = fd->load_from_file(p_filename, p_base_size); + if (err != OK) { + memdelete(fd); + return RID(); + } + + return font_owner.make_rid(fd); +} + +RID TextServerAdvanced::create_font_memory(const uint8_t *p_data, size_t p_size, const String &p_type, int p_base_size) { + _THREAD_SAFE_METHOD_ + FontDataAdvanced *fd = nullptr; + if (p_type == "ttf" || p_type == "otf" || p_type == "woff") { + fd = memnew(DynamicFontDataAdvanced); + } else if (p_type == "fnt" || p_type == "font") { + fd = memnew(BitmapFontDataAdvanced); + } else { + return RID(); + } + + Error err = fd->load_from_memory(p_data, p_size, p_base_size); + if (err != OK) { + memdelete(fd); + return RID(); + } + + return font_owner.make_rid(fd); +} + +float TextServerAdvanced::font_get_height(RID p_font, int p_size) const { + _THREAD_SAFE_METHOD_ + const FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, 0.f); + return fd->get_height(p_size); +} + +float TextServerAdvanced::font_get_ascent(RID p_font, int p_size) const { + _THREAD_SAFE_METHOD_ + const FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, 0.f); + return fd->get_ascent(p_size); +} + +float TextServerAdvanced::font_get_descent(RID p_font, int p_size) const { + _THREAD_SAFE_METHOD_ + const FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, 0.f); + return fd->get_descent(p_size); +} + +float TextServerAdvanced::font_get_underline_position(RID p_font, int p_size) const { + _THREAD_SAFE_METHOD_ + const FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, 0.f); + return fd->get_underline_position(p_size); +} + +float TextServerAdvanced::font_get_underline_thickness(RID p_font, int p_size) const { + _THREAD_SAFE_METHOD_ + const FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, 0.f); + return fd->get_underline_thickness(p_size); +} + +void TextServerAdvanced::font_set_antialiased(RID p_font, bool p_antialiased) { + _THREAD_SAFE_METHOD_ + FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND(!fd); + fd->set_antialiased(p_antialiased); +} + +Dictionary TextServerAdvanced::font_get_feature_list(RID p_font) const { + _THREAD_SAFE_METHOD_ + const FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, Dictionary()); + return fd->get_feature_list(); +} + +bool TextServerAdvanced::font_get_antialiased(RID p_font) const { + _THREAD_SAFE_METHOD_ + const FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, false); + return fd->get_antialiased(); +} + +void TextServerAdvanced::font_set_distance_field_hint(RID p_font, bool p_distance_field) { + _THREAD_SAFE_METHOD_ + FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND(!fd); + fd->set_distance_field_hint(p_distance_field); +} + +bool TextServerAdvanced::font_get_distance_field_hint(RID p_font) const { + _THREAD_SAFE_METHOD_ + const FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, false); + return fd->get_distance_field_hint(); +} + +void TextServerAdvanced::font_set_hinting(RID p_font, TextServer::Hinting p_hinting) { + _THREAD_SAFE_METHOD_ + FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND(!fd); + fd->set_hinting(p_hinting); +} + +TextServer::Hinting TextServerAdvanced::font_get_hinting(RID p_font) const { + _THREAD_SAFE_METHOD_ + const FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, TextServer::HINTING_NONE); + return fd->get_hinting(); +} + +void TextServerAdvanced::font_set_force_autohinter(RID p_font, bool p_enabeld) { + _THREAD_SAFE_METHOD_ + FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND(!fd); + fd->set_force_autohinter(p_enabeld); +} + +bool TextServerAdvanced::font_get_force_autohinter(RID p_font) const { + _THREAD_SAFE_METHOD_ + const FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, false); + return fd->get_force_autohinter(); +} + +bool TextServerAdvanced::font_has_char(RID p_font, char32_t p_char) const { + _THREAD_SAFE_METHOD_ + const FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, false); + return fd->has_char(p_char); +} + +String TextServerAdvanced::font_get_supported_chars(RID p_font) const { + _THREAD_SAFE_METHOD_ + const FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, String()); + return fd->get_supported_chars(); +} + +bool TextServerAdvanced::font_has_outline(RID p_font) const { + _THREAD_SAFE_METHOD_ + const FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, false); + return fd->has_outline(); +} + +float TextServerAdvanced::font_get_base_size(RID p_font) const { + _THREAD_SAFE_METHOD_ + const FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, 0.f); + return fd->get_base_size(); +} + +bool TextServerAdvanced::font_is_language_supported(RID p_font, const String &p_language) const { + _THREAD_SAFE_METHOD_ + const FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, false); + if (fd->lang_support_overrides.has(p_language)) { + return fd->lang_support_overrides[p_language]; + } else { + Vector<String> tags = p_language.replace("-", "_").split("_"); + if (tags.size() > 0) { + if (fd->lang_support_overrides.has(tags[0])) { + return fd->lang_support_overrides[tags[0]]; + } + } + return fd->is_lang_supported(p_language); + } +} + +void TextServerAdvanced::font_set_language_support_override(RID p_font, const String &p_language, bool p_supported) { + _THREAD_SAFE_METHOD_ + FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND(!fd); + fd->lang_support_overrides[p_language] = p_supported; +} + +bool TextServerAdvanced::font_get_language_support_override(RID p_font, const String &p_language) { + _THREAD_SAFE_METHOD_ + FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, false); + return fd->lang_support_overrides[p_language]; +} + +void TextServerAdvanced::font_remove_language_support_override(RID p_font, const String &p_language) { + _THREAD_SAFE_METHOD_ + FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND(!fd); + fd->lang_support_overrides.erase(p_language); +} + +Vector<String> TextServerAdvanced::font_get_language_support_overrides(RID p_font) { + _THREAD_SAFE_METHOD_ + FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, Vector<String>()); + Vector<String> ret; + for (Map<String, bool>::Element *E = fd->lang_support_overrides.front(); E; E = E->next()) { + ret.push_back(E->key()); + } + return ret; +} + +bool TextServerAdvanced::font_is_script_supported(RID p_font, const String &p_script) const { + _THREAD_SAFE_METHOD_ + const FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, false); + if (fd->script_support_overrides.has(p_script)) { + return fd->script_support_overrides[p_script]; + } else { + hb_script_t scr = hb_script_from_string(p_script.ascii().get_data(), -1); + return fd->is_script_supported(scr); + } +} + +void TextServerAdvanced::font_set_script_support_override(RID p_font, const String &p_script, bool p_supported) { + _THREAD_SAFE_METHOD_ + FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND(!fd); + fd->script_support_overrides[p_script] = p_supported; +} + +bool TextServerAdvanced::font_get_script_support_override(RID p_font, const String &p_script) { + _THREAD_SAFE_METHOD_ + FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, false); + return fd->script_support_overrides[p_script]; +} + +void TextServerAdvanced::font_remove_script_support_override(RID p_font, const String &p_script) { + _THREAD_SAFE_METHOD_ + FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND(!fd); + fd->script_support_overrides.erase(p_script); +} + +Vector<String> TextServerAdvanced::font_get_script_support_overrides(RID p_font) { + _THREAD_SAFE_METHOD_ + FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, Vector<String>()); + Vector<String> ret; + for (Map<String, bool>::Element *E = fd->script_support_overrides.front(); E; E = E->next()) { + ret.push_back(E->key()); + } + return ret; +} + +uint32_t TextServerAdvanced::font_get_glyph_index(RID p_font, char32_t p_char, char32_t p_variation_selector) const { + _THREAD_SAFE_METHOD_ + const FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, 0); + return fd->get_glyph_index(p_char, p_variation_selector); +} + +Vector2 TextServerAdvanced::font_get_glyph_advance(RID p_font, uint32_t p_index, int p_size) const { + _THREAD_SAFE_METHOD_ + const FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, Vector2()); + return fd->get_advance(p_index, p_size); +} + +Vector2 TextServerAdvanced::font_get_glyph_kerning(RID p_font, uint32_t p_index_a, uint32_t p_index_b, int p_size) const { + _THREAD_SAFE_METHOD_ + const FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, Vector2()); + return fd->get_kerning(p_index_a, p_index_b, p_size); +} + +Vector2 TextServerAdvanced::font_draw_glyph(RID p_font, RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const { + _THREAD_SAFE_METHOD_ + const FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, Vector2()); + return fd->draw_glyph(p_canvas, p_size, p_pos, p_index, p_color); +} + +Vector2 TextServerAdvanced::font_draw_glyph_outline(RID p_font, RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const { + _THREAD_SAFE_METHOD_ + const FontDataAdvanced *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, Vector2()); + return fd->draw_glyph_outline(p_canvas, p_size, p_outline_size, p_pos, p_index, p_color); +} + +float TextServerAdvanced::font_get_oversampling() const { + return oversampling; +} + +void TextServerAdvanced::font_set_oversampling(float p_oversampling) { + _THREAD_SAFE_METHOD_ + if (oversampling != p_oversampling) { + oversampling = p_oversampling; + List<RID> fonts; + font_owner.get_owned_list(&fonts); + for (List<RID>::Element *E = fonts.front(); E; E = E->next()) { + font_owner.getornull(E->get())->clear_cache(); + } + + List<RID> text_bufs; + shaped_owner.get_owned_list(&text_bufs); + for (List<RID>::Element *E = text_bufs.front(); E; E = E->next()) { + invalidate(shaped_owner.getornull(E->get())); + } + } +} + +Vector<String> TextServerAdvanced::get_system_fonts() const { + return Vector<String>(); +} + +/*************************************************************************/ +/* Shaped text buffer interface */ +/*************************************************************************/ + +int TextServerAdvanced::_convert_pos(const ShapedTextDataAdvanced *p_sd, int p_pos) const { + int32_t limit = p_pos; + if (p_sd->text.length() != p_sd->utf16.length()) { + const UChar *data = p_sd->utf16.ptr(); + for (int i = 0; i < p_pos; i++) { + if (U16_IS_LEAD(data[i])) { + limit--; + } + } + } + return limit; +} + +int TextServerAdvanced::_convert_pos_inv(const ShapedTextDataAdvanced *p_sd, int p_pos) const { + int32_t limit = p_pos; + if (p_sd->text.length() != p_sd->utf16.length()) { + for (int i = 0; i < p_pos; i++) { + if (p_sd->text[i] > 0xFFFF) { + limit++; + } + } + } + return limit; +} + +void TextServerAdvanced::invalidate(TextServerAdvanced::ShapedTextDataAdvanced *p_shaped) { + p_shaped->valid = false; + p_shaped->sort_valid = false; + p_shaped->line_breaks_valid = false; + p_shaped->justification_ops_valid = false; + p_shaped->ascent = 0.f; + p_shaped->descent = 0.f; + p_shaped->width = 0.f; + p_shaped->upos = 0.f; + p_shaped->uthk = 0.f; + p_shaped->glyphs.clear(); + p_shaped->glyphs_logical.clear(); + p_shaped->utf16 = Char16String(); + if (p_shaped->script_iter != nullptr) { + memdelete(p_shaped->script_iter); + p_shaped->script_iter = nullptr; + } + for (int i = 0; i < p_shaped->bidi_iter.size(); i++) { + ubidi_close(p_shaped->bidi_iter[i]); + } + p_shaped->bidi_iter.clear(); +} + +void TextServerAdvanced::full_copy(ShapedTextDataAdvanced *p_shaped) { + ShapedTextDataAdvanced *parent = shaped_owner.getornull(p_shaped->parent); + + for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = parent->objects.front(); E; E = E->next()) { + if (E->get().pos >= p_shaped->start && E->get().pos < p_shaped->end) { + p_shaped->objects[E->key()] = E->get(); + } + } + + for (int k = 0; k < parent->spans.size(); k++) { + ShapedTextDataAdvanced::Span span = parent->spans[k]; + if (span.start >= p_shaped->end || span.end <= p_shaped->start) { + continue; + } + span.start = MAX(p_shaped->start, span.start); + span.end = MIN(p_shaped->end, span.end); + p_shaped->spans.push_back(span); + } + + p_shaped->parent = RID(); +} + +RID TextServerAdvanced::create_shaped_text(TextServer::Direction p_direction, TextServer::Orientation p_orientation) { + _THREAD_SAFE_METHOD_ + ShapedTextDataAdvanced *sd = memnew(ShapedTextDataAdvanced); + sd->hb_buffer = hb_buffer_create(); + sd->direction = p_direction; + sd->orientation = p_orientation; + return shaped_owner.make_rid(sd); +} + +void TextServerAdvanced::shaped_text_clear(RID p_shaped) { + _THREAD_SAFE_METHOD_ + ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND(!sd); + + sd->parent = RID(); + sd->start = 0; + sd->end = 0; + sd->text = String(); + sd->spans.clear(); + sd->objects.clear(); + sd->bidi_override.clear(); + invalidate(sd); +} + +void TextServerAdvanced::shaped_text_set_direction(RID p_shaped, TextServer::Direction p_direction) { + _THREAD_SAFE_METHOD_ + ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND(!sd); + + if (sd->direction != p_direction) { + if (sd->parent != RID()) { + full_copy(sd); + } + sd->direction = p_direction; + invalidate(sd); + } +} + +TextServer::Direction TextServerAdvanced::shaped_text_get_direction(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, TextServer::DIRECTION_LTR); + return sd->direction; +} + +void TextServerAdvanced::shaped_text_set_bidi_override(RID p_shaped, const Vector<Vector2i> &p_override) { + _THREAD_SAFE_METHOD_ + ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND(!sd); + if (sd->parent != RID()) { + full_copy(sd); + } + sd->bidi_override = p_override; + invalidate(sd); +} + +void TextServerAdvanced::shaped_text_set_orientation(RID p_shaped, TextServer::Orientation p_orientation) { + _THREAD_SAFE_METHOD_ + ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND(!sd); + if (sd->orientation != p_orientation) { + if (sd->parent != RID()) { + full_copy(sd); + } + sd->orientation = p_orientation; + invalidate(sd); + } +} + +void TextServerAdvanced::shaped_text_set_preserve_invalid(RID p_shaped, bool p_enabled) { + _THREAD_SAFE_METHOD_ + ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND(!sd); + ERR_FAIL_COND(sd->parent != RID()); + if (sd->preserve_invalid != p_enabled) { + sd->preserve_invalid = p_enabled; + invalidate(sd); + } +} + +bool TextServerAdvanced::shaped_text_get_preserve_invalid(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, false); + return sd->preserve_invalid; +} + +void TextServerAdvanced::shaped_text_set_preserve_control(RID p_shaped, bool p_enabled) { + _THREAD_SAFE_METHOD_ + ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND(!sd); + if (sd->preserve_control != p_enabled) { + if (sd->parent != RID()) { + full_copy(sd); + } + sd->preserve_control = p_enabled; + invalidate(sd); + } +} + +bool TextServerAdvanced::shaped_text_get_preserve_control(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, false); + return sd->preserve_control; +} + +TextServer::Orientation TextServerAdvanced::shaped_text_get_orientation(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, TextServer::ORIENTATION_HORIZONTAL); + return sd->orientation; +} + +bool TextServerAdvanced::shaped_text_add_string(RID p_shaped, const String &p_text, const Vector<RID> &p_fonts, int p_size, const Dictionary &p_opentype_features, const String &p_language) { + _THREAD_SAFE_METHOD_ + ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, false); + ERR_FAIL_COND_V(p_size <= 0, false); + + if (p_text.empty()) { + return true; + } + + if (sd->parent != RID()) { + full_copy(sd); + } + + ShapedTextDataAdvanced::Span span; + span.start = sd->text.length(); + span.end = span.start + p_text.length(); + span.fonts = p_fonts; // Do not pre-sort, spans will be divided to subruns later. + span.font_size = p_size; + span.language = p_language; + span.features = p_opentype_features; + + sd->spans.push_back(span); + sd->text += p_text; + sd->end += p_text.length(); + invalidate(sd); + + return true; +} + +bool TextServerAdvanced::shaped_text_add_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align, int p_length) { + _THREAD_SAFE_METHOD_ + ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, false); + ERR_FAIL_COND_V(p_key == Variant(), false); + ERR_FAIL_COND_V(sd->objects.has(p_key), false); + + if (sd->parent != RID()) { + full_copy(sd); + } + + ShapedTextDataAdvanced::Span span; + span.start = sd->text.length(); + span.end = span.start + p_length; + span.embedded_key = p_key; + + ShapedTextDataAdvanced::EmbeddedObject obj; + obj.inline_align = p_inline_align; + obj.rect.size = p_size; + obj.pos = span.start; + + sd->spans.push_back(span); + sd->text += String::chr(0xfffc).repeat(p_length); + sd->end += p_length; + sd->objects[p_key] = obj; + invalidate(sd); + + return true; +} + +bool TextServerAdvanced::shaped_text_resize_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align) { + _THREAD_SAFE_METHOD_ + ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, false); + ERR_FAIL_COND_V(!sd->objects.has(p_key), false); + sd->objects[p_key].rect.size = p_size; + sd->objects[p_key].inline_align = p_inline_align; + if (sd->valid) { + // Recalc string metrics. + sd->ascent = 0; + sd->descent = 0; + sd->width = 0; + sd->upos = 0; + sd->uthk = 0; + for (int i = 0; i < sd->glyphs.size(); i++) { + Glyph gl = sd->glyphs[i]; + Variant key; + if (gl.count == 1) { + for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = sd->objects.front(); E; E = E->next()) { + if (E->get().pos == gl.start) { + key = E->key(); + break; + } + } + } + if (key != Variant()) { + if (sd->orientation == ORIENTATION_HORIZONTAL) { + sd->objects[key].rect.position.x = sd->width; + sd->width += sd->objects[key].rect.size.x; + switch (sd->objects[key].inline_align) { + case VALIGN_TOP: { + sd->ascent = MAX(sd->ascent, sd->objects[key].rect.size.y); + } break; + case VALIGN_CENTER: { + sd->ascent = MAX(sd->ascent, sd->objects[key].rect.size.y / 2); + sd->descent = MAX(sd->descent, sd->objects[key].rect.size.y / 2); + } break; + case VALIGN_BOTTOM: { + sd->descent = MAX(sd->descent, sd->objects[key].rect.size.y); + } break; + } + sd->glyphs.write[i].advance = sd->objects[key].rect.size.x; + } else { + sd->objects[key].rect.position.y = sd->width; + sd->width += sd->objects[key].rect.size.y; + switch (sd->objects[key].inline_align) { + case VALIGN_TOP: { + sd->ascent = MAX(sd->ascent, sd->objects[key].rect.size.x); + } break; + case VALIGN_CENTER: { + sd->ascent = MAX(sd->ascent, sd->objects[key].rect.size.x / 2); + sd->descent = MAX(sd->descent, sd->objects[key].rect.size.x / 2); + } break; + case VALIGN_BOTTOM: { + sd->descent = MAX(sd->descent, sd->objects[key].rect.size.x); + } break; + } + sd->glyphs.write[i].advance = sd->objects[key].rect.size.y; + } + } else { + const FontDataAdvanced *fd = font_owner.getornull(gl.font_rid); + if (fd != nullptr) { + if (sd->orientation == ORIENTATION_HORIZONTAL) { + sd->ascent = MAX(sd->ascent, MAX(fd->get_ascent(gl.font_size), -gl.y_off)); + sd->descent = MAX(sd->descent, MAX(fd->get_descent(gl.font_size), gl.y_off)); + } else { + sd->ascent = MAX(sd->ascent, fd->get_advance(gl.index, gl.font_size).x * 0.5); + sd->descent = MAX(sd->descent, fd->get_advance(gl.index, gl.font_size).x * 0.5); + } + sd->upos = MAX(sd->upos, font_get_underline_position(gl.font_rid, gl.font_size)); + sd->uthk = MAX(sd->uthk, font_get_underline_thickness(gl.font_rid, gl.font_size)); + } else if (sd->preserve_invalid || (sd->preserve_control && is_control(gl.index))) { + // Glyph not found, replace with hex code box. + if (sd->orientation == ORIENTATION_HORIZONTAL) { + sd->ascent = MAX(sd->ascent, get_hex_code_box_size(gl.font_size, gl.index).y * 0.75f); + sd->descent = MAX(sd->descent, get_hex_code_box_size(gl.font_size, gl.index).y * 0.25f); + } else { + sd->ascent = MAX(sd->ascent, get_hex_code_box_size(gl.font_size, gl.index).x * 0.5f); + sd->descent = MAX(sd->descent, get_hex_code_box_size(gl.font_size, gl.index).x * 0.5f); + } + } + sd->width += gl.advance * gl.repeat; + } + } + + // Align embedded objects to baseline. + for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = sd->objects.front(); E; E = E->next()) { + if ((E->get().pos >= sd->start) && (E->get().pos < sd->end)) { + if (sd->orientation == ORIENTATION_HORIZONTAL) { + switch (E->get().inline_align) { + case VALIGN_TOP: { + E->get().rect.position.y = -sd->ascent; + } break; + case VALIGN_CENTER: { + E->get().rect.position.y = -(E->get().rect.size.y / 2); + } break; + case VALIGN_BOTTOM: { + E->get().rect.position.y = sd->descent - E->get().rect.size.y; + } break; + } + } else { + switch (E->get().inline_align) { + case VALIGN_TOP: { + E->get().rect.position.x = -sd->ascent; + } break; + case VALIGN_CENTER: { + E->get().rect.position.x = -(E->get().rect.size.x / 2); + } break; + case VALIGN_BOTTOM: { + E->get().rect.position.x = sd->descent - E->get().rect.size.x; + } break; + } + } + } + } + } + return true; +} + +RID TextServerAdvanced::shaped_text_substr(RID p_shaped, int p_start, int p_length) const { + _THREAD_SAFE_METHOD_ + const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, RID()); + if (sd->parent != RID()) { + return shaped_text_substr(sd->parent, p_start, p_length); + } + if (!sd->valid) { + const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + } + ERR_FAIL_COND_V(p_start < 0 || p_length < 0, RID()); + ERR_FAIL_COND_V(sd->start > p_start || sd->end < p_start, RID()); + ERR_FAIL_COND_V(sd->end < p_start + p_length, RID()); + + ShapedTextDataAdvanced *new_sd = memnew(ShapedTextDataAdvanced); + + new_sd->hb_buffer = hb_buffer_create(); + new_sd->parent = p_shaped; + new_sd->start = p_start; + new_sd->end = p_start + p_length; + + new_sd->orientation = sd->orientation; + new_sd->direction = sd->direction; + new_sd->para_direction = sd->para_direction; + new_sd->line_breaks_valid = sd->line_breaks_valid; + new_sd->justification_ops_valid = sd->justification_ops_valid; + new_sd->sort_valid = false; + new_sd->upos = sd->upos; + new_sd->uthk = sd->uthk; + + if (p_length > 0) { + new_sd->text = sd->text.substr(p_start, p_length); + new_sd->utf16 = new_sd->text.utf16(); + new_sd->script_iter = memnew(ScriptIterator(new_sd->text, 0, new_sd->text.length())); + + for (int ov = 0; ov < sd->bidi_override.size(); ov++) { + UErrorCode err = U_ZERO_ERROR; + + if (sd->bidi_override[ov].x >= p_start + p_length || sd->bidi_override[ov].y <= p_start) { + continue; + } + int start = _convert_pos_inv(sd, MAX(0, p_start - sd->bidi_override[ov].x)); + int end = _convert_pos_inv(sd, MIN(p_start + p_length, sd->bidi_override[ov].y) - sd->bidi_override[ov].x); + + ERR_FAIL_COND_V_MSG((start < 0 || end - start > new_sd->utf16.length()), RID(), "Invalid BiDi override range."); + + //Create temporary line bidi & shape + UBiDi *bidi_iter = ubidi_openSized(end - start, 0, &err); + ERR_FAIL_COND_V_MSG(U_FAILURE(err), RID(), u_errorName(err)); + ubidi_setLine(sd->bidi_iter[ov], start, end, bidi_iter, &err); + if (U_FAILURE(err)) { + ubidi_close(bidi_iter); + ERR_FAIL_V_MSG(RID(), u_errorName(err)); + } + new_sd->bidi_iter.push_back(bidi_iter); + + err = U_ZERO_ERROR; + int bidi_run_count = ubidi_countRuns(bidi_iter, &err); + ERR_FAIL_COND_V_MSG(U_FAILURE(err), RID(), u_errorName(err)); + for (int i = 0; i < bidi_run_count; i++) { + int32_t _bidi_run_start = 0; + int32_t _bidi_run_length = 0; + ubidi_getVisualRun(bidi_iter, i, &_bidi_run_start, &_bidi_run_length); + + int32_t bidi_run_start = _convert_pos(sd, sd->bidi_override[ov].x + start + _bidi_run_start); + int32_t bidi_run_end = _convert_pos(sd, sd->bidi_override[ov].x + start + _bidi_run_start + _bidi_run_length); + + for (int j = 0; j < sd->glyphs.size(); j++) { + if ((sd->glyphs[j].start >= bidi_run_start) && (sd->glyphs[j].end <= bidi_run_end)) { + // Copy glyphs. + Glyph gl = sd->glyphs[j]; + Variant key; + if (gl.count == 1) { + for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = sd->objects.front(); E; E = E->next()) { + if (E->get().pos == gl.start) { + key = E->key(); + new_sd->objects[key] = E->get(); + break; + } + } + } + if (key != Variant()) { + if (new_sd->orientation == ORIENTATION_HORIZONTAL) { + new_sd->objects[key].rect.position.x = new_sd->width; + new_sd->width += new_sd->objects[key].rect.size.x; + switch (new_sd->objects[key].inline_align) { + case VALIGN_TOP: { + new_sd->ascent = MAX(new_sd->ascent, new_sd->objects[key].rect.size.y); + } break; + case VALIGN_CENTER: { + new_sd->ascent = MAX(new_sd->ascent, new_sd->objects[key].rect.size.y / 2); + new_sd->descent = MAX(new_sd->descent, new_sd->objects[key].rect.size.y / 2); + } break; + case VALIGN_BOTTOM: { + new_sd->descent = MAX(new_sd->descent, new_sd->objects[key].rect.size.y); + } break; + } + } else { + new_sd->objects[key].rect.position.y = new_sd->width; + new_sd->width += new_sd->objects[key].rect.size.y; + switch (new_sd->objects[key].inline_align) { + case VALIGN_TOP: { + new_sd->ascent = MAX(new_sd->ascent, new_sd->objects[key].rect.size.x); + } break; + case VALIGN_CENTER: { + new_sd->ascent = MAX(new_sd->ascent, new_sd->objects[key].rect.size.x / 2); + new_sd->descent = MAX(new_sd->descent, new_sd->objects[key].rect.size.x / 2); + } break; + case VALIGN_BOTTOM: { + new_sd->descent = MAX(new_sd->descent, new_sd->objects[key].rect.size.x); + } break; + } + } + } else { + const FontDataAdvanced *fd = font_owner.getornull(gl.font_rid); + if (fd != nullptr) { + if (new_sd->orientation == ORIENTATION_HORIZONTAL) { + new_sd->ascent = MAX(new_sd->ascent, MAX(fd->get_ascent(gl.font_size), -gl.y_off)); + new_sd->descent = MAX(new_sd->descent, MAX(fd->get_descent(gl.font_size), gl.y_off)); + } else { + new_sd->ascent = MAX(new_sd->ascent, fd->get_advance(gl.index, gl.font_size).x * 0.5); + new_sd->descent = MAX(new_sd->descent, fd->get_advance(gl.index, gl.font_size).x * 0.5); + } + } else if (new_sd->preserve_invalid || (new_sd->preserve_control && is_control(gl.index))) { + // Glyph not found, replace with hex code box. + if (new_sd->orientation == ORIENTATION_HORIZONTAL) { + new_sd->ascent = MAX(new_sd->ascent, get_hex_code_box_size(gl.font_size, gl.index).y * 0.75f); + new_sd->descent = MAX(new_sd->descent, get_hex_code_box_size(gl.font_size, gl.index).y * 0.25f); + } else { + new_sd->ascent = MAX(new_sd->ascent, get_hex_code_box_size(gl.font_size, gl.index).x * 0.5f); + new_sd->descent = MAX(new_sd->descent, get_hex_code_box_size(gl.font_size, gl.index).x * 0.5f); + } + } + new_sd->width += gl.advance * gl.repeat; + } + new_sd->glyphs.push_back(gl); + } + } + } + } + + // Align embedded objects to baseline. + for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = new_sd->objects.front(); E; E = E->next()) { + if ((E->get().pos >= new_sd->start) && (E->get().pos < new_sd->end)) { + if (sd->orientation == ORIENTATION_HORIZONTAL) { + switch (E->get().inline_align) { + case VALIGN_TOP: { + E->get().rect.position.y = -new_sd->ascent; + } break; + case VALIGN_CENTER: { + E->get().rect.position.y = -(E->get().rect.size.y / 2); + } break; + case VALIGN_BOTTOM: { + E->get().rect.position.y = new_sd->descent - E->get().rect.size.y; + } break; + } + } else { + switch (E->get().inline_align) { + case VALIGN_TOP: { + E->get().rect.position.x = -new_sd->ascent; + } break; + case VALIGN_CENTER: { + E->get().rect.position.x = -(E->get().rect.size.x / 2); + } break; + case VALIGN_BOTTOM: { + E->get().rect.position.x = new_sd->descent - E->get().rect.size.x; + } break; + } + } + } + } + } + + new_sd->valid = true; + + return shaped_owner.make_rid(new_sd); +} + +RID TextServerAdvanced::shaped_text_get_parent(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, RID()); + return sd->parent; +} + +float TextServerAdvanced::shaped_text_fit_to_width(RID p_shaped, float p_width, uint8_t /*JustificationFlag*/ p_jst_flags) { + _THREAD_SAFE_METHOD_ + ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, 0.f); + if (!sd->valid) { + const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + } + if (!sd->justification_ops_valid) { + const_cast<TextServerAdvanced *>(this)->shaped_text_update_justification_ops(p_shaped); + } + + int start_pos = 0; + int end_pos = sd->glyphs.size() - 1; + + if ((p_jst_flags & JUSTIFICATION_AFTER_LAST_TAB) == JUSTIFICATION_AFTER_LAST_TAB) { + int start, end, delta; + if (sd->para_direction == DIRECTION_LTR) { + start = sd->glyphs.size() - 1; + end = -1; + delta = -1; + } else { + start = 0; + end = sd->glyphs.size(); + delta = +1; + } + + for (int i = start; i != end; i += delta) { + if ((sd->glyphs[i].flags & GRAPHEME_IS_TAB) == GRAPHEME_IS_TAB) { + if (sd->para_direction == DIRECTION_LTR) { + start_pos = i; + break; + } else { + end_pos = i; + break; + } + } + } + } + + if ((p_jst_flags & JUSTIFICATION_TRIM_EDGE_SPACES) == JUSTIFICATION_TRIM_EDGE_SPACES) { + while ((start_pos < end_pos) && ((sd->glyphs[start_pos].flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE || (sd->glyphs[start_pos].flags & GRAPHEME_IS_BREAK_HARD) == GRAPHEME_IS_BREAK_HARD || (sd->glyphs[start_pos].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT)) { + sd->width -= sd->glyphs[start_pos].advance * sd->glyphs[start_pos].repeat; + sd->glyphs.write[start_pos].advance = 0; + start_pos += sd->glyphs[start_pos].count; + } + while ((start_pos < end_pos) && ((sd->glyphs[end_pos].flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE || (sd->glyphs[end_pos].flags & GRAPHEME_IS_BREAK_HARD) == GRAPHEME_IS_BREAK_HARD || (sd->glyphs[end_pos].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT)) { + sd->width -= sd->glyphs[end_pos].advance * sd->glyphs[end_pos].repeat; + sd->glyphs.write[end_pos].advance = 0; + end_pos -= sd->glyphs[end_pos].count; + } + } + + int space_count = 0; + int elongation_count = 0; + for (int i = start_pos; i <= end_pos; i++) { + const Glyph &gl = sd->glyphs[i]; + if (gl.count > 0) { + if ((gl.flags & GRAPHEME_IS_ELONGATION) == GRAPHEME_IS_ELONGATION) { + elongation_count++; + } + if ((gl.flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE) { + space_count++; + } + } + } + + if ((elongation_count > 0) && ((p_jst_flags & JUSTIFICATION_KASHIDA) == JUSTIFICATION_KASHIDA)) { + float delta_width_per_kashida = (p_width - sd->width) / elongation_count; + for (int i = start_pos; i <= end_pos; i++) { + Glyph &gl = sd->glyphs.write[i]; + if (gl.count > 0) { + if (((gl.flags & GRAPHEME_IS_ELONGATION) == GRAPHEME_IS_ELONGATION) && (gl.advance > 0)) { + int count = delta_width_per_kashida / gl.advance; + int prev_count = gl.repeat; + if ((gl.flags & GRAPHEME_IS_VIRTUAL) == GRAPHEME_IS_VIRTUAL) { + gl.repeat = count; + } else { + gl.repeat = count + 1; + } + sd->width += (gl.repeat - prev_count) * gl.advance; + } + } + } + } + + if ((space_count > 0) && ((p_jst_flags & JUSTIFICATION_WORD_BOUND) == JUSTIFICATION_WORD_BOUND)) { + float delta_width_per_space = (p_width - sd->width) / space_count; + for (int i = start_pos; i <= end_pos; i++) { + Glyph &gl = sd->glyphs.write[i]; + if (gl.count > 0) { + if ((gl.flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE) { + float old_adv = gl.advance; + if ((gl.flags & GRAPHEME_IS_VIRTUAL) == GRAPHEME_IS_VIRTUAL) { + gl.advance = MAX(gl.advance + delta_width_per_space, 0.f); + } else { + gl.advance = MAX(gl.advance + delta_width_per_space, 0.05 * gl.font_size); + } + sd->width += (gl.advance - old_adv); + } + } + } + } + + return sd->width; +} + +float TextServerAdvanced::shaped_text_tab_align(RID p_shaped, const Vector<float> &p_tab_stops) { + _THREAD_SAFE_METHOD_ + ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, 0.f); + if (!sd->valid) { + const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + } + if (!sd->line_breaks_valid) { + const_cast<TextServerAdvanced *>(this)->shaped_text_update_breaks(p_shaped); + } + + int tab_index = 0; + float off = 0.f; + + int start, end, delta; + if (sd->para_direction == DIRECTION_LTR) { + start = 0; + end = sd->glyphs.size(); + delta = +1; + } else { + start = sd->glyphs.size() - 1; + end = -1; + delta = -1; + } + + for (int i = start; i != end; i += delta) { + if ((sd->glyphs[i].flags & GRAPHEME_IS_TAB) == GRAPHEME_IS_TAB) { + float tab_off = 0.f; + while (tab_off <= off) { + tab_off += p_tab_stops[tab_index]; + tab_index++; + if (tab_index >= p_tab_stops.size()) { + tab_index = 0; + } + } + float old_adv = sd->glyphs.write[i].advance; + sd->glyphs.write[i].advance = (tab_off - off); + sd->width += sd->glyphs.write[i].advance - old_adv; + off = 0; + continue; + } + off += sd->glyphs[i].advance * sd->glyphs[i].repeat; + } + + return 0.f; +} + +bool TextServerAdvanced::shaped_text_update_breaks(RID p_shaped) { + _THREAD_SAFE_METHOD_ + ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, false); + if (!sd->valid) { + shaped_text_shape(p_shaped); + } + + if (sd->line_breaks_valid) { + return true; // Noting to do. + } + + const UChar *data = sd->utf16.ptr(); + + Map<int, bool> breaks; + + UErrorCode err = U_ZERO_ERROR; + for (int i = 0; i < sd->spans.size(); i++) { + UBreakIterator *bi = ubrk_open(UBRK_LINE, sd->spans[i].language.ascii().get_data(), data + _convert_pos_inv(sd, sd->spans[i].start), _convert_pos_inv(sd, sd->spans[i].end - sd->spans[i].start), &err); + if (U_FAILURE(err)) { + //No data loaded - use fallback. + for (int j = sd->spans[i].start; j < sd->spans[i].end; j++) { + char32_t c = sd->text[j - sd->start]; + if (is_whitespace(c)) { + breaks[j] = false; + } + if (is_linebreak(c)) { + breaks[j] = true; + } + } + } else { + while (ubrk_next(bi) != UBRK_DONE) { + int pos = _convert_pos(sd, ubrk_current(bi)) + sd->spans[i].start - 1; + if (pos != sd->spans[i].end) { + if ((ubrk_getRuleStatus(bi) >= UBRK_LINE_HARD) && (ubrk_getRuleStatus(bi) < UBRK_LINE_HARD_LIMIT)) { + breaks[pos] = true; + } else if ((ubrk_getRuleStatus(bi) >= UBRK_LINE_SOFT) && (ubrk_getRuleStatus(bi) < UBRK_LINE_SOFT_LIMIT)) { + breaks[pos] = false; + } + } + } + } + ubrk_close(bi); + } + + sd->sort_valid = false; + sd->glyphs_logical.clear(); + + for (int i = 0; i < sd->glyphs.size(); i++) { + if (sd->glyphs[i].count > 0) { + char32_t c = sd->text[sd->glyphs[i].start - sd->start]; + if (c == 0xfffc) { + continue; + } + if (c == 0x0009 || c == 0x000b) { + sd->glyphs.write[i].flags |= GRAPHEME_IS_TAB; + } + if (breaks.has(sd->glyphs[i].start)) { + if (breaks[sd->glyphs[i].start]) { + sd->glyphs.write[i].flags |= GRAPHEME_IS_BREAK_HARD; + } else { + if (is_whitespace(c)) { + sd->glyphs.write[i].flags |= GRAPHEME_IS_BREAK_SOFT; + sd->glyphs.write[i].flags |= GRAPHEME_IS_SPACE; + } else { + TextServer::Glyph gl; + gl.start = sd->glyphs[i].start; + gl.end = sd->glyphs[i].end; + gl.count = 1; + gl.repeat = 1; + gl.font_rid = sd->glyphs[i].font_rid; + gl.font_size = sd->glyphs[i].font_size; + gl.flags = GRAPHEME_IS_BREAK_SOFT | GRAPHEME_IS_VIRTUAL; + sd->glyphs.insert(i + sd->glyphs[i].count, gl); // insert after + i += sd->glyphs[i].count; + continue; + } + } + } + + i += (sd->glyphs[i].count - 1); + } + } + + sd->line_breaks_valid = true; + + return sd->line_breaks_valid; +} + +_FORCE_INLINE_ int _generate_kashida_justification_opportunies(const String &p_data, int p_start, int p_end) { + int kashida_pos = -1; + int8_t priority = 100; + int i = p_start; + + char32_t pc = 0; + + while ((p_end > p_start) && is_transparent(p_data[p_end - 1])) { + p_end--; + } + + while (i < p_end) { + uint32_t c = p_data[i]; + + if (c == 0x0640) { + kashida_pos = i; + priority = 0; + } + if (priority >= 1 && i < p_end - 1) { + if (is_seen_sad(c) && (p_data[i + 1] != 0x200C)) { + kashida_pos = i; + priority = 1; + } + } + if (priority >= 2 && i > p_start) { + if (is_teh_marbuta(c) || is_dal(c) || (is_heh(c) && i == p_end - 1)) { + if (is_connected_to_prev(c, pc)) { + kashida_pos = i - 1; + priority = 2; + } + } + } + if (priority >= 3 && i > p_start) { + if (is_alef(c) || ((is_lam(c) || is_tah(c) || is_kaf(c) || is_gaf(c)) && i == p_end - 1)) { + if (is_connected_to_prev(c, pc)) { + kashida_pos = i - 1; + priority = 3; + } + } + } + if (priority >= 4 && i > p_start && i < p_end - 1) { + if (is_beh(c)) { + if (is_reh(p_data[i + 1]) || is_yeh(p_data[i + 1])) { + if (is_connected_to_prev(c, pc)) { + kashida_pos = i - 1; + priority = 4; + } + } + } + } + if (priority >= 5 && i > p_start) { + if (is_waw(c) || ((is_ain(c) || is_qaf(c) || is_feh(c)) && i == p_end - 1)) { + if (is_connected_to_prev(c, pc)) { + kashida_pos = i - 1; + priority = 5; + } + } + } + if (priority >= 6 && i > p_start) { + if (is_reh(c)) { + if (is_connected_to_prev(c, pc)) { + kashida_pos = i - 1; + priority = 6; + } + } + } + if (!is_transparent(c)) + pc = c; + i++; + } + + return kashida_pos; +} + +bool TextServerAdvanced::shaped_text_update_justification_ops(RID p_shaped) { + _THREAD_SAFE_METHOD_ + ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, false); + if (!sd->valid) { + shaped_text_shape(p_shaped); + } + if (!sd->line_breaks_valid) { + shaped_text_update_breaks(p_shaped); + } + + const UChar *data = sd->utf16.ptr(); + int32_t data_size = sd->utf16.length(); + + Map<int, bool> jstops; + + // Use ICU word iterator and custom kashida detection. + UErrorCode err = U_ZERO_ERROR; + UBreakIterator *bi = ubrk_open(UBRK_WORD, "", data, data_size, &err); + if (U_FAILURE(err)) { + // No data - use fallback + int limit = 0; + for (int i = 0; i < sd->text.length(); i++) { + if (is_whitespace(data[i])) { + int ks = _generate_kashida_justification_opportunies(sd->text, limit, i) + sd->start; + if (ks != -1) { + jstops[ks] = true; + } + limit = i + 1; + } + } + int ks = _generate_kashida_justification_opportunies(sd->text, limit, sd->text.length()) + sd->start; + if (ks != -1) { + jstops[ks] = true; + } + } else { + int limit = 0; + while (ubrk_next(bi) != UBRK_DONE) { + if (ubrk_getRuleStatus(bi) != UBRK_WORD_NONE) { + int i = _convert_pos(sd, ubrk_current(bi)); + jstops[i + sd->start] = false; + int ks = _generate_kashida_justification_opportunies(sd->text, limit, i) + sd->start; + if (ks != -1) { + jstops[ks] = true; + } + limit = i; + } + } + ubrk_close(bi); + } + + sd->sort_valid = false; + sd->glyphs_logical.clear(); + + if (jstops.size() > 0) { + for (int i = 0; i < sd->glyphs.size(); i++) { + if (sd->glyphs[i].count > 0) { + if (jstops.has(sd->glyphs[i].start)) { + char32_t c = sd->text[sd->glyphs[i].start - sd->start]; + if (c == 0xfffc) { + continue; + } + if (jstops[sd->glyphs[i].start]) { + if (c == 0x0640) { + sd->glyphs.write[i].flags |= GRAPHEME_IS_ELONGATION; + } else { + if (sd->glyphs[i].font_rid != RID()) { + TextServer::Glyph gl = _shape_single_glyph(sd, 0x0640, HB_SCRIPT_ARABIC, HB_DIRECTION_RTL, sd->glyphs[i].font_rid, sd->glyphs[i].font_size); + if ((gl.flags & GRAPHEME_IS_VALID) == GRAPHEME_IS_VALID) { + gl.start = sd->glyphs[i].start; + gl.end = sd->glyphs[i].end; + gl.repeat = 0; + gl.count = 1; + if (sd->orientation == ORIENTATION_HORIZONTAL) { + gl.y_off = sd->glyphs[i].y_off; + } else { + gl.x_off = sd->glyphs[i].x_off; + } + gl.flags |= GRAPHEME_IS_ELONGATION | GRAPHEME_IS_VIRTUAL; + sd->glyphs.insert(i, gl); + i++; + } + } + } + } else if (!is_whitespace(c)) { + TextServer::Glyph gl; + gl.start = sd->glyphs[i].start; + gl.end = sd->glyphs[i].end; + gl.count = 1; + gl.repeat = 1; + gl.font_rid = sd->glyphs[i].font_rid; + gl.font_size = sd->glyphs[i].font_size; + gl.flags = GRAPHEME_IS_SPACE | GRAPHEME_IS_VIRTUAL; + sd->glyphs.insert(i + sd->glyphs[i].count, gl); // insert after + i += sd->glyphs[i].count; + continue; + } + } + } + } + } + + sd->justification_ops_valid = true; + return sd->justification_ops_valid; +} + +TextServer::Glyph TextServerAdvanced::_shape_single_glyph(ShapedTextDataAdvanced *p_sd, char32_t p_char, hb_script_t p_script, hb_direction_t p_direction, RID p_font, int p_font_size) { + FontDataAdvanced *fd = font_owner.getornull(p_font); + hb_font_t *hb_font = fd->get_hb_handle(p_font_size); + + hb_buffer_clear_contents(p_sd->hb_buffer); + hb_buffer_set_direction(p_sd->hb_buffer, p_direction); + hb_buffer_set_flags(p_sd->hb_buffer, (hb_buffer_flags_t)(HB_BUFFER_FLAG_DEFAULT)); + hb_buffer_set_script(p_sd->hb_buffer, p_script); + hb_buffer_add_utf32(p_sd->hb_buffer, (const uint32_t *)&p_char, 1, 0, 1); + + hb_shape(hb_font, p_sd->hb_buffer, nullptr, 0); + + unsigned int glyph_count = 0; + hb_glyph_info_t *glyph_info = hb_buffer_get_glyph_infos(p_sd->hb_buffer, &glyph_count); + hb_glyph_position_t *glyph_pos = hb_buffer_get_glyph_positions(p_sd->hb_buffer, &glyph_count); + + // Process glyphs. + TextServer::Glyph gl; + gl.start = -1; + gl.end = -1; + + if (p_direction == HB_DIRECTION_RTL || p_direction == HB_DIRECTION_BTT) { + gl.flags |= TextServer::GRAPHEME_IS_RTL; + } + + gl.font_rid = p_font; + gl.font_size = p_font_size; + + if (glyph_count > 0) { + if (p_sd->orientation == ORIENTATION_HORIZONTAL) { + gl.advance = glyph_pos[0].x_advance / (64.0 / fd->get_font_scale(p_font_size)); + } else { + gl.advance = -glyph_pos[0].y_advance / (64.0 / fd->get_font_scale(p_font_size)); + } + gl.count = 1; + + gl.index = glyph_info[0].codepoint; + gl.x_off = glyph_pos[0].x_offset / (64.0 / fd->get_font_scale(p_font_size)); + gl.y_off = -glyph_pos[0].y_offset / (64.0 / fd->get_font_scale(p_font_size)); + + if ((glyph_info[0].codepoint != 0) || !u_isgraph(p_char)) { + gl.flags |= GRAPHEME_IS_VALID; + } + } + return gl; +} + +void TextServerAdvanced::_shape_run(ShapedTextDataAdvanced *p_sd, int32_t p_start, int32_t p_end, hb_script_t p_script, hb_direction_t p_direction, Vector<RID> p_fonts, int p_span, int p_fb_index) { + FontDataAdvanced *fd = nullptr; + if (p_fb_index < p_fonts.size()) { + fd = font_owner.getornull(p_fonts[p_fb_index]); + } + + if (fd == nullptr) { + // Add fallback glyohs + for (int i = p_start; i < p_end; i++) { + if (p_sd->preserve_invalid || (p_sd->preserve_control && is_control(p_sd->text[i]))) { + TextServer::Glyph gl; + gl.start = i; + gl.end = i + 1; + gl.count = 1; + gl.index = p_sd->text[i]; + gl.font_size = p_sd->spans[p_span].font_size; + gl.font_rid = RID(); + gl.flags = 0; + if (p_direction == HB_DIRECTION_RTL || p_direction == HB_DIRECTION_BTT) { + gl.flags |= TextServer::GRAPHEME_IS_RTL; + } + if (p_sd->orientation == ORIENTATION_HORIZONTAL) { + gl.advance = get_hex_code_box_size(gl.font_size, gl.index).x; + p_sd->ascent = MAX(p_sd->ascent, get_hex_code_box_size(gl.font_size, gl.index).y * 0.75f); + p_sd->descent = MAX(p_sd->descent, get_hex_code_box_size(gl.font_size, gl.index).y * 0.25f); + } else { + gl.advance = get_hex_code_box_size(gl.font_size, gl.index).y; + p_sd->ascent = MAX(p_sd->ascent, get_hex_code_box_size(gl.font_size, gl.index).x * 0.5f); + p_sd->descent = MAX(p_sd->descent, get_hex_code_box_size(gl.font_size, gl.index).x * 0.5f); + } + p_sd->width += gl.advance; + + p_sd->glyphs.push_back(gl); + } + } + return; + } + + hb_font_t *hb_font = fd->get_hb_handle(p_sd->spans[p_span].font_size); + ERR_FAIL_COND(hb_font == nullptr); + + hb_buffer_clear_contents(p_sd->hb_buffer); + hb_buffer_set_direction(p_sd->hb_buffer, p_direction); + if (p_sd->preserve_control) { + hb_buffer_set_flags(p_sd->hb_buffer, (hb_buffer_flags_t)(HB_BUFFER_FLAG_PRESERVE_DEFAULT_IGNORABLES | (p_start == 0 ? HB_BUFFER_FLAG_BOT : 0) | (p_end == p_sd->text.length() ? HB_BUFFER_FLAG_EOT : 0))); + } else { + hb_buffer_set_flags(p_sd->hb_buffer, (hb_buffer_flags_t)(HB_BUFFER_FLAG_DEFAULT | (p_start == 0 ? HB_BUFFER_FLAG_BOT : 0) | (p_end == p_sd->text.length() ? HB_BUFFER_FLAG_EOT : 0))); + } + hb_buffer_set_script(p_sd->hb_buffer, p_script); + + if (p_sd->spans[p_span].language != String()) { + hb_language_t lang = hb_language_from_string(p_sd->spans[p_span].language.ascii().get_data(), -1); + hb_buffer_set_language(p_sd->hb_buffer, lang); + } + + hb_buffer_add_utf32(p_sd->hb_buffer, (const uint32_t *)p_sd->text.ptr(), p_sd->text.length(), p_start, p_end - p_start); + + Vector<hb_feature_t> ftrs; + for (const Variant *ftr = p_sd->spans[p_span].features.next(nullptr); ftr != nullptr; ftr = p_sd->spans[p_span].features.next(ftr)) { + double values = p_sd->spans[p_span].features[*ftr]; + if (values >= 0) { + hb_feature_t feature; + feature.tag = *ftr; + feature.value = values; + feature.start = 0; + feature.end = -1; + ftrs.push_back(feature); + } + } + hb_shape(hb_font, p_sd->hb_buffer, ftrs.empty() ? nullptr : &ftrs[0], ftrs.size()); + + unsigned int glyph_count = 0; + hb_glyph_info_t *glyph_info = hb_buffer_get_glyph_infos(p_sd->hb_buffer, &glyph_count); + hb_glyph_position_t *glyph_pos = hb_buffer_get_glyph_positions(p_sd->hb_buffer, &glyph_count); + + // Process glyphs. + if (glyph_count > 0) { + TextServer::Glyph *w = (TextServer::Glyph *)memalloc(glyph_count * sizeof(TextServer::Glyph)); + + int end = (p_direction == HB_DIRECTION_RTL || p_direction == HB_DIRECTION_BTT) ? p_end : 0; + uint32_t last_cluster_id = UINT32_MAX; + unsigned int last_cluster_index = 0; + bool last_cluster_valid = true; + + for (unsigned int i = 0; i < glyph_count; i++) { + if ((i > 0) && (last_cluster_id != glyph_info[i].cluster)) { + if (p_direction == HB_DIRECTION_RTL || p_direction == HB_DIRECTION_BTT) { + end = w[last_cluster_index].start; + } else { + for (unsigned int j = last_cluster_index; j < i; j++) { + w[j].end = glyph_info[i].cluster; + } + } + if (p_direction == HB_DIRECTION_RTL || p_direction == HB_DIRECTION_BTT) { + w[last_cluster_index].flags |= TextServer::GRAPHEME_IS_RTL; + } + if (last_cluster_valid) { + w[last_cluster_index].flags |= GRAPHEME_IS_VALID; + } + w[last_cluster_index].count = i - last_cluster_index; + last_cluster_index = i; + last_cluster_valid = true; + } + + last_cluster_id = glyph_info[i].cluster; + + TextServer::Glyph &gl = w[i]; + gl = TextServer::Glyph(); + + gl.start = glyph_info[i].cluster; + gl.end = end; + gl.count = 0; + + gl.font_rid = p_fonts[p_fb_index]; + gl.font_size = p_sd->spans[p_span].font_size; + + gl.index = glyph_info[i].codepoint; + if (gl.index != 0) { + if (p_sd->orientation == ORIENTATION_HORIZONTAL) { + gl.advance = glyph_pos[i].x_advance / (64.0 / fd->get_font_scale(gl.font_size)); + } else { + gl.advance = -glyph_pos[i].y_advance / (64.0 / fd->get_font_scale(gl.font_size)); + } + gl.x_off = glyph_pos[i].x_offset / (64.0 / fd->get_font_scale(gl.font_size)); + gl.y_off = -glyph_pos[i].y_offset / (64.0 / fd->get_font_scale(gl.font_size)); + } + + if (p_sd->preserve_control) { + last_cluster_valid = last_cluster_valid && ((glyph_info[i].codepoint != 0) || is_whitespace(p_sd->text[glyph_info[i].cluster]) || is_linebreak(p_sd->text[glyph_info[i].cluster])); + } else { + last_cluster_valid = last_cluster_valid && ((glyph_info[i].codepoint != 0) || !u_isgraph(p_sd->text[glyph_info[i].cluster])); + } + } + if (p_direction == HB_DIRECTION_LTR || p_direction == HB_DIRECTION_TTB) { + for (unsigned int j = last_cluster_index; j < glyph_count; j++) { + w[j].end = p_end; + } + } + w[last_cluster_index].count = glyph_count - last_cluster_index; + if (p_direction == HB_DIRECTION_RTL || p_direction == HB_DIRECTION_BTT) { + w[last_cluster_index].flags |= TextServer::GRAPHEME_IS_RTL; + } + if (last_cluster_valid) { + w[last_cluster_index].flags |= GRAPHEME_IS_VALID; + } + + //Fallback. + int failed_subrun_start = p_end + 1; + int failed_subrun_end = p_start; + + for (unsigned int i = 0; i < glyph_count; i++) { + if ((w[i].flags & GRAPHEME_IS_VALID) == GRAPHEME_IS_VALID) { + if (failed_subrun_start != p_end + 1) { + _shape_run(p_sd, failed_subrun_start, failed_subrun_end, p_script, p_direction, p_fonts, p_span, p_fb_index + 1); + failed_subrun_start = p_end + 1; + failed_subrun_end = p_start; + } + for (int j = 0; j < w[i].count; j++) { + if (p_sd->orientation == ORIENTATION_HORIZONTAL) { + p_sd->ascent = MAX(p_sd->ascent, MAX(fd->get_ascent(w[i + j].font_size), w[i + j].y_off)); + p_sd->descent = MAX(p_sd->descent, MAX(fd->get_descent(w[i + j].font_size), w[i + j].y_off)); + } else { + p_sd->ascent = MAX(p_sd->ascent, fd->get_advance(w[i + j].index, w[i + j].font_size).x * 0.5); + p_sd->descent = MAX(p_sd->descent, fd->get_advance(w[i + j].index, w[i + j].font_size).x * 0.5); + } + p_sd->upos = MAX(p_sd->upos, font_get_underline_position(w[i + j].font_rid, w[i + j].font_size)); + p_sd->uthk = MAX(p_sd->uthk, font_get_underline_thickness(w[i + j].font_rid, w[i + j].font_size)); + p_sd->width += w[i + j].advance; + p_sd->glyphs.push_back(w[i + j]); + } + } else { + if (failed_subrun_start >= w[i].start) { + failed_subrun_start = w[i].start; + } + if (failed_subrun_end <= w[i].end) { + failed_subrun_end = w[i].end; + } + } + i += w[i].count - 1; + } + memfree(w); + if (failed_subrun_start != p_end + 1) { + _shape_run(p_sd, failed_subrun_start, failed_subrun_end, p_script, p_direction, p_fonts, p_span, p_fb_index + 1); + } + } +} + +bool TextServerAdvanced::shaped_text_shape(RID p_shaped) { + _THREAD_SAFE_METHOD_ + ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, false); + + if (sd->valid) { + return true; + } + + if (sd->parent != RID()) { + full_copy(sd); + } + invalidate(sd); + + if (sd->text.length() == 0) { + sd->valid = true; + return true; + } + + sd->utf16 = sd->text.utf16(); + const UChar *data = sd->utf16.ptr(); + + // Create script iterator. + if (sd->script_iter == nullptr) { + sd->script_iter = memnew(ScriptIterator(sd->text, 0, sd->text.length())); + } + + if (sd->bidi_override.empty()) { + sd->bidi_override.push_back(Vector2i(0, sd->end)); + } + + for (int ov = 0; ov < sd->bidi_override.size(); ov++) { + // Create BiDi iterator. + int start = _convert_pos_inv(sd, sd->bidi_override[ov].x); + int end = _convert_pos_inv(sd, sd->bidi_override[ov].y); + + ERR_FAIL_COND_V_MSG((start < 0 || end - start > sd->utf16.length()), false, "Invalid BiDi override range."); + + UErrorCode err = U_ZERO_ERROR; + UBiDi *bidi_iter = ubidi_openSized(end, 0, &err); + ERR_FAIL_COND_V_MSG(U_FAILURE(err), false, u_errorName(err)); + + switch (sd->direction) { + case DIRECTION_LTR: { + ubidi_setPara(bidi_iter, data + start, end - start, UBIDI_LTR, nullptr, &err); + sd->para_direction = DIRECTION_LTR; + } break; + case DIRECTION_RTL: { + ubidi_setPara(bidi_iter, data + start, end - start, UBIDI_RTL, nullptr, &err); + sd->para_direction = DIRECTION_RTL; + } break; + case DIRECTION_AUTO: { + UBiDiDirection direction = ubidi_getBaseDirection(data + start, end - start); + if (direction != UBIDI_NEUTRAL) { + ubidi_setPara(bidi_iter, data + start, end - start, direction, nullptr, &err); + sd->para_direction = (direction == UBIDI_RTL) ? DIRECTION_RTL : DIRECTION_LTR; + } else { + ubidi_setPara(bidi_iter, data + start, end - start, UBIDI_DEFAULT_LTR, nullptr, &err); + sd->para_direction = DIRECTION_LTR; + } + } break; + } + ERR_FAIL_COND_V_MSG(U_FAILURE(err), false, u_errorName(err)); + sd->bidi_iter.push_back(bidi_iter); + + err = U_ZERO_ERROR; + int bidi_run_count = ubidi_countRuns(bidi_iter, &err); + ERR_FAIL_COND_V_MSG(U_FAILURE(err), false, u_errorName(err)); + for (int i = 0; i < bidi_run_count; i++) { + int32_t _bidi_run_start = 0; + int32_t _bidi_run_length = 0; + hb_direction_t bidi_run_direction = HB_DIRECTION_INVALID; + bool is_rtl = (ubidi_getVisualRun(bidi_iter, i, &_bidi_run_start, &_bidi_run_length) == UBIDI_LTR); + switch (sd->orientation) { + case ORIENTATION_HORIZONTAL: { + if (is_rtl) { + bidi_run_direction = HB_DIRECTION_LTR; + } else { + bidi_run_direction = HB_DIRECTION_RTL; + } + } break; + case ORIENTATION_VERTICAL: { + if (is_rtl) { + bidi_run_direction = HB_DIRECTION_TTB; + } else { + bidi_run_direction = HB_DIRECTION_BTT; + } + } + } + + int32_t bidi_run_start = _convert_pos(sd, sd->bidi_override[ov].x + _bidi_run_start); + int32_t bidi_run_end = _convert_pos(sd, sd->bidi_override[ov].x + _bidi_run_start + _bidi_run_length); + + // Shape runs. + + int scr_from = (is_rtl) ? 0 : sd->script_iter->script_ranges.size() - 1; + int scr_to = (is_rtl) ? sd->script_iter->script_ranges.size() : -1; + int scr_delta = (is_rtl) ? +1 : -1; + + for (int j = scr_from; j != scr_to; j += scr_delta) { + if ((sd->script_iter->script_ranges[j].start < bidi_run_end) && (sd->script_iter->script_ranges[j].end > bidi_run_start)) { + int32_t script_run_start = MAX(sd->script_iter->script_ranges[j].start, bidi_run_start); + int32_t script_run_end = MIN(sd->script_iter->script_ranges[j].end, bidi_run_end); + char scr_buffer[5] = { 0, 0, 0, 0, 0 }; + hb_tag_to_string(hb_script_to_iso15924_tag(sd->script_iter->script_ranges[j].script), scr_buffer); + String script = String(scr_buffer); + + int spn_from = (is_rtl) ? 0 : sd->spans.size() - 1; + int spn_to = (is_rtl) ? sd->spans.size() : -1; + int spn_delta = (is_rtl) ? +1 : -1; + + for (int k = spn_from; k != spn_to; k += spn_delta) { + const ShapedTextDataAdvanced::Span &span = sd->spans[k]; + if (span.start >= script_run_end || span.end <= script_run_start) { + continue; + } + if (span.embedded_key != Variant()) { + // Embedded object. + if (sd->orientation == ORIENTATION_HORIZONTAL) { + sd->objects[span.embedded_key].rect.position.x = sd->width; + sd->width += sd->objects[span.embedded_key].rect.size.x; + switch (sd->objects[span.embedded_key].inline_align) { + case VALIGN_TOP: { + sd->ascent = MAX(sd->ascent, sd->objects[span.embedded_key].rect.size.y); + } break; + case VALIGN_CENTER: { + sd->ascent = MAX(sd->ascent, sd->objects[span.embedded_key].rect.size.y / 2); + sd->descent = MAX(sd->descent, sd->objects[span.embedded_key].rect.size.y / 2); + } break; + case VALIGN_BOTTOM: { + sd->descent = MAX(sd->descent, sd->objects[span.embedded_key].rect.size.y); + } break; + } + } else { + sd->objects[span.embedded_key].rect.position.y = sd->width; + sd->width += sd->objects[span.embedded_key].rect.size.y; + switch (sd->objects[span.embedded_key].inline_align) { + case VALIGN_TOP: { + sd->ascent = MAX(sd->ascent, sd->objects[span.embedded_key].rect.size.x); + } break; + case VALIGN_CENTER: { + sd->ascent = MAX(sd->ascent, sd->objects[span.embedded_key].rect.size.x / 2); + sd->descent = MAX(sd->descent, sd->objects[span.embedded_key].rect.size.x / 2); + } break; + case VALIGN_BOTTOM: { + sd->descent = MAX(sd->descent, sd->objects[span.embedded_key].rect.size.x); + } break; + } + } + Glyph gl; + gl.start = span.start; + gl.end = span.end; + gl.count = 1; + gl.index = 0; + gl.flags = GRAPHEME_IS_VALID | GRAPHEME_IS_VIRTUAL; + if (sd->orientation == ORIENTATION_HORIZONTAL) { + gl.advance = sd->objects[span.embedded_key].rect.size.x; + } else { + gl.advance = sd->objects[span.embedded_key].rect.size.y; + } + sd->glyphs.push_back(gl); + } else { + Vector<RID> fonts; + // Push fonts with the language and script support first. + for (int l = 0; l < span.fonts.size(); l++) { + if ((font_is_language_supported(span.fonts[l], span.language)) && (font_is_script_supported(span.fonts[l], script))) { + fonts.push_back(sd->spans[k].fonts[l]); + } + } + // Push fonts with the script support. + for (int l = 0; l < sd->spans[k].fonts.size(); l++) { + if (!(font_is_language_supported(span.fonts[l], span.language)) && (font_is_script_supported(span.fonts[l], script))) { + fonts.push_back(sd->spans[k].fonts[l]); + } + } + // Push the rest valid fonts. + for (int l = 0; l < sd->spans[k].fonts.size(); l++) { + if (!(font_is_language_supported(span.fonts[l], span.language)) && !(font_is_script_supported(span.fonts[l], script))) { + fonts.push_back(sd->spans[k].fonts[l]); + } + } + _shape_run(sd, MAX(sd->spans[k].start, script_run_start), MIN(sd->spans[k].end, script_run_end), sd->script_iter->script_ranges[j].script, bidi_run_direction, fonts, k, 0); + } + } + } + } + } + } + + // Align embedded objects to baseline. + for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = sd->objects.front(); E; E = E->next()) { + if (sd->orientation == ORIENTATION_HORIZONTAL) { + switch (E->get().inline_align) { + case VALIGN_TOP: { + E->get().rect.position.y = -sd->ascent; + } break; + case VALIGN_CENTER: { + E->get().rect.position.y = -(E->get().rect.size.y / 2); + } break; + case VALIGN_BOTTOM: { + E->get().rect.position.y = sd->descent - E->get().rect.size.y; + } break; + } + } else { + switch (E->get().inline_align) { + case VALIGN_TOP: { + E->get().rect.position.x = -sd->ascent; + } break; + case VALIGN_CENTER: { + E->get().rect.position.x = -(E->get().rect.size.x / 2); + } break; + case VALIGN_BOTTOM: { + E->get().rect.position.x = sd->descent - E->get().rect.size.x; + } break; + } + } + } + + sd->valid = true; + return sd->valid; +} + +bool TextServerAdvanced::shaped_text_is_ready(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, false); + return sd->valid; +} + +Vector<TextServer::Glyph> TextServerAdvanced::shaped_text_get_glyphs(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, Vector<TextServer::Glyph>()); + if (!sd->valid) { + const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + } + return sd->glyphs; +} + +Vector2i TextServerAdvanced::shaped_text_get_range(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, Vector2i()); + return Vector2(sd->start, sd->end); +} + +Vector<TextServer::Glyph> TextServerAdvanced::shaped_text_sort_logical(RID p_shaped) { + _THREAD_SAFE_METHOD_ + ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, Vector<TextServer::Glyph>()); + if (!sd->valid) { + const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + } + + if (!sd->sort_valid) { + sd->glyphs_logical = sd->glyphs; + sd->glyphs_logical.sort_custom<TextServer::GlyphCompare>(); + sd->sort_valid = true; + } + + return sd->glyphs_logical; +} + +Array TextServerAdvanced::shaped_text_get_objects(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + Array ret; + const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, ret); + for (const Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = sd->objects.front(); E; E = E->next()) { + ret.push_back(E->key()); + } + + return ret; +} + +Rect2 TextServerAdvanced::shaped_text_get_object_rect(RID p_shaped, Variant p_key) const { + _THREAD_SAFE_METHOD_ + const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, Rect2()); + ERR_FAIL_COND_V(!sd->objects.has(p_key), Rect2()); + if (!sd->valid) { + const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + } + return sd->objects[p_key].rect; +} + +Size2 TextServerAdvanced::shaped_text_get_size(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, Size2()); + if (!sd->valid) { + const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + } + if (sd->orientation == TextServer::ORIENTATION_HORIZONTAL) { + return Size2(sd->width, sd->ascent + sd->descent); + } else { + return Size2(sd->ascent + sd->descent, sd->width); + } +} + +float TextServerAdvanced::shaped_text_get_ascent(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, 0.f); + if (!sd->valid) { + const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + } + return sd->ascent; +} + +float TextServerAdvanced::shaped_text_get_descent(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, 0.f); + if (!sd->valid) { + const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + } + return sd->descent; +} + +float TextServerAdvanced::shaped_text_get_width(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, 0.f); + if (!sd->valid) { + const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + } + return sd->width; +} + +float TextServerAdvanced::shaped_text_get_underline_position(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, 0.f); + if (!sd->valid) { + const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + } + + return sd->upos; +} + +float TextServerAdvanced::shaped_text_get_underline_thickness(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, 0.f); + if (!sd->valid) { + const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + } + + return sd->uthk; +} + +struct num_system_data { + String lang; + String digits; + String percent_sign; + String exp; +}; + +static num_system_data num_systems[]{ + { "ar,ar_AR,ar_BH,ar_DJ,ar_EG,ar_ER,ar_IL,ar_IQ,ar_JO,ar_KM,ar_KW,ar_LB,ar_MR,ar_OM,ar_PS,ar_QA,ar_SA,ar_SD,ar_SO,ar_SS,ar_SY,ar_TD,ar_YE", U"٠١٢٣٤٥٦٧٨٩٫", U"٪", U"اس" }, + { "fa,ks,pa_Arab,ps,ug,ur_IN,ur,uz_Arab", U"۰۱۲۳۴۵۶۷۸۹٫", U"٪", U"اس" }, + { "as,bn,mni", U"০১২৩৪৫৬৭৮৯.", U"%", U"e" }, + { "mr,ne", U"०१२३४५६७८९.", U"%", U"e" }, + { "dz", U"༠༡༢༣༤༥༦༧༨༩.", U"%", U"e" }, + { "sat", U"᱐᱑᱒᱓᱔᱕᱖᱗᱘᱙.", U"%", U"e" }, + { "my", U"၀၁၂၃၄၅၆၇၈၉.", U"%", U"e" }, + { String(), String(), String(), String() }, +}; + +String TextServerAdvanced::format_number(const String &p_string, const String &p_language) const { + _THREAD_SAFE_METHOD_ + String lang = (p_language == "") ? TranslationServer::get_singleton()->get_tool_locale() : p_language; + + String res = p_string; + for (int i = 0; num_systems[i].lang != String(); i++) { + Vector<String> langs = num_systems[i].lang.split(","); + if (langs.has(lang)) { + if (num_systems[i].digits == String()) { + return p_string; + } + res.replace("e", num_systems[i].exp); + res.replace("E", num_systems[i].exp); + char32_t *data = res.ptrw(); + for (int j = 0; j < res.size(); j++) { + if (data[j] >= 0x30 && data[j] <= 0x39) { + data[j] = num_systems[i].digits[data[j] - 0x30]; + } else if (data[j] == '.' || data[j] == ',') { + data[j] = num_systems[i].digits[10]; + } + } + break; + } + } + return res; +} + +String TextServerAdvanced::parse_number(const String &p_string, const String &p_language) const { + _THREAD_SAFE_METHOD_ + String lang = (p_language == "") ? TranslationServer::get_singleton()->get_tool_locale() : p_language; + + String res = p_string; + for (int i = 0; num_systems[i].lang != String(); i++) { + Vector<String> langs = num_systems[i].lang.split(","); + if (langs.has(lang)) { + if (num_systems[i].digits == String()) { + return p_string; + } + res.replace(num_systems[i].exp, "e"); + char32_t *data = res.ptrw(); + for (int j = 0; j < res.size(); j++) { + if (data[j] == num_systems[i].digits[10]) { + data[j] = '.'; + } else { + for (int k = 0; k < 10; k++) { + if (data[j] == num_systems[i].digits[k]) { + data[j] = 0x30 + k; + } + } + } + } + break; + } + } + return res; +} + +String TextServerAdvanced::percent_sign(const String &p_language) const { + _THREAD_SAFE_METHOD_ + String lang = (p_language == "") ? TranslationServer::get_singleton()->get_tool_locale() : p_language; + + for (int i = 0; num_systems[i].lang != String(); i++) { + Vector<String> langs = num_systems[i].lang.split(","); + if (langs.has(lang)) { + if (num_systems[i].percent_sign == String()) { + return "%"; + } + return num_systems[i].percent_sign; + } + } + return "%"; +} + +TextServer *TextServerAdvanced::create_func(Error &r_error, void *p_user_data) { + r_error = OK; + return memnew(TextServerAdvanced()); +} + +void TextServerAdvanced::register_server() { + TextServerManager::register_create_function(interface_name, interface_features, create_func, nullptr); +} + +TextServerAdvanced::TextServerAdvanced() { +} + +TextServerAdvanced::~TextServerAdvanced() { + u_cleanup(); +#ifndef ICU_STATIC_DATA + if (icu_data != nullptr) { + memfree(icu_data); + icu_data = nullptr; + } +#endif +} diff --git a/modules/text_server_adv/text_server_adv.h b/modules/text_server_adv/text_server_adv.h new file mode 100644 index 0000000000..f26b87f67e --- /dev/null +++ b/modules/text_server_adv/text_server_adv.h @@ -0,0 +1,244 @@ +/*************************************************************************/ +/* text_server_adv.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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. */ +/*************************************************************************/ + +#ifndef TEXT_SERVER_ADV_H +#define TEXT_SERVER_ADV_H + +/*************************************************************************/ +/* ICU/HarfBuzz/Graphite backed Text Server implementation with BiDi, */ +/* shaping and advanced font features support. */ +/*************************************************************************/ + +#include "servers/text_server.h" + +#include "core/templates/rid_owner.h" +#include "scene/resources/texture.h" +#include "script_iterator.h" + +#include <unicode/ubidi.h> +#include <unicode/ubrk.h> +#include <unicode/uchar.h> +#include <unicode/uclean.h> +#include <unicode/udata.h> +#include <unicode/uiter.h> +#include <unicode/uloc.h> +#include <unicode/uscript.h> +#include <unicode/ustring.h> +#include <unicode/utypes.h> + +#include <hb-icu.h> +#include <hb.h> + +#include "font_adv.h" + +class TextServerAdvanced : public TextServer { + GDCLASS(TextServerAdvanced, TextServer); + _THREAD_SAFE_CLASS_ + + static String interface_name; + static uint32_t interface_features; + + uint8_t *icu_data = nullptr; + + struct ShapedTextDataAdvanced : public ShapedTextData { + /* Intermediate data */ + Char16String utf16; + Vector<UBiDi *> bidi_iter; + Vector<Vector2i> bidi_override; + ScriptIterator *script_iter = nullptr; + hb_buffer_t *hb_buffer = nullptr; + + ~ShapedTextDataAdvanced() { + for (int i = 0; i < bidi_iter.size(); i++) { + ubidi_close(bidi_iter[i]); + } + if (script_iter) { + memdelete(script_iter); + } + if (hb_buffer) { + hb_buffer_destroy(hb_buffer); + } + } + }; + + float oversampling = 1.f; + mutable RID_PtrOwner<FontDataAdvanced> font_owner; + mutable RID_PtrOwner<ShapedTextDataAdvanced> shaped_owner; + + int _convert_pos(const ShapedTextDataAdvanced *p_sd, int p_pos) const; + int _convert_pos_inv(const ShapedTextDataAdvanced *p_sd, int p_pos) const; + void _shape_run(ShapedTextDataAdvanced *p_sd, int32_t p_start, int32_t p_end, hb_script_t p_script, hb_direction_t p_direction, Vector<RID> p_fonts, int p_span, int p_fb_index); + TextServer::Glyph _shape_single_glyph(ShapedTextDataAdvanced *p_sd, char32_t p_char, hb_script_t p_script, hb_direction_t p_direction, RID p_font, int p_font_size); + +protected: + static void _bind_methods(){}; + + void full_copy(ShapedTextDataAdvanced *p_shaped); + void invalidate(ShapedTextDataAdvanced *p_shaped); + +public: + virtual bool has_feature(Feature p_feature) override; + virtual String get_name() const override; + + virtual void free(RID p_rid) override; + virtual bool has(RID p_rid) override; + virtual bool load_support_data(const String &p_filename) override; + +#ifdef TOOLS_ENABLED + virtual String get_support_data_filename() override { return _MKSTR(ICU_DATA_NAME); }; + virtual String get_support_data_info() override { return String("ICU break iteration data (") + _MKSTR(ICU_DATA_NAME) + String(")."); }; + virtual bool save_support_data(const String &p_filename) override; +#endif + + virtual bool is_locale_right_to_left(const String &p_locale) override; + + virtual int32_t name_to_tag(const String &p_name) override; + virtual String tag_to_name(int32_t p_tag) override; + + /* Font interface */ + virtual RID create_font_system(const String &p_name, int p_base_size = 16) override; + virtual RID create_font_resource(const String &p_filename, int p_base_size = 16) override; + virtual RID create_font_memory(const uint8_t *p_data, size_t p_size, const String &p_type, int p_base_size = 16) override; + + virtual float font_get_height(RID p_font, int p_size) const override; + virtual float font_get_ascent(RID p_font, int p_size) const override; + virtual float font_get_descent(RID p_font, int p_size) const override; + + virtual float font_get_underline_position(RID p_font, int p_size) const override; + virtual float font_get_underline_thickness(RID p_font, int p_size) const override; + + virtual void font_set_antialiased(RID p_font, bool p_antialiased) override; + virtual bool font_get_antialiased(RID p_font) const override; + + virtual Dictionary font_get_feature_list(RID p_font) const override; + + virtual void font_set_hinting(RID p_font, Hinting p_hinting) override; + virtual Hinting font_get_hinting(RID p_font) const override; + + virtual void font_set_distance_field_hint(RID p_font, bool p_distance_field) override; + virtual bool font_get_distance_field_hint(RID p_font) const override; + + virtual void font_set_force_autohinter(RID p_font, bool p_enabeld) override; + virtual bool font_get_force_autohinter(RID p_font) const override; + + virtual bool font_has_char(RID p_font, char32_t p_char) const override; + virtual String font_get_supported_chars(RID p_font) const override; + + virtual bool font_has_outline(RID p_font) const override; + virtual float font_get_base_size(RID p_font) const override; + + virtual bool font_is_language_supported(RID p_font, const String &p_language) const override; + virtual void font_set_language_support_override(RID p_font, const String &p_language, bool p_supported) override; + virtual bool font_get_language_support_override(RID p_font, const String &p_language) override; + virtual void font_remove_language_support_override(RID p_font, const String &p_language) override; + Vector<String> font_get_language_support_overrides(RID p_font) override; + + virtual bool font_is_script_supported(RID p_font, const String &p_script) const override; + virtual void font_set_script_support_override(RID p_font, const String &p_script, bool p_supported) override; + virtual bool font_get_script_support_override(RID p_font, const String &p_script) override; + virtual void font_remove_script_support_override(RID p_font, const String &p_script) override; + Vector<String> font_get_script_support_overrides(RID p_font) override; + + virtual uint32_t font_get_glyph_index(RID p_font, char32_t p_char, char32_t p_variation_selector = 0x0000) const override; + virtual Vector2 font_get_glyph_advance(RID p_font, uint32_t p_index, int p_size) const override; + virtual Vector2 font_get_glyph_kerning(RID p_font, uint32_t p_index_a, uint32_t p_index_b, int p_size) const override; + + virtual Vector2 font_draw_glyph(RID p_font, RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color = Color(1, 1, 1)) const override; + virtual Vector2 font_draw_glyph_outline(RID p_font, RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color = Color(1, 1, 1)) const override; + + virtual float font_get_oversampling() const override; + virtual void font_set_oversampling(float p_oversampling) override; + + virtual Vector<String> get_system_fonts() const override; + + /* Shaped text buffer interface */ + + virtual RID create_shaped_text(Direction p_direction = DIRECTION_AUTO, Orientation p_orientation = ORIENTATION_HORIZONTAL) override; + + virtual void shaped_text_clear(RID p_shaped) override; + + virtual void shaped_text_set_direction(RID p_shaped, Direction p_direction = DIRECTION_AUTO) override; + virtual Direction shaped_text_get_direction(RID p_shaped) const override; + + virtual void shaped_text_set_bidi_override(RID p_shaped, const Vector<Vector2i> &p_override) override; + + virtual void shaped_text_set_orientation(RID p_shaped, Orientation p_orientation = ORIENTATION_HORIZONTAL) override; + virtual Orientation shaped_text_get_orientation(RID p_shaped) const override; + + virtual void shaped_text_set_preserve_invalid(RID p_shaped, bool p_enabled) override; + virtual bool shaped_text_get_preserve_invalid(RID p_shaped) const override; + + virtual void shaped_text_set_preserve_control(RID p_shaped, bool p_enabled) override; + virtual bool shaped_text_get_preserve_control(RID p_shaped) const override; + + virtual bool shaped_text_add_string(RID p_shaped, const String &p_text, const Vector<RID> &p_fonts, int p_size, const Dictionary &p_opentype_features = Dictionary(), const String &p_language = "") override; + virtual bool shaped_text_add_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align = VALIGN_CENTER, int p_length = 1) override; + virtual bool shaped_text_resize_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align = VALIGN_CENTER) override; + + virtual RID shaped_text_substr(RID p_shaped, int p_start, int p_length) const override; + virtual RID shaped_text_get_parent(RID p_shaped) const override; + + virtual float shaped_text_fit_to_width(RID p_shaped, float p_width, uint8_t /*JustificationFlag*/ p_jst_flags = JUSTIFICATION_WORD_BOUND | JUSTIFICATION_KASHIDA) override; + virtual float shaped_text_tab_align(RID p_shaped, const Vector<float> &p_tab_stops) override; + + virtual bool shaped_text_shape(RID p_shaped) override; + virtual bool shaped_text_update_breaks(RID p_shaped) override; + virtual bool shaped_text_update_justification_ops(RID p_shaped) override; + + virtual bool shaped_text_is_ready(RID p_shaped) const override; + + virtual Vector<Glyph> shaped_text_get_glyphs(RID p_shaped) const override; + + virtual Vector2i shaped_text_get_range(RID p_shaped) const override; + + virtual Vector<Glyph> shaped_text_sort_logical(RID p_shaped) override; + + virtual Array shaped_text_get_objects(RID p_shaped) const override; + virtual Rect2 shaped_text_get_object_rect(RID p_shaped, Variant p_key) const override; + + virtual Size2 shaped_text_get_size(RID p_shaped) const override; + virtual float shaped_text_get_ascent(RID p_shaped) const override; + virtual float shaped_text_get_descent(RID p_shaped) const override; + virtual float shaped_text_get_width(RID p_shaped) const override; + virtual float shaped_text_get_underline_position(RID p_shaped) const override; + virtual float shaped_text_get_underline_thickness(RID p_shaped) const override; + + virtual String format_number(const String &p_string, const String &p_language = "") const override; + virtual String parse_number(const String &p_string, const String &p_language = "") const override; + virtual String percent_sign(const String &p_language = "") const override; + + static TextServer *create_func(Error &r_error, void *p_user_data); + static void register_server(); + + TextServerAdvanced(); + ~TextServerAdvanced(); +}; + +#endif // TEXT_SERVER_ADV_H diff --git a/modules/text_server_fb/SCsub b/modules/text_server_fb/SCsub new file mode 100644 index 0000000000..7650e27063 --- /dev/null +++ b/modules/text_server_fb/SCsub @@ -0,0 +1,12 @@ +#!/usr/bin/env python + +Import("env") +Import("env_modules") + +env_text_server_fb = env_modules.Clone() +env_text_server_fb.Append( + CPPPATH=[ + "#thirdparty/freetype/include", + ] +) +env_text_server_fb.add_source_files(env.modules_sources, "*.cpp") diff --git a/modules/text_server_fb/bitmap_font_fb.cpp b/modules/text_server_fb/bitmap_font_fb.cpp new file mode 100644 index 0000000000..5ab8edbd71 --- /dev/null +++ b/modules/text_server_fb/bitmap_font_fb.cpp @@ -0,0 +1,357 @@ +/*************************************************************************/ +/* bitmap_font_fb.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 "bitmap_font_fb.h" + +Error BitmapFontDataFallback::load_from_file(const String &p_filename, int p_base_size) { + _THREAD_SAFE_METHOD_ + //fnt format used by angelcode bmfont + //http://www.angelcode.com/products/bmfont/ + + FileAccess *f = FileAccess::open(p_filename, FileAccess::READ); + ERR_FAIL_COND_V_MSG(!f, ERR_FILE_NOT_FOUND, "Can't open font: " + p_filename + "."); + + while (true) { + String line = f->get_line(); + + int delimiter = line.find(" "); + String type = line.substr(0, delimiter); + int pos = delimiter + 1; + Map<String, String> keys; + + while (pos < line.size() && line[pos] == ' ') { + pos++; + } + + while (pos < line.size()) { + int eq = line.find("=", pos); + if (eq == -1) { + break; + } + String key = line.substr(pos, eq - pos); + int end = -1; + String value; + if (line[eq + 1] == '"') { + end = line.find("\"", eq + 2); + if (end == -1) { + break; + } + value = line.substr(eq + 2, end - 1 - eq - 1); + pos = end + 1; + } else { + end = line.find(" ", eq + 1); + if (end == -1) { + end = line.size(); + } + value = line.substr(eq + 1, end - eq); + pos = end; + } + + while (pos < line.size() && line[pos] == ' ') { + pos++; + } + + keys[key] = value; + } + + if (type == "info") { + if (keys.has("size")) { + base_size = keys["size"].to_int(); + } + } else if (type == "common") { + if (keys.has("lineHeight")) { + height = keys["lineHeight"].to_int(); + } + if (keys.has("base")) { + ascent = keys["base"].to_int(); + } + } else if (type == "page") { + if (keys.has("file")) { + String base_dir = p_filename.get_base_dir(); + String file = base_dir.plus_file(keys["file"]); + if (RenderingServer::get_singleton() != nullptr) { + Ref<Texture2D> tex = ResourceLoader::load(file); + if (tex.is_null()) { + ERR_PRINT("Can't load font texture!"); + } else { + ERR_FAIL_COND_V_MSG(tex.is_null(), ERR_FILE_CANT_READ, "It's not a reference to a valid Texture object."); + textures.push_back(tex); + } + } + } + } else if (type == "char") { + Character c; + char32_t idx = 0; + if (keys.has("id")) { + idx = keys["id"].to_int(); + } + if (keys.has("x")) { + c.rect.position.x = keys["x"].to_int(); + } + if (keys.has("y")) { + c.rect.position.y = keys["y"].to_int(); + } + if (keys.has("width")) { + c.rect.size.width = keys["width"].to_int(); + } + if (keys.has("height")) { + c.rect.size.height = keys["height"].to_int(); + } + if (keys.has("xoffset")) { + c.align.x = keys["xoffset"].to_int(); + } + if (keys.has("yoffset")) { + c.align.y = keys["yoffset"].to_int(); + } + if (keys.has("page")) { + c.texture_idx = keys["page"].to_int(); + } + if (keys.has("xadvance")) { + c.advance.x = keys["xadvance"].to_int(); + } + if (keys.has("yadvance")) { + c.advance.y = keys["yadvance"].to_int(); + } + if (c.advance.x < 0) { + c.advance.x = c.rect.size.width + 1; + } + if (c.advance.y < 0) { + c.advance.y = c.rect.size.height + 1; + } + char_map[idx] = c; + } else if (type == "kerning") { + KerningPairKey kpk; + float k = 0; + if (keys.has("first")) { + kpk.A = keys["first"].to_int(); + } + if (keys.has("second")) { + kpk.B = keys["second"].to_int(); + } + if (keys.has("amount")) { + k = keys["amount"].to_int(); + } + kerning_map[kpk] = k; + } + + if (f->eof_reached()) { + break; + } + } + if (base_size == 0) { + base_size = height; + } + + valid = true; + + memdelete(f); + return OK; +} + +Error BitmapFontDataFallback::load_from_memory(const uint8_t *p_data, size_t p_size, int p_base_size) { + _THREAD_SAFE_METHOD_ + ERR_FAIL_COND_V(p_data == nullptr, ERR_CANT_CREATE); + ERR_FAIL_COND_V(p_size != sizeof(TextServer::BitmapFontData), ERR_CANT_CREATE); + + const TextServer::BitmapFontData *data = (const TextServer::BitmapFontData *)p_data; + + if (RenderingServer::get_singleton() != nullptr) { + Ref<Image> image = memnew(Image(data->img)); + Ref<ImageTexture> tex = memnew(ImageTexture); + tex->create_from_image(image); + + textures.push_back(tex); + } + + for (int i = 0; i < data->charcount; i++) { + const int *c = &data->char_rects[i * 8]; + + Character chr; + chr.rect.position.x = c[1]; + chr.rect.position.y = c[2]; + chr.rect.size.x = c[3]; + chr.rect.size.y = c[4]; + chr.texture_idx = 0; + if (c[7] < 0) { + chr.advance.x = c[3]; + } else { + chr.advance.x = c[7]; + } + chr.align = Vector2(c[6], c[5]); + char_map[c[0]] = chr; + } + + for (int i = 0; i < data->kerning_count; i++) { + KerningPairKey kpk; + kpk.A = data->kernings[i * 3 + 0]; + kpk.B = data->kernings[i * 3 + 1]; + + if (data->kernings[i * 3 + 2] == 0 && kerning_map.has(kpk)) { + kerning_map.erase(kpk); + } else { + kerning_map[kpk] = data->kernings[i * 3 + 2]; + } + } + + height = data->height; + ascent = data->ascent; + + base_size = p_base_size; + if (base_size == 0) { + base_size = height; + } + + valid = true; + + return OK; +} + +float BitmapFontDataFallback::get_height(int p_size) const { + ERR_FAIL_COND_V(!valid, 0.f); + return height * (float(p_size) / float(base_size)); +} + +float BitmapFontDataFallback::get_ascent(int p_size) const { + ERR_FAIL_COND_V(!valid, 0.f); + return ascent * (float(p_size) / float(base_size)); +} + +float BitmapFontDataFallback::get_descent(int p_size) const { + ERR_FAIL_COND_V(!valid, 0.f); + return (height - ascent) * (float(p_size) / float(base_size)); +} + +float BitmapFontDataFallback::get_underline_position(int p_size) const { + ERR_FAIL_COND_V(!valid, 0.f); + return 2 * (float(p_size) / float(base_size)); +} + +float BitmapFontDataFallback::get_underline_thickness(int p_size) const { + ERR_FAIL_COND_V(!valid, 0.f); + return 1 * (float(p_size) / float(base_size)); +} + +void BitmapFontDataFallback::set_distance_field_hint(bool p_distance_field) { + distance_field_hint = p_distance_field; +} + +bool BitmapFontDataFallback::get_distance_field_hint() const { + return distance_field_hint; +} + +float BitmapFontDataFallback::get_base_size() const { + return base_size; +} + +bool BitmapFontDataFallback::has_char(char32_t p_char) const { + _THREAD_SAFE_METHOD_ + ERR_FAIL_COND_V(!valid, false); + return char_map.has(p_char); +} + +String BitmapFontDataFallback::get_supported_chars() const { + _THREAD_SAFE_METHOD_ + ERR_FAIL_COND_V(!valid, String()); + String chars; + const char32_t *k = nullptr; + while ((k = char_map.next(k))) { + chars += char32_t(*k); + } + return chars; +} + +Vector2 BitmapFontDataFallback::get_advance(char32_t p_char, int p_size) const { + _THREAD_SAFE_METHOD_ + ERR_FAIL_COND_V(!valid, Vector2()); + const Character *c = char_map.getptr(p_char); + ERR_FAIL_COND_V(c == nullptr, Vector2()); + + return c->advance * (float(p_size) / float(base_size)); +} + +Vector2 BitmapFontDataFallback::get_kerning(char32_t p_char, char32_t p_next, int p_size) const { + _THREAD_SAFE_METHOD_ + ERR_FAIL_COND_V(!valid, Vector2()); + KerningPairKey kpk; + kpk.A = p_char; + kpk.B = p_next; + + const Map<KerningPairKey, int>::Element *E = kerning_map.find(kpk); + if (E) { + return Vector2(-E->get() * (float(p_size) / float(base_size)), 0); + } else { + return Vector2(); + } +} + +Vector2 BitmapFontDataFallback::draw_glyph(RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const { + _THREAD_SAFE_METHOD_ + if (p_index == 0) { + return Vector2(); + } + ERR_FAIL_COND_V(!valid, Vector2()); + const Character *c = char_map.getptr(p_index); + + ERR_FAIL_COND_V(c == nullptr, Vector2()); + ERR_FAIL_COND_V(c->texture_idx < -1 || c->texture_idx >= textures.size(), Vector2()); + if (c->texture_idx != -1) { + Point2 cpos = p_pos; + cpos += c->align * (float(p_size) / float(base_size)); + cpos.y -= ascent * (float(p_size) / float(base_size)); + + if (RenderingServer::get_singleton() != nullptr) { + //if (distance_field_hint) { // Not implemented. + // RenderingServer::get_singleton()->canvas_item_set_distance_field_mode(p_canvas, true); + //} + RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, Rect2(cpos, c->rect.size * (float(p_size) / float(base_size))), textures[c->texture_idx]->get_rid(), c->rect, p_color, false, false); + //if (distance_field_hint) { + // RenderingServer::get_singleton()->canvas_item_set_distance_field_mode(p_canvas, false); + //} + } + } + + return c->advance * (float(p_size) / float(base_size)); +} + +Vector2 BitmapFontDataFallback::draw_glyph_outline(RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const { + _THREAD_SAFE_METHOD_ + if (p_index == 0) { + return Vector2(); + } + ERR_FAIL_COND_V(!valid, Vector2()); + const Character *c = char_map.getptr(p_index); + + ERR_FAIL_COND_V(c == nullptr, Vector2()); + ERR_FAIL_COND_V(c->texture_idx < -1 || c->texture_idx >= textures.size(), Vector2()); + + // Not supported, return advance for compatibility. + + return c->advance * (float(p_size) / float(base_size)); +} diff --git a/modules/text_server_fb/bitmap_font_fb.h b/modules/text_server_fb/bitmap_font_fb.h new file mode 100644 index 0000000000..73e6d8f791 --- /dev/null +++ b/modules/text_server_fb/bitmap_font_fb.h @@ -0,0 +1,107 @@ +/*************************************************************************/ +/* bitmap_font_fb.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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. */ +/*************************************************************************/ + +#ifndef BITMAP_FONT_FALLBACK_H +#define BITMAP_FONT_FALLBACK_H + +#include "font_fb.h" + +struct BitmapFontDataFallback : public FontDataFallback { + _THREAD_SAFE_CLASS_ + +private: + Vector<Ref<Texture2D>> textures; + + struct Character { + int texture_idx = 0; + Rect2 rect; + Vector2 align; + Vector2 advance = Vector2(-1, -1); + }; + + struct KerningPairKey { + union { + struct { + uint32_t A, B; + }; + + uint64_t pair = 0; + }; + + _FORCE_INLINE_ bool operator<(const KerningPairKey &p_r) const { return pair < p_r.pair; } + }; + + HashMap<char32_t, Character> char_map; + Map<KerningPairKey, int> kerning_map; + + float height = 0.f; + float ascent = 0.f; + int base_size = 0; + bool distance_field_hint = false; + +public: + virtual void clear_cache() override{}; + + virtual Error load_from_file(const String &p_filename, int p_base_size) override; + virtual Error load_from_memory(const uint8_t *p_data, size_t p_size, int p_base_size) override; + + virtual float get_height(int p_size) const override; + virtual float get_ascent(int p_size) const override; + virtual float get_descent(int p_size) const override; + + virtual float get_underline_position(int p_size) const override; + virtual float get_underline_thickness(int p_size) const override; + + virtual void set_antialiased(bool p_antialiased) override{}; + virtual bool get_antialiased() const override { return false; }; + + virtual void set_hinting(TextServer::Hinting p_hinting) override{}; + virtual TextServer::Hinting get_hinting() const override { return TextServer::HINTING_NONE; }; + + virtual void set_distance_field_hint(bool p_distance_field) override; + virtual bool get_distance_field_hint() const override; + + virtual void set_force_autohinter(bool p_enabeld) override{}; + virtual bool get_force_autohinter() const override { return false; }; + + virtual bool has_outline() const override { return false; }; + virtual float get_base_size() const override; + + virtual bool has_char(char32_t p_char) const override; + virtual String get_supported_chars() const override; + + virtual Vector2 get_advance(char32_t p_char, int p_size) const override; + virtual Vector2 get_kerning(char32_t p_char, char32_t p_next, int p_size) const override; + + virtual Vector2 draw_glyph(RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const override; + virtual Vector2 draw_glyph_outline(RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const override; +}; + +#endif // BITMAP_FONT_FALLBACK_H diff --git a/modules/text_server_fb/config.py b/modules/text_server_fb/config.py new file mode 100644 index 0000000000..491377a369 --- /dev/null +++ b/modules/text_server_fb/config.py @@ -0,0 +1,11 @@ +def can_build(env, platform): + return env.module_check_dependencies("text_server_fb", ["freetype"]) + + +def configure(env): + pass + + +def is_enabled(): + # The module is disabled by default. Use module_text_server_fb_enabled=yes to enable it. + return False diff --git a/modules/text_server_fb/dynamic_font_fb.cpp b/modules/text_server_fb/dynamic_font_fb.cpp new file mode 100644 index 0000000000..6feeaec102 --- /dev/null +++ b/modules/text_server_fb/dynamic_font_fb.cpp @@ -0,0 +1,731 @@ +/*************************************************************************/ +/* dynamic_font_fb.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 "dynamic_font_fb.h" + +#include FT_STROKER_H +#include FT_ADVANCES_H + +HashMap<String, Vector<uint8_t>> DynamicFontDataFallback::font_mem_cache; + +DynamicFontDataFallback::DataAtSize *DynamicFontDataFallback::get_data_for_size(int p_size, int p_outline_size) { + ERR_FAIL_COND_V(!valid, nullptr); + ERR_FAIL_COND_V(p_size < 0 || p_size > UINT16_MAX, nullptr); + ERR_FAIL_COND_V(p_outline_size < 0 || p_outline_size > UINT16_MAX, nullptr); + + CacheID id; + id.size = p_size; + id.outline_size = p_outline_size; + + DataAtSize *fds = nullptr; + Map<CacheID, DataAtSize *>::Element *E = nullptr; + if (p_outline_size != 0) { + E = size_cache_outline.find(id); + } else { + E = size_cache.find(id); + } + + if (E != nullptr) { + fds = E->get(); + } else { + // FT_OPEN_STREAM is extremely slow only on Android. + if (OS::get_singleton()->get_name() == "Android" && font_mem == nullptr && font_path != String()) { + if (font_mem_cache.has(font_path)) { + font_mem = font_mem_cache[font_path].ptr(); + font_mem_size = font_mem_cache[font_path].size(); + } else { + FileAccess *f = FileAccess::open(font_path, FileAccess::READ); + if (!f) { + ERR_FAIL_V_MSG(nullptr, "Cannot open font file '" + font_path + "'."); + } + + size_t len = f->get_len(); + font_mem_cache[font_path] = Vector<uint8_t>(); + Vector<uint8_t> &fontdata = font_mem_cache[font_path]; + fontdata.resize(len); + f->get_buffer(fontdata.ptrw(), len); + font_mem = fontdata.ptr(); + font_mem_size = len; + f->close(); + } + } + + int error = 0; + fds = memnew(DataAtSize); + if (font_mem == nullptr && font_path != String()) { + FileAccess *f = FileAccess::open(font_path, FileAccess::READ); + if (!f) { + memdelete(fds); + ERR_FAIL_V_MSG(nullptr, "Cannot open font file '" + font_path + "'."); + } + + memset(&fds->stream, 0, sizeof(FT_StreamRec)); + fds->stream.base = nullptr; + fds->stream.size = f->get_len(); + fds->stream.pos = 0; + fds->stream.descriptor.pointer = f; + fds->stream.read = _ft_stream_io; + fds->stream.close = _ft_stream_close; + + FT_Open_Args fargs; + memset(&fargs, 0, sizeof(FT_Open_Args)); + fargs.flags = FT_OPEN_STREAM; + fargs.stream = &fds->stream; + error = FT_Open_Face(library, &fargs, 0, &fds->face); + } else if (font_mem) { + memset(&fds->stream, 0, sizeof(FT_StreamRec)); + fds->stream.base = (unsigned char *)font_mem; + fds->stream.size = font_mem_size; + fds->stream.pos = 0; + + FT_Open_Args fargs; + memset(&fargs, 0, sizeof(FT_Open_Args)); + fargs.memory_base = (unsigned char *)font_mem; + fargs.memory_size = font_mem_size; + fargs.flags = FT_OPEN_MEMORY; + fargs.stream = &fds->stream; + error = FT_Open_Face(library, &fargs, 0, &fds->face); + + } else { + memdelete(fds); + ERR_FAIL_V_MSG(nullptr, "DynamicFont uninitialized."); + } + + if (error == FT_Err_Unknown_File_Format) { + memdelete(fds); + ERR_FAIL_V_MSG(nullptr, "Unknown font format."); + + } else if (error) { + memdelete(fds); + ERR_FAIL_V_MSG(nullptr, "Error loading font."); + } + + oversampling = TS->font_get_oversampling(); + + if (FT_HAS_COLOR(fds->face) && fds->face->num_fixed_sizes > 0) { + int best_match = 0; + int diff = ABS(p_size - ((int64_t)fds->face->available_sizes[0].width)); + fds->scale_color_font = float(p_size * oversampling) / fds->face->available_sizes[0].width; + for (int i = 1; i < fds->face->num_fixed_sizes; i++) { + int ndiff = ABS(p_size - ((int64_t)fds->face->available_sizes[i].width)); + if (ndiff < diff) { + best_match = i; + diff = ndiff; + fds->scale_color_font = float(p_size * oversampling) / fds->face->available_sizes[i].width; + } + } + FT_Select_Size(fds->face, best_match); + } else { + FT_Set_Pixel_Sizes(fds->face, 0, p_size * oversampling); + } + + fds->size = p_size; + fds->ascent = (fds->face->size->metrics.ascender / 64.0) / oversampling * fds->scale_color_font; + fds->descent = (-fds->face->size->metrics.descender / 64.0) / oversampling * fds->scale_color_font; + fds->underline_position = -fds->face->underline_position / 64.0 / oversampling * fds->scale_color_font; + fds->underline_thickness = fds->face->underline_thickness / 64.0 / oversampling * fds->scale_color_font; + if (p_outline_size != 0) { + size_cache_outline[id] = fds; + } else { + size_cache[id] = fds; + } + } + + return fds; +} + +unsigned long DynamicFontDataFallback::_ft_stream_io(FT_Stream stream, unsigned long offset, unsigned char *buffer, unsigned long count) { + FileAccess *f = (FileAccess *)stream->descriptor.pointer; + + if (f->get_position() != offset) { + f->seek(offset); + } + if (count == 0) { + return 0; + } + + return f->get_buffer(buffer, count); +} + +void DynamicFontDataFallback::_ft_stream_close(FT_Stream stream) { + FileAccess *f = (FileAccess *)stream->descriptor.pointer; + f->close(); + memdelete(f); +} + +DynamicFontDataFallback::TexturePosition DynamicFontDataFallback::find_texture_pos_for_glyph(DynamicFontDataFallback::DataAtSize *p_data, int p_color_size, Image::Format p_image_format, int p_width, int p_height) { + TexturePosition ret; + ret.index = -1; + ret.x = 0; + ret.y = 0; + + int mw = p_width; + int mh = p_height; + + for (int i = 0; i < p_data->textures.size(); i++) { + const CharTexture &ct = p_data->textures[i]; + + if (RenderingServer::get_singleton() != nullptr) { + if (ct.texture->get_format() != p_image_format) { + continue; + } + } + + if (mw > ct.texture_size || mh > ct.texture_size) { //too big for this texture + continue; + } + + ret.y = 0x7FFFFFFF; + ret.x = 0; + + for (int j = 0; j < ct.texture_size - mw; j++) { + int max_y = 0; + + for (int k = j; k < j + mw; k++) { + int y = ct.offsets[k]; + if (y > max_y) { + max_y = y; + } + } + + if (max_y < ret.y) { + ret.y = max_y; + ret.x = j; + } + } + + if (ret.y == 0x7FFFFFFF || ret.y + mh > ct.texture_size) { + continue; //fail, could not fit it here + } + + ret.index = i; + break; + } + + if (ret.index == -1) { + //could not find texture to fit, create one + ret.x = 0; + ret.y = 0; + + int texsize = MAX(p_data->size * oversampling * 8, 256); + if (mw > texsize) { + texsize = mw; //special case, adapt to it? + } + if (mh > texsize) { + texsize = mh; //special case, adapt to it? + } + + texsize = next_power_of_2(texsize); + + texsize = MIN(texsize, 4096); + + CharTexture tex; + tex.texture_size = texsize; + tex.imgdata.resize(texsize * texsize * p_color_size); //grayscale alpha + + { + //zero texture + uint8_t *w = tex.imgdata.ptrw(); + ERR_FAIL_COND_V(texsize * texsize * p_color_size > tex.imgdata.size(), ret); + // Initialize the texture to all-white pixels to prevent artifacts when the + // font is displayed at a non-default scale with filtering enabled. + if (p_color_size == 2) { + for (int i = 0; i < texsize * texsize * p_color_size; i += 2) { // FORMAT_LA8 + w[i + 0] = 255; + w[i + 1] = 0; + } + } else if (p_color_size == 4) { + for (int i = 0; i < texsize * texsize * p_color_size; i += 4) { // FORMAT_RGBA8 + w[i + 0] = 255; + w[i + 1] = 255; + w[i + 2] = 255; + w[i + 3] = 0; + } + } else { + ERR_FAIL_V(ret); + } + } + tex.offsets.resize(texsize); + for (int i = 0; i < texsize; i++) { //zero offsets + tex.offsets.write[i] = 0; + } + + p_data->textures.push_back(tex); + ret.index = p_data->textures.size() - 1; + } + + return ret; +} + +DynamicFontDataFallback::Character DynamicFontDataFallback::Character::not_found() { + Character ch; + return ch; +} + +DynamicFontDataFallback::Character DynamicFontDataFallback::bitmap_to_character(DynamicFontDataFallback::DataAtSize *p_data, FT_Bitmap bitmap, int yofs, int xofs, const Vector2 &advance) { + int w = bitmap.width; + int h = bitmap.rows; + + int mw = w + rect_margin * 2; + int mh = h + rect_margin * 2; + + ERR_FAIL_COND_V(mw > 4096, Character::not_found()); + ERR_FAIL_COND_V(mh > 4096, Character::not_found()); + + int color_size = bitmap.pixel_mode == FT_PIXEL_MODE_BGRA ? 4 : 2; + Image::Format require_format = color_size == 4 ? Image::FORMAT_RGBA8 : Image::FORMAT_LA8; + + TexturePosition tex_pos = find_texture_pos_for_glyph(p_data, color_size, require_format, mw, mh); + ERR_FAIL_COND_V(tex_pos.index < 0, Character::not_found()); + + //fit character in char texture + + CharTexture &tex = p_data->textures.write[tex_pos.index]; + + { + uint8_t *wr = tex.imgdata.ptrw(); + + for (int i = 0; i < h; i++) { + for (int j = 0; j < w; j++) { + int ofs = ((i + tex_pos.y + rect_margin) * tex.texture_size + j + tex_pos.x + rect_margin) * color_size; + ERR_FAIL_COND_V(ofs >= tex.imgdata.size(), Character::not_found()); + switch (bitmap.pixel_mode) { + case FT_PIXEL_MODE_MONO: { + int byte = i * bitmap.pitch + (j >> 3); + int bit = 1 << (7 - (j % 8)); + wr[ofs + 0] = 255; //grayscale as 1 + wr[ofs + 1] = (bitmap.buffer[byte] & bit) ? 255 : 0; + } break; + case FT_PIXEL_MODE_GRAY: + wr[ofs + 0] = 255; //grayscale as 1 + wr[ofs + 1] = bitmap.buffer[i * bitmap.pitch + j]; + break; + case FT_PIXEL_MODE_BGRA: { + int ofs_color = i * bitmap.pitch + (j << 2); + wr[ofs + 2] = bitmap.buffer[ofs_color + 0]; + wr[ofs + 1] = bitmap.buffer[ofs_color + 1]; + wr[ofs + 0] = bitmap.buffer[ofs_color + 2]; + wr[ofs + 3] = bitmap.buffer[ofs_color + 3]; + } break; + // TODO: FT_PIXEL_MODE_LCD + default: + ERR_FAIL_V_MSG(Character::not_found(), "Font uses unsupported pixel format: " + itos(bitmap.pixel_mode) + "."); + break; + } + } + } + } + + //blit to image and texture + { + if (RenderingServer::get_singleton() != nullptr) { + Ref<Image> img = memnew(Image(tex.texture_size, tex.texture_size, 0, require_format, tex.imgdata)); + + if (tex.texture.is_null()) { + tex.texture.instance(); + tex.texture->create_from_image(img); + } else { + tex.texture->update(img); //update + } + } + } + + // update height array + for (int k = tex_pos.x; k < tex_pos.x + mw; k++) { + tex.offsets.write[k] = tex_pos.y + mh; + } + + Character chr; + chr.align = Vector2(xofs, -yofs) * p_data->scale_color_font / oversampling; + chr.advance = advance * p_data->scale_color_font / oversampling; + chr.texture_idx = tex_pos.index; + chr.found = true; + + chr.rect_uv = Rect2(tex_pos.x + rect_margin, tex_pos.y + rect_margin, w, h); + chr.rect = chr.rect_uv; + chr.rect.position /= oversampling; + chr.rect.size *= (p_data->scale_color_font / oversampling); + return chr; +} + +void DynamicFontDataFallback::update_char(int p_size, char32_t p_char) { + DataAtSize *fds = get_data_for_size(p_size, false); + ERR_FAIL_COND(fds == nullptr); + + if (fds->char_map.has(p_char)) { + return; + } + + Character character = Character::not_found(); + + FT_GlyphSlot slot = fds->face->glyph; + FT_UInt gl_index = FT_Get_Char_Index(fds->face, p_char); + + if (gl_index == 0) { + fds->char_map[p_char] = character; + return; + } + + int ft_hinting; + switch (hinting) { + case TextServer::HINTING_NONE: + ft_hinting = FT_LOAD_NO_HINTING; + break; + case TextServer::HINTING_LIGHT: + ft_hinting = FT_LOAD_TARGET_LIGHT; + break; + default: + ft_hinting = FT_LOAD_TARGET_NORMAL; + break; + } + + FT_Fixed v, h; + FT_Get_Advance(fds->face, gl_index, FT_HAS_COLOR(fds->face) ? FT_LOAD_COLOR : FT_LOAD_DEFAULT | (force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0) | ft_hinting, &h); + FT_Get_Advance(fds->face, gl_index, FT_HAS_COLOR(fds->face) ? FT_LOAD_COLOR : FT_LOAD_DEFAULT | (force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0) | ft_hinting | FT_LOAD_VERTICAL_LAYOUT, &v); + + int error = FT_Load_Glyph(fds->face, gl_index, FT_HAS_COLOR(fds->face) ? FT_LOAD_COLOR : FT_LOAD_DEFAULT | (force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0) | ft_hinting); + if (error) { + fds->char_map[p_char] = character; + return; + } + + error = FT_Render_Glyph(fds->face->glyph, antialiased ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO); + if (!error) { + character = bitmap_to_character(fds, slot->bitmap, slot->bitmap_top, slot->bitmap_left, Vector2((h + (1 << 9)) >> 10, (v + (1 << 9)) >> 10) / 64.0); + } + + fds->char_map[p_char] = character; +} + +void DynamicFontDataFallback::update_char_outline(int p_size, int p_outline_size, char32_t p_char) { + DataAtSize *fds = get_data_for_size(p_size, p_outline_size); + ERR_FAIL_COND(fds == nullptr); + + if (fds->char_map.has(p_char)) { + return; + } + + Character character = Character::not_found(); + FT_UInt gl_index = FT_Get_Char_Index(fds->face, p_char); + + if (gl_index == 0) { + fds->char_map[p_char] = character; + return; + } + + int error = FT_Load_Glyph(fds->face, gl_index, FT_LOAD_NO_BITMAP | (force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0)); + if (error) { + fds->char_map[p_char] = character; + return; + } + + FT_Stroker stroker; + if (FT_Stroker_New(library, &stroker) != 0) { + fds->char_map[p_char] = character; + return; + } + + FT_Stroker_Set(stroker, (int)(p_outline_size * oversampling * 64.0), FT_STROKER_LINECAP_BUTT, FT_STROKER_LINEJOIN_ROUND, 0); + FT_Glyph glyph; + FT_BitmapGlyph glyph_bitmap; + + if (FT_Get_Glyph(fds->face->glyph, &glyph) != 0) { + goto cleanup_stroker; + } + if (FT_Glyph_Stroke(&glyph, stroker, 1) != 0) { + goto cleanup_glyph; + } + if (FT_Glyph_To_Bitmap(&glyph, antialiased ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO, nullptr, 1) != 0) { + goto cleanup_glyph; + } + + glyph_bitmap = (FT_BitmapGlyph)glyph; + character = bitmap_to_character(fds, glyph_bitmap->bitmap, glyph_bitmap->top, glyph_bitmap->left, Vector2()); + +cleanup_glyph: + FT_Done_Glyph(glyph); +cleanup_stroker: + FT_Stroker_Done(stroker); + + fds->char_map[p_char] = character; +} + +void DynamicFontDataFallback::clear_cache() { + _THREAD_SAFE_METHOD_ + for (Map<CacheID, DataAtSize *>::Element *E = size_cache.front(); E; E = E->next()) { + memdelete(E->get()); + } + size_cache.clear(); + for (Map<CacheID, DataAtSize *>::Element *E = size_cache_outline.front(); E; E = E->next()) { + memdelete(E->get()); + } + size_cache_outline.clear(); +} + +Error DynamicFontDataFallback::load_from_file(const String &p_filename, int p_base_size) { + _THREAD_SAFE_METHOD_ + if (library == nullptr) { + int error = FT_Init_FreeType(&library); + ERR_FAIL_COND_V_MSG(error != 0, ERR_CANT_CREATE, "Error initializing FreeType."); + } + clear_cache(); + + font_path = p_filename; + base_size = p_base_size; + + valid = true; + DataAtSize *fds = get_data_for_size(base_size); // load base size. + if (fds == nullptr) { + valid = false; + ERR_FAIL_V(ERR_CANT_CREATE); + } + + return OK; +} + +Error DynamicFontDataFallback::load_from_memory(const uint8_t *p_data, size_t p_size, int p_base_size) { + _THREAD_SAFE_METHOD_ + if (library == nullptr) { + int error = FT_Init_FreeType(&library); + ERR_FAIL_COND_V_MSG(error != 0, ERR_CANT_CREATE, "Error initializing FreeType."); + } + clear_cache(); + + font_mem = p_data; + font_mem_size = p_size; + base_size = p_base_size; + + valid = true; + DataAtSize *fds = get_data_for_size(base_size); // load base size. + if (fds == nullptr) { + valid = false; + ERR_FAIL_V(ERR_CANT_CREATE); + } + + return OK; +} + +float DynamicFontDataFallback::get_height(int p_size) const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataFallback *>(this)->get_data_for_size(p_size); + ERR_FAIL_COND_V(fds == nullptr, 0.f); + return fds->ascent + fds->descent; +} + +float DynamicFontDataFallback::get_ascent(int p_size) const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataFallback *>(this)->get_data_for_size(p_size); + ERR_FAIL_COND_V(fds == nullptr, 0.f); + return fds->ascent; +} + +float DynamicFontDataFallback::get_descent(int p_size) const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataFallback *>(this)->get_data_for_size(p_size); + ERR_FAIL_COND_V(fds == nullptr, 0.f); + return fds->descent; +} + +float DynamicFontDataFallback::get_underline_position(int p_size) const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataFallback *>(this)->get_data_for_size(p_size); + ERR_FAIL_COND_V(fds == nullptr, 0.f); + return fds->underline_position; +} + +float DynamicFontDataFallback::get_underline_thickness(int p_size) const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataFallback *>(this)->get_data_for_size(p_size); + ERR_FAIL_COND_V(fds == nullptr, 0.f); + return fds->underline_thickness; +} + +void DynamicFontDataFallback::set_antialiased(bool p_antialiased) { + if (antialiased != p_antialiased) { + clear_cache(); + antialiased = p_antialiased; + } +} + +bool DynamicFontDataFallback::get_antialiased() const { + return antialiased; +} + +void DynamicFontDataFallback::set_force_autohinter(bool p_enabled) { + if (force_autohinter != p_enabled) { + clear_cache(); + force_autohinter = p_enabled; + } +} + +bool DynamicFontDataFallback::get_force_autohinter() const { + return force_autohinter; +} + +void DynamicFontDataFallback::set_hinting(TextServer::Hinting p_hinting) { + if (hinting != p_hinting) { + clear_cache(); + hinting = p_hinting; + } +} + +TextServer::Hinting DynamicFontDataFallback::get_hinting() const { + return hinting; +} + +bool DynamicFontDataFallback::has_outline() const { + return true; +} + +float DynamicFontDataFallback::get_base_size() const { + return base_size; +} + +bool DynamicFontDataFallback::has_char(char32_t p_char) const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataFallback *>(this)->get_data_for_size(base_size); + ERR_FAIL_COND_V(fds == nullptr, false); + + const_cast<DynamicFontDataFallback *>(this)->update_char(base_size, p_char); + Character ch = fds->char_map[p_char]; + + return (ch.found); +} + +String DynamicFontDataFallback::get_supported_chars() const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataFallback *>(this)->get_data_for_size(base_size); + ERR_FAIL_COND_V(fds == nullptr, String()); + + String chars; + + FT_UInt gindex; + FT_ULong charcode = FT_Get_First_Char(fds->face, &gindex); + while (gindex != 0) { + if (charcode != 0) { + chars += char32_t(charcode); + } + charcode = FT_Get_Next_Char(fds->face, charcode, &gindex); + } + + return chars; +} + +Vector2 DynamicFontDataFallback::get_advance(char32_t p_char, int p_size) const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataFallback *>(this)->get_data_for_size(p_size); + ERR_FAIL_COND_V(fds == nullptr, Vector2()); + + const_cast<DynamicFontDataFallback *>(this)->update_char(p_size, p_char); + Character ch = fds->char_map[p_char]; + + return ch.advance; +} + +Vector2 DynamicFontDataFallback::get_kerning(char32_t p_char, char32_t p_next, int p_size) const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataFallback *>(this)->get_data_for_size(p_size); + ERR_FAIL_COND_V(fds == nullptr, Vector2()); + + FT_Vector delta; + FT_Get_Kerning(fds->face, FT_Get_Char_Index(fds->face, p_char), FT_Get_Char_Index(fds->face, p_next), FT_KERNING_DEFAULT, &delta); + return Vector2(delta.x, delta.y); +} + +Vector2 DynamicFontDataFallback::draw_glyph(RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataFallback *>(this)->get_data_for_size(p_size); + ERR_FAIL_COND_V(fds == nullptr, Vector2()); + + const_cast<DynamicFontDataFallback *>(this)->update_char(p_size, p_index); + Character ch = fds->char_map[p_index]; + + Vector2 advance; + if (ch.found) { + ERR_FAIL_COND_V(ch.texture_idx < -1 || ch.texture_idx >= fds->textures.size(), Vector2()); + + if (ch.texture_idx != -1) { + Point2 cpos = p_pos; + cpos += ch.align; + + Color modulate = p_color; + if (FT_HAS_COLOR(fds->face)) { + modulate.r = modulate.g = modulate.b = 1.0; + } + if (RenderingServer::get_singleton() != nullptr) { + RID texture = fds->textures[ch.texture_idx].texture->get_rid(); + RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, Rect2(cpos, ch.rect.size), texture, ch.rect_uv, modulate, false, false); + } + } + + advance = ch.advance; + } + + return advance; +} + +Vector2 DynamicFontDataFallback::draw_glyph_outline(RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const { + _THREAD_SAFE_METHOD_ + DataAtSize *fds = const_cast<DynamicFontDataFallback *>(this)->get_data_for_size(p_size, p_outline_size); + ERR_FAIL_COND_V(fds == nullptr, Vector2()); + + const_cast<DynamicFontDataFallback *>(this)->update_char_outline(p_size, p_outline_size, p_index); + Character ch = fds->char_map[p_index]; + + Vector2 advance; + if (ch.found) { + ERR_FAIL_COND_V(ch.texture_idx < -1 || ch.texture_idx >= fds->textures.size(), Vector2()); + + if (ch.texture_idx != -1) { + Point2 cpos = p_pos; + cpos += ch.align; + + Color modulate = p_color; + if (FT_HAS_COLOR(fds->face)) { + modulate.r = modulate.g = modulate.b = 1.0; + } + if (RenderingServer::get_singleton() != nullptr) { + RID texture = fds->textures[ch.texture_idx].texture->get_rid(); + RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, Rect2(cpos, ch.rect.size), texture, ch.rect_uv, modulate, false, false); + } + } + + advance = ch.advance; + } + + return advance; +} + +DynamicFontDataFallback::~DynamicFontDataFallback() { + clear_cache(); + if (library != nullptr) { + FT_Done_FreeType(library); + } +} diff --git a/modules/text_server_fb/dynamic_font_fb.h b/modules/text_server_fb/dynamic_font_fb.h new file mode 100644 index 0000000000..060b8cfbf9 --- /dev/null +++ b/modules/text_server_fb/dynamic_font_fb.h @@ -0,0 +1,172 @@ +/*************************************************************************/ +/* dynamic_font_fb.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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. */ +/*************************************************************************/ + +#ifndef DYNAMIC_FONT_FALLBACK_H +#define DYNAMIC_FONT_FALLBACK_H + +#include "font_fb.h" + +#include <ft2build.h> +#include FT_FREETYPE_H + +struct DynamicFontDataFallback : public FontDataFallback { + _THREAD_SAFE_CLASS_ + +private: + struct CharTexture { + Vector<uint8_t> imgdata; + int texture_size = 0; + Vector<int> offsets; + Ref<ImageTexture> texture; + }; + + struct Character { + bool found = false; + int texture_idx = 0; + Rect2 rect; + Rect2 rect_uv; + Vector2 align; + Vector2 advance = Vector2(-1, -1); + + static Character not_found(); + }; + + struct TexturePosition { + int index = 0; + int x = 0; + int y = 0; + }; + + struct CacheID { + union { + struct { + uint32_t size : 16; + uint32_t outline_size : 16; + }; + uint32_t key; + }; + bool operator<(CacheID right) const { + return key < right.key; + } + CacheID() { + key = 0; + } + }; + + struct DataAtSize { + FT_Face face = nullptr; + FT_StreamRec stream; + + int size = 0; + float scale_color_font = 1.f; + float ascent = 0; + float descent = 0; + float underline_position = 0; + float underline_thickness = 0; + + Vector<CharTexture> textures; + HashMap<char32_t, Character> char_map; + + ~DataAtSize() { + if (face != nullptr) { + FT_Done_Face(face); + } + } + }; + + FT_Library library = nullptr; + + // Source data. + const uint8_t *font_mem = nullptr; + int font_mem_size = 0; + String font_path; + static HashMap<String, Vector<uint8_t>> font_mem_cache; + + float rect_margin = 1.f; + int base_size = 16; + float oversampling = 1.f; + bool antialiased = true; + bool force_autohinter = false; + TextServer::Hinting hinting = TextServer::HINTING_LIGHT; + + Map<CacheID, DataAtSize *> size_cache; + Map<CacheID, DataAtSize *> size_cache_outline; + + static unsigned long _ft_stream_io(FT_Stream stream, unsigned long offset, unsigned char *buffer, unsigned long count); + static void _ft_stream_close(FT_Stream stream); + + DataAtSize *get_data_for_size(int p_size, int p_outline_size = 0); + + TexturePosition find_texture_pos_for_glyph(DataAtSize *p_data, int p_color_size, Image::Format p_image_format, int p_width, int p_height); + Character bitmap_to_character(DataAtSize *p_data, FT_Bitmap bitmap, int yofs, int xofs, const Vector2 &advance); + _FORCE_INLINE_ void update_char(int p_size, char32_t p_char); + _FORCE_INLINE_ void update_char_outline(int p_size, int p_outline_size, char32_t p_char); + +public: + virtual void clear_cache() override; + + virtual Error load_from_file(const String &p_filename, int p_base_size) override; + virtual Error load_from_memory(const uint8_t *p_data, size_t p_size, int p_base_size) override; + + virtual float get_height(int p_size) const override; + virtual float get_ascent(int p_size) const override; + virtual float get_descent(int p_size) const override; + + virtual float get_underline_position(int p_size) const override; + virtual float get_underline_thickness(int p_size) const override; + + virtual void set_antialiased(bool p_antialiased) override; + virtual bool get_antialiased() const override; + + virtual void set_hinting(TextServer::Hinting p_hinting) override; + virtual TextServer::Hinting get_hinting() const override; + + virtual void set_force_autohinter(bool p_enabeld) override; + virtual bool get_force_autohinter() const override; + + virtual void set_distance_field_hint(bool p_distance_field) override{}; + virtual bool get_distance_field_hint() const override { return false; }; + + virtual bool has_outline() const override; + virtual float get_base_size() const override; + + virtual bool has_char(char32_t p_char) const override; + virtual String get_supported_chars() const override; + + virtual Vector2 get_advance(char32_t p_char, int p_size) const override; + virtual Vector2 get_kerning(char32_t p_char, char32_t p_next, int p_size) const override; + + virtual Vector2 draw_glyph(RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const override; + virtual Vector2 draw_glyph_outline(RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const override; + + virtual ~DynamicFontDataFallback() override; +}; + +#endif // DYNAMIC_FONT_FALLBACK_H diff --git a/modules/text_server_fb/font_fb.h b/modules/text_server_fb/font_fb.h new file mode 100644 index 0000000000..d2ce2661a1 --- /dev/null +++ b/modules/text_server_fb/font_fb.h @@ -0,0 +1,80 @@ +/*************************************************************************/ +/* font_fb.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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. */ +/*************************************************************************/ + +#ifndef FONT_FALLBACK_H +#define FONT_FALLBACK_H + +#include "servers/text_server.h" + +struct FontDataFallback { + Map<String, bool> lang_support_overrides; + Map<String, bool> script_support_overrides; + bool valid = false; + + virtual void clear_cache() = 0; + + virtual Error load_from_file(const String &p_filename, int p_base_size) = 0; + virtual Error load_from_memory(const uint8_t *p_data, size_t p_size, int p_base_size) = 0; + + virtual float get_height(int p_size) const = 0; + virtual float get_ascent(int p_size) const = 0; + virtual float get_descent(int p_size) const = 0; + + virtual float get_underline_position(int p_size) const = 0; + virtual float get_underline_thickness(int p_size) const = 0; + + virtual void set_antialiased(bool p_antialiased) = 0; + virtual bool get_antialiased() const = 0; + + virtual void set_hinting(TextServer::Hinting p_hinting) = 0; + virtual TextServer::Hinting get_hinting() const = 0; + + virtual void set_distance_field_hint(bool p_distance_field) = 0; + virtual bool get_distance_field_hint() const = 0; + + virtual void set_force_autohinter(bool p_enabeld) = 0; + virtual bool get_force_autohinter() const = 0; + + virtual bool has_outline() const = 0; + virtual float get_base_size() const = 0; + + virtual bool has_char(char32_t p_char) const = 0; + virtual String get_supported_chars() const = 0; + + virtual Vector2 get_advance(char32_t p_char, int p_size) const = 0; + virtual Vector2 get_kerning(char32_t p_char, char32_t p_next, int p_size) const = 0; + + virtual Vector2 draw_glyph(RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const = 0; + virtual Vector2 draw_glyph_outline(RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const = 0; + + virtual ~FontDataFallback(){}; +}; + +#endif // FONT_FALLBACK_H diff --git a/modules/text_server_fb/register_types.cpp b/modules/text_server_fb/register_types.cpp new file mode 100644 index 0000000000..ad4d2d47ab --- /dev/null +++ b/modules/text_server_fb/register_types.cpp @@ -0,0 +1,43 @@ +/*************************************************************************/ +/* register_types.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 "register_types.h" + +#include "text_server_fb.h" + +void preregister_text_server_fb_types() { + TextServerFallback::register_server(); +} + +void register_text_server_fb_types() { +} + +void unregister_text_server_fb_types() { +} diff --git a/modules/text_server_fb/register_types.h b/modules/text_server_fb/register_types.h new file mode 100644 index 0000000000..58f8436c67 --- /dev/null +++ b/modules/text_server_fb/register_types.h @@ -0,0 +1,40 @@ +/*************************************************************************/ +/* register_types.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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. */ +/*************************************************************************/ + +#ifndef TEXT_SERVER_FB_REGISTER_TYPES_H +#define TEXT_SERVER_FB_REGISTER_TYPES_H + +#define MODULE_TEXT_SERVER_FB_HAS_PREREGISTER + +void preregister_text_server_fb_types(); +void register_text_server_fb_types(); +void unregister_text_server_fb_types(); + +#endif // TEXT_SERVER_FB_REGISTER_TYPES_H diff --git a/modules/text_server_fb/text_server_fb.cpp b/modules/text_server_fb/text_server_fb.cpp new file mode 100644 index 0000000000..e74a1d9ef9 --- /dev/null +++ b/modules/text_server_fb/text_server_fb.cpp @@ -0,0 +1,1362 @@ +/*************************************************************************/ +/* text_server_fb.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 "text_server_fb.h" + +#include "bitmap_font_fb.h" +#include "dynamic_font_fb.h" + +_FORCE_INLINE_ bool is_control(char32_t p_char) { + return (p_char <= 0x001f) || (p_char >= 0x007f && p_char <= 0x009F); +} + +_FORCE_INLINE_ bool is_whitespace(char32_t p_char) { + return (p_char == 0x0020) || (p_char == 0x00A0) || (p_char == 0x1680) || (p_char >= 0x2000 && p_char <= 0x200a) || (p_char == 0x202f) || (p_char == 0x205f) || (p_char == 0x3000) || (p_char == 0x2028) || (p_char == 0x2029) || (p_char >= 0x0009 && p_char <= 0x000d) || (p_char == 0x0085); +} + +_FORCE_INLINE_ bool is_linebreak(char32_t p_char) { + return (p_char >= 0x000a && p_char <= 0x000d) || (p_char == 0x0085) || (p_char == 0x2028) || (p_char == 0x2029); +} + +/*************************************************************************/ + +String TextServerFallback::interface_name = "Fallback"; +uint32_t TextServerFallback::interface_features = 0; // Nothing is supported. + +bool TextServerFallback::has_feature(Feature p_feature) { + return (interface_features & p_feature) == p_feature; +} + +String TextServerFallback::get_name() const { + return interface_name; +} + +void TextServerFallback::free(RID p_rid) { + _THREAD_SAFE_METHOD_ + if (font_owner.owns(p_rid)) { + FontDataFallback *fd = font_owner.getornull(p_rid); + font_owner.free(p_rid); + memdelete(fd); + } else if (shaped_owner.owns(p_rid)) { + ShapedTextData *sd = shaped_owner.getornull(p_rid); + shaped_owner.free(p_rid); + memdelete(sd); + } +} + +bool TextServerFallback::has(RID p_rid) { + _THREAD_SAFE_METHOD_ + return font_owner.owns(p_rid) || shaped_owner.owns(p_rid); +} + +bool TextServerFallback::load_support_data(const String &p_filename) { + return false; // No extra data used. +} + +#ifdef TOOLS_ENABLED + +bool TextServerFallback::save_support_data(const String &p_filename) { + return false; // No extra data used. +} + +#endif + +bool TextServerFallback::is_locale_right_to_left(const String &p_locale) { + return false; // No RTL support. +} + +/*************************************************************************/ +/* Font interface */ +/*************************************************************************/ + +RID TextServerFallback::create_font_system(const String &p_name, int p_base_size) { + ERR_FAIL_V_MSG(RID(), "System fonts are not supported by this text server."); +} + +RID TextServerFallback::create_font_resource(const String &p_filename, int p_base_size) { + _THREAD_SAFE_METHOD_ + FontDataFallback *fd = nullptr; + if (p_filename.get_extension() == "ttf" || p_filename.get_extension() == "otf" || p_filename.get_extension() == "woff") { + fd = memnew(DynamicFontDataFallback); + } else if (p_filename.get_extension() == "fnt" || p_filename.get_extension() == "font") { + fd = memnew(BitmapFontDataFallback); + } else { + return RID(); + } + + Error err = fd->load_from_file(p_filename, p_base_size); + if (err != OK) { + memdelete(fd); + return RID(); + } + + return font_owner.make_rid(fd); +} + +RID TextServerFallback::create_font_memory(const uint8_t *p_data, size_t p_size, const String &p_type, int p_base_size) { + _THREAD_SAFE_METHOD_ + FontDataFallback *fd = nullptr; + if (p_type == "ttf" || p_type == "otf" || p_type == "woff") { + fd = memnew(DynamicFontDataFallback); + } else if (p_type == "fnt" || p_type == "font") { + fd = memnew(BitmapFontDataFallback); + } else { + return RID(); + } + + Error err = fd->load_from_memory(p_data, p_size, p_base_size); + if (err != OK) { + memdelete(fd); + return RID(); + } + + return font_owner.make_rid(fd); +} + +float TextServerFallback::font_get_height(RID p_font, int p_size) const { + _THREAD_SAFE_METHOD_ + const FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, 0.f); + return fd->get_height(p_size); +} + +float TextServerFallback::font_get_ascent(RID p_font, int p_size) const { + _THREAD_SAFE_METHOD_ + const FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, 0.f); + return fd->get_ascent(p_size); +} + +float TextServerFallback::font_get_descent(RID p_font, int p_size) const { + _THREAD_SAFE_METHOD_ + const FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, 0.f); + return fd->get_descent(p_size); +} + +float TextServerFallback::font_get_underline_position(RID p_font, int p_size) const { + _THREAD_SAFE_METHOD_ + const FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, 0.f); + return fd->get_underline_position(p_size); +} + +float TextServerFallback::font_get_underline_thickness(RID p_font, int p_size) const { + _THREAD_SAFE_METHOD_ + const FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, 0.f); + return fd->get_underline_thickness(p_size); +} + +void TextServerFallback::font_set_antialiased(RID p_font, bool p_antialiased) { + _THREAD_SAFE_METHOD_ + FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND(!fd); + fd->set_antialiased(p_antialiased); +} + +bool TextServerFallback::font_get_antialiased(RID p_font) const { + _THREAD_SAFE_METHOD_ + const FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, false); + return fd->get_antialiased(); +} + +void TextServerFallback::font_set_distance_field_hint(RID p_font, bool p_distance_field) { + _THREAD_SAFE_METHOD_ + FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND(!fd); + fd->set_distance_field_hint(p_distance_field); +} + +bool TextServerFallback::font_get_distance_field_hint(RID p_font) const { + _THREAD_SAFE_METHOD_ + const FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, false); + return fd->get_distance_field_hint(); +} + +void TextServerFallback::font_set_hinting(RID p_font, TextServer::Hinting p_hinting) { + _THREAD_SAFE_METHOD_ + FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND(!fd); + fd->set_hinting(p_hinting); +} + +TextServer::Hinting TextServerFallback::font_get_hinting(RID p_font) const { + _THREAD_SAFE_METHOD_ + const FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, TextServer::HINTING_NONE); + return fd->get_hinting(); +} + +void TextServerFallback::font_set_force_autohinter(RID p_font, bool p_enabeld) { + _THREAD_SAFE_METHOD_ + FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND(!fd); + fd->set_force_autohinter(p_enabeld); +} + +bool TextServerFallback::font_get_force_autohinter(RID p_font) const { + _THREAD_SAFE_METHOD_ + const FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, false); + return fd->get_force_autohinter(); +} + +bool TextServerFallback::font_has_char(RID p_font, char32_t p_char) const { + _THREAD_SAFE_METHOD_ + const FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, false); + return fd->has_char(p_char); +} + +String TextServerFallback::font_get_supported_chars(RID p_font) const { + _THREAD_SAFE_METHOD_ + const FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, String()); + return fd->get_supported_chars(); +} + +bool TextServerFallback::font_has_outline(RID p_font) const { + _THREAD_SAFE_METHOD_ + const FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, false); + return fd->has_outline(); +} + +float TextServerFallback::font_get_base_size(RID p_font) const { + _THREAD_SAFE_METHOD_ + const FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, 0.f); + return fd->get_base_size(); +} + +bool TextServerFallback::font_is_language_supported(RID p_font, const String &p_language) const { + _THREAD_SAFE_METHOD_ + const FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, false); + if (fd->lang_support_overrides.has(p_language)) { + return fd->lang_support_overrides[p_language]; + } else { + Vector<String> tags = p_language.replace("-", "_").split("_"); + if (tags.size() > 0) { + if (fd->lang_support_overrides.has(tags[0])) { + return fd->lang_support_overrides[tags[0]]; + } + } + return false; + } +} + +void TextServerFallback::font_set_language_support_override(RID p_font, const String &p_language, bool p_supported) { + _THREAD_SAFE_METHOD_ + FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND(!fd); + fd->lang_support_overrides[p_language] = p_supported; +} + +bool TextServerFallback::font_get_language_support_override(RID p_font, const String &p_language) { + _THREAD_SAFE_METHOD_ + FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, false); + return fd->lang_support_overrides[p_language]; +} + +void TextServerFallback::font_remove_language_support_override(RID p_font, const String &p_language) { + _THREAD_SAFE_METHOD_ + FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND(!fd); + fd->lang_support_overrides.erase(p_language); +} + +Vector<String> TextServerFallback::font_get_language_support_overrides(RID p_font) { + _THREAD_SAFE_METHOD_ + FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, Vector<String>()); + Vector<String> ret; + for (Map<String, bool>::Element *E = fd->lang_support_overrides.front(); E; E = E->next()) { + ret.push_back(E->key()); + } + return ret; +} + +bool TextServerFallback::font_is_script_supported(RID p_font, const String &p_script) const { + _THREAD_SAFE_METHOD_ + const FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, false); + if (fd->script_support_overrides.has(p_script)) { + return fd->script_support_overrides[p_script]; + } else { + return true; + } +} + +void TextServerFallback::font_set_script_support_override(RID p_font, const String &p_script, bool p_supported) { + _THREAD_SAFE_METHOD_ + FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND(!fd); + fd->script_support_overrides[p_script] = p_supported; +} + +bool TextServerFallback::font_get_script_support_override(RID p_font, const String &p_script) { + _THREAD_SAFE_METHOD_ + FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, false); + return fd->script_support_overrides[p_script]; +} + +void TextServerFallback::font_remove_script_support_override(RID p_font, const String &p_script) { + _THREAD_SAFE_METHOD_ + FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND(!fd); + fd->script_support_overrides.erase(p_script); +} + +Vector<String> TextServerFallback::font_get_script_support_overrides(RID p_font) { + _THREAD_SAFE_METHOD_ + FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, Vector<String>()); + Vector<String> ret; + for (Map<String, bool>::Element *E = fd->script_support_overrides.front(); E; E = E->next()) { + ret.push_back(E->key()); + } + return ret; +} + +uint32_t TextServerFallback::font_get_glyph_index(RID p_font, char32_t p_char, char32_t p_variation_selector) const { + return (uint32_t)p_char; +} + +Vector2 TextServerFallback::font_get_glyph_advance(RID p_font, uint32_t p_index, int p_size) const { + _THREAD_SAFE_METHOD_ + const FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, Vector2()); + return fd->get_advance(p_index, p_size); +} + +Vector2 TextServerFallback::font_get_glyph_kerning(RID p_font, uint32_t p_index_a, uint32_t p_index_b, int p_size) const { + _THREAD_SAFE_METHOD_ + const FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, Vector2()); + return fd->get_kerning(p_index_a, p_index_b, p_size); +} + +Vector2 TextServerFallback::font_draw_glyph(RID p_font, RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const { + _THREAD_SAFE_METHOD_ + const FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, Vector2()); + return fd->draw_glyph(p_canvas, p_size, p_pos, p_index, p_color); +} + +Vector2 TextServerFallback::font_draw_glyph_outline(RID p_font, RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const { + _THREAD_SAFE_METHOD_ + const FontDataFallback *fd = font_owner.getornull(p_font); + ERR_FAIL_COND_V(!fd, Vector2()); + return fd->draw_glyph_outline(p_canvas, p_size, p_outline_size, p_pos, p_index, p_color); +} + +float TextServerFallback::font_get_oversampling() const { + return oversampling; +} + +void TextServerFallback::font_set_oversampling(float p_oversampling) { + _THREAD_SAFE_METHOD_ + if (oversampling != p_oversampling) { + oversampling = p_oversampling; + List<RID> fonts; + font_owner.get_owned_list(&fonts); + for (List<RID>::Element *E = fonts.front(); E; E = E->next()) { + font_owner.getornull(E->get())->clear_cache(); + } + } +} + +Vector<String> TextServerFallback::get_system_fonts() const { + return Vector<String>(); +} + +/*************************************************************************/ +/* Shaped text buffer interface */ +/*************************************************************************/ + +void TextServerFallback::invalidate(ShapedTextData *p_shaped) { + p_shaped->valid = false; + p_shaped->sort_valid = false; + p_shaped->line_breaks_valid = false; + p_shaped->justification_ops_valid = false; + p_shaped->ascent = 0.f; + p_shaped->descent = 0.f; + p_shaped->width = 0.f; + p_shaped->upos = 0.f; + p_shaped->uthk = 0.f; + p_shaped->glyphs.clear(); + p_shaped->glyphs_logical.clear(); +} + +void TextServerFallback::full_copy(ShapedTextData *p_shaped) { + ShapedTextData *parent = shaped_owner.getornull(p_shaped->parent); + + for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = parent->objects.front(); E; E = E->next()) { + if (E->get().pos >= p_shaped->start && E->get().pos < p_shaped->end) { + p_shaped->objects[E->key()] = E->get(); + } + } + + for (int k = 0; k < parent->spans.size(); k++) { + ShapedTextData::Span span = parent->spans[k]; + if (span.start >= p_shaped->end || span.end <= p_shaped->start) { + continue; + } + span.start = MAX(p_shaped->start, span.start); + span.end = MIN(p_shaped->end, span.end); + p_shaped->spans.push_back(span); + } + + p_shaped->parent = RID(); +} + +RID TextServerFallback::create_shaped_text(TextServer::Direction p_direction, TextServer::Orientation p_orientation) { + _THREAD_SAFE_METHOD_ + ShapedTextData *sd = memnew(ShapedTextData); + sd->direction = p_direction; + sd->orientation = p_orientation; + + return shaped_owner.make_rid(sd); +} + +void TextServerFallback::shaped_text_clear(RID p_shaped) { + _THREAD_SAFE_METHOD_ + ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND(!sd); + + sd->parent = RID(); + sd->start = 0; + sd->end = 0; + sd->text = String(); + sd->spans.clear(); + sd->objects.clear(); + invalidate(sd); +} + +void TextServerFallback::shaped_text_set_direction(RID p_shaped, TextServer::Direction p_direction) { + if (p_direction == DIRECTION_RTL) { + ERR_PRINT_ONCE("Right-to-left layout is not supported by this text server."); + } +} + +TextServer::Direction TextServerFallback::shaped_text_get_direction(RID p_shaped) const { + return TextServer::DIRECTION_LTR; +} + +void TextServerFallback::shaped_text_set_orientation(RID p_shaped, TextServer::Orientation p_orientation) { + _THREAD_SAFE_METHOD_ + ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND(!sd); + if (sd->orientation != p_orientation) { + if (sd->parent != RID()) { + full_copy(sd); + } + sd->orientation = p_orientation; + invalidate(sd); + } +} + +void TextServerFallback::shaped_text_set_bidi_override(RID p_shaped, const Vector<Vector2i> &p_override) { + //No BiDi support, ignore. +} + +TextServer::Orientation TextServerFallback::shaped_text_get_orientation(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, TextServer::ORIENTATION_HORIZONTAL); + return sd->orientation; +} + +void TextServerFallback::shaped_text_set_preserve_invalid(RID p_shaped, bool p_enabled) { + _THREAD_SAFE_METHOD_ + ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND(!sd); + if (sd->preserve_invalid != p_enabled) { + if (sd->parent != RID()) { + full_copy(sd); + } + sd->preserve_invalid = p_enabled; + invalidate(sd); + } +} + +bool TextServerFallback::shaped_text_get_preserve_invalid(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, false); + return sd->preserve_invalid; +} + +void TextServerFallback::shaped_text_set_preserve_control(RID p_shaped, bool p_enabled) { + _THREAD_SAFE_METHOD_ + ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND(!sd); + if (sd->preserve_control != p_enabled) { + if (sd->parent != RID()) { + full_copy(sd); + } + sd->preserve_control = p_enabled; + invalidate(sd); + } +} + +bool TextServerFallback::shaped_text_get_preserve_control(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, false); + return sd->preserve_control; +} + +bool TextServerFallback::shaped_text_add_string(RID p_shaped, const String &p_text, const Vector<RID> &p_fonts, int p_size, const Dictionary &p_opentype_features, const String &p_language) { + _THREAD_SAFE_METHOD_ + ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, false); + ERR_FAIL_COND_V(p_size <= 0, false); + + if (p_text.empty()) { + return true; + } + + if (sd->parent != RID()) { + full_copy(sd); + } + + ShapedTextData::Span span; + span.start = sd->text.length(); + span.end = span.start + p_text.length(); + // Pre-sort fonts, push fonts with the language support first. + for (int i = 0; i < p_fonts.size(); i++) { + if (font_is_language_supported(p_fonts[i], p_language)) { + span.fonts.push_back(p_fonts[i]); + } + } + // Push the rest valid fonts. + for (int i = 0; i < p_fonts.size(); i++) { + if (!font_is_language_supported(p_fonts[i], p_language)) { + span.fonts.push_back(p_fonts[i]); + } + } + ERR_FAIL_COND_V(span.fonts.empty(), false); + span.font_size = p_size; + span.language = p_language; + + sd->spans.push_back(span); + sd->text += p_text; + sd->end += p_text.length(); + invalidate(sd); + + return true; +} + +bool TextServerFallback::shaped_text_add_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align, int p_length) { + _THREAD_SAFE_METHOD_ + ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, false); + ERR_FAIL_COND_V(p_key == Variant(), false); + ERR_FAIL_COND_V(sd->objects.has(p_key), false); + + if (sd->parent != RID()) { + full_copy(sd); + } + + ShapedTextData::Span span; + span.start = sd->text.length(); + span.end = span.start + p_length; + span.embedded_key = p_key; + + ShapedTextData::EmbeddedObject obj; + obj.inline_align = p_inline_align; + obj.rect.size = p_size; + obj.pos = span.start; + + sd->spans.push_back(span); + sd->text += String::chr(0xfffc).repeat(p_length); + sd->end += p_length; + sd->objects[p_key] = obj; + invalidate(sd); + + return true; +} + +bool TextServerFallback::shaped_text_resize_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align) { + _THREAD_SAFE_METHOD_ + ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, false); + ERR_FAIL_COND_V(!sd->objects.has(p_key), false); + sd->objects[p_key].rect.size = p_size; + sd->objects[p_key].inline_align = p_inline_align; + if (sd->valid) { + // Recalc string metrics. + sd->ascent = 0; + sd->descent = 0; + sd->width = 0; + sd->upos = 0; + sd->uthk = 0; + for (int i = 0; i < sd->glyphs.size(); i++) { + Glyph gl = sd->glyphs[i]; + Variant key; + if (gl.count == 1) { + for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = sd->objects.front(); E; E = E->next()) { + if (E->get().pos == gl.start) { + key = E->key(); + break; + } + } + } + if (key != Variant()) { + if (sd->orientation == ORIENTATION_HORIZONTAL) { + sd->objects[key].rect.position.x = sd->width; + sd->width += sd->objects[key].rect.size.x; + switch (sd->objects[key].inline_align) { + case VALIGN_TOP: { + sd->ascent = MAX(sd->ascent, sd->objects[key].rect.size.y); + } break; + case VALIGN_CENTER: { + sd->ascent = MAX(sd->ascent, sd->objects[key].rect.size.y / 2); + sd->descent = MAX(sd->descent, sd->objects[key].rect.size.y / 2); + } break; + case VALIGN_BOTTOM: { + sd->descent = MAX(sd->descent, sd->objects[key].rect.size.y); + } break; + } + sd->glyphs.write[i].advance = sd->objects[key].rect.size.x; + } else { + sd->objects[key].rect.position.y = sd->width; + sd->width += sd->objects[key].rect.size.y; + switch (sd->objects[key].inline_align) { + case VALIGN_TOP: { + sd->ascent = MAX(sd->ascent, sd->objects[key].rect.size.x); + } break; + case VALIGN_CENTER: { + sd->ascent = MAX(sd->ascent, sd->objects[key].rect.size.x / 2); + sd->descent = MAX(sd->descent, sd->objects[key].rect.size.x / 2); + } break; + case VALIGN_BOTTOM: { + sd->descent = MAX(sd->descent, sd->objects[key].rect.size.x); + } break; + } + sd->glyphs.write[i].advance = sd->objects[key].rect.size.y; + } + } else { + const FontDataFallback *fd = font_owner.getornull(gl.font_rid); + if (fd != nullptr) { + if (sd->orientation == ORIENTATION_HORIZONTAL) { + sd->ascent = MAX(sd->ascent, fd->get_ascent(gl.font_size)); + sd->descent = MAX(sd->descent, fd->get_descent(gl.font_size)); + } else { + sd->ascent = MAX(sd->ascent, fd->get_advance(gl.index, gl.font_size).x * 0.5); + sd->descent = MAX(sd->descent, fd->get_advance(gl.index, gl.font_size).x * 0.5); + } + sd->upos = MAX(sd->upos, font_get_underline_position(gl.font_rid, gl.font_size)); + sd->uthk = MAX(sd->uthk, font_get_underline_thickness(gl.font_rid, gl.font_size)); + } else if (sd->preserve_invalid || (sd->preserve_control && is_control(gl.index))) { + // Glyph not found, replace with hex code box. + if (sd->orientation == ORIENTATION_HORIZONTAL) { + sd->ascent = MAX(sd->ascent, get_hex_code_box_size(gl.font_size, gl.index).y * 0.75f); + sd->descent = MAX(sd->descent, get_hex_code_box_size(gl.font_size, gl.index).y * 0.25f); + } else { + sd->ascent = MAX(sd->ascent, get_hex_code_box_size(gl.font_size, gl.index).x * 0.5f); + sd->descent = MAX(sd->descent, get_hex_code_box_size(gl.font_size, gl.index).x * 0.5f); + } + } + sd->width += gl.advance * gl.repeat; + } + } + + // Align embedded objects to baseline. + for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = sd->objects.front(); E; E = E->next()) { + if ((E->get().pos >= sd->start) && (E->get().pos < sd->end)) { + if (sd->orientation == ORIENTATION_HORIZONTAL) { + switch (E->get().inline_align) { + case VALIGN_TOP: { + E->get().rect.position.y = -sd->ascent; + } break; + case VALIGN_CENTER: { + E->get().rect.position.y = -(E->get().rect.size.y / 2); + } break; + case VALIGN_BOTTOM: { + E->get().rect.position.y = sd->descent - E->get().rect.size.y; + } break; + } + } else { + switch (E->get().inline_align) { + case VALIGN_TOP: { + E->get().rect.position.x = -sd->ascent; + } break; + case VALIGN_CENTER: { + E->get().rect.position.x = -(E->get().rect.size.x / 2); + } break; + case VALIGN_BOTTOM: { + E->get().rect.position.x = sd->descent - E->get().rect.size.x; + } break; + } + } + } + } + } + return true; +} + +RID TextServerFallback::shaped_text_substr(RID p_shaped, int p_start, int p_length) const { + _THREAD_SAFE_METHOD_ + const ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, RID()); + if (sd->parent != RID()) { + return shaped_text_substr(sd->parent, p_start, p_length); + } + if (!sd->valid) { + const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + } + ERR_FAIL_COND_V(p_start < 0 || p_length < 0, RID()); + ERR_FAIL_COND_V(sd->start > p_start || sd->end < p_start, RID()); + ERR_FAIL_COND_V(sd->end < p_start + p_length, RID()); + + ShapedTextData *new_sd = memnew(ShapedTextData); + new_sd->parent = p_shaped; + new_sd->start = p_start; + new_sd->end = p_start + p_length; + + new_sd->orientation = sd->orientation; + new_sd->direction = sd->direction; + new_sd->para_direction = sd->para_direction; + new_sd->line_breaks_valid = sd->line_breaks_valid; + new_sd->justification_ops_valid = sd->justification_ops_valid; + new_sd->sort_valid = false; + new_sd->upos = sd->upos; + new_sd->uthk = sd->uthk; + + if (p_length > 0) { + new_sd->text = sd->text.substr(p_start, p_length); + + for (int i = 0; i < sd->glyphs.size(); i++) { + if ((sd->glyphs[i].start >= new_sd->start) && (sd->glyphs[i].end <= new_sd->end)) { + Glyph gl = sd->glyphs[i]; + Variant key; + if (gl.count == 1) { + for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = sd->objects.front(); E; E = E->next()) { + if (E->get().pos == gl.start) { + key = E->key(); + new_sd->objects[key] = E->get(); + break; + } + } + } + if (key != Variant()) { + if (new_sd->orientation == ORIENTATION_HORIZONTAL) { + new_sd->objects[key].rect.position.x = new_sd->width; + new_sd->width += new_sd->objects[key].rect.size.x; + switch (new_sd->objects[key].inline_align) { + case VALIGN_TOP: { + new_sd->ascent = MAX(new_sd->ascent, new_sd->objects[key].rect.size.y); + } break; + case VALIGN_CENTER: { + new_sd->ascent = MAX(new_sd->ascent, new_sd->objects[key].rect.size.y / 2); + new_sd->descent = MAX(new_sd->descent, new_sd->objects[key].rect.size.y / 2); + } break; + case VALIGN_BOTTOM: { + new_sd->descent = MAX(new_sd->descent, new_sd->objects[key].rect.size.y); + } break; + } + } else { + new_sd->objects[key].rect.position.y = new_sd->width; + new_sd->width += new_sd->objects[key].rect.size.y; + switch (new_sd->objects[key].inline_align) { + case VALIGN_TOP: { + new_sd->ascent = MAX(new_sd->ascent, new_sd->objects[key].rect.size.x); + } break; + case VALIGN_CENTER: { + new_sd->ascent = MAX(new_sd->ascent, new_sd->objects[key].rect.size.x / 2); + new_sd->descent = MAX(new_sd->descent, new_sd->objects[key].rect.size.x / 2); + } break; + case VALIGN_BOTTOM: { + new_sd->descent = MAX(new_sd->descent, new_sd->objects[key].rect.size.x); + } break; + } + } + } else { + const FontDataFallback *fd = font_owner.getornull(gl.font_rid); + if (fd != nullptr) { + if (new_sd->orientation == ORIENTATION_HORIZONTAL) { + new_sd->ascent = MAX(new_sd->ascent, fd->get_ascent(gl.font_size)); + new_sd->descent = MAX(new_sd->descent, fd->get_descent(gl.font_size)); + } else { + new_sd->ascent = MAX(new_sd->ascent, fd->get_advance(gl.index, gl.font_size).x * 0.5); + new_sd->descent = MAX(new_sd->descent, fd->get_advance(gl.index, gl.font_size).x * 0.5); + } + } else if (new_sd->preserve_invalid || (new_sd->preserve_control && is_control(gl.index))) { + // Glyph not found, replace with hex code box. + if (new_sd->orientation == ORIENTATION_HORIZONTAL) { + new_sd->ascent = MAX(new_sd->ascent, get_hex_code_box_size(gl.font_size, gl.index).y * 0.75f); + new_sd->descent = MAX(new_sd->descent, get_hex_code_box_size(gl.font_size, gl.index).y * 0.25f); + } else { + new_sd->ascent = MAX(new_sd->ascent, get_hex_code_box_size(gl.font_size, gl.index).x * 0.5f); + new_sd->descent = MAX(new_sd->descent, get_hex_code_box_size(gl.font_size, gl.index).x * 0.5f); + } + } + new_sd->width += gl.advance * gl.repeat; + } + new_sd->glyphs.push_back(gl); + } + } + + for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = new_sd->objects.front(); E; E = E->next()) { + if ((E->get().pos >= new_sd->start) && (E->get().pos < new_sd->end)) { + if (sd->orientation == ORIENTATION_HORIZONTAL) { + switch (E->get().inline_align) { + case VALIGN_TOP: { + E->get().rect.position.y = -new_sd->ascent; + } break; + case VALIGN_CENTER: { + E->get().rect.position.y = -(E->get().rect.size.y / 2); + } break; + case VALIGN_BOTTOM: { + E->get().rect.position.y = new_sd->descent - E->get().rect.size.y; + } break; + } + } else { + switch (E->get().inline_align) { + case VALIGN_TOP: { + E->get().rect.position.x = -new_sd->ascent; + } break; + case VALIGN_CENTER: { + E->get().rect.position.x = -(E->get().rect.size.x / 2); + } break; + case VALIGN_BOTTOM: { + E->get().rect.position.x = new_sd->descent - E->get().rect.size.x; + } break; + } + } + } + } + } + new_sd->valid = true; + + return shaped_owner.make_rid(new_sd); +} + +RID TextServerFallback::shaped_text_get_parent(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, RID()); + return sd->parent; +} + +float TextServerFallback::shaped_text_fit_to_width(RID p_shaped, float p_width, uint8_t /*JustificationFlag*/ p_jst_flags) { + _THREAD_SAFE_METHOD_ + ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, 0.f); + if (!sd->valid) { + const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + } + if (!sd->justification_ops_valid) { + const_cast<TextServerFallback *>(this)->shaped_text_update_justification_ops(p_shaped); + } + + int start_pos = 0; + int end_pos = sd->glyphs.size() - 1; + + if ((p_jst_flags & JUSTIFICATION_AFTER_LAST_TAB) == JUSTIFICATION_AFTER_LAST_TAB) { + int start, end, delta; + if (sd->para_direction == DIRECTION_LTR) { + start = sd->glyphs.size() - 1; + end = -1; + delta = -1; + } else { + start = 0; + end = sd->glyphs.size(); + delta = +1; + } + + for (int i = start; i != end; i += delta) { + if ((sd->glyphs[i].flags & GRAPHEME_IS_TAB) == GRAPHEME_IS_TAB) { + if (sd->para_direction == DIRECTION_LTR) { + start_pos = i; + break; + } else { + end_pos = i; + break; + } + } + } + } + + if ((p_jst_flags & JUSTIFICATION_TRIM_EDGE_SPACES) == JUSTIFICATION_TRIM_EDGE_SPACES) { + while ((start_pos < end_pos) && ((sd->glyphs[start_pos].flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE || (sd->glyphs[start_pos].flags & GRAPHEME_IS_BREAK_HARD) == GRAPHEME_IS_BREAK_HARD || (sd->glyphs[start_pos].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT)) { + sd->width -= sd->glyphs[start_pos].advance * sd->glyphs[start_pos].repeat; + sd->glyphs.write[start_pos].advance = 0; + start_pos += sd->glyphs[start_pos].count; + } + while ((start_pos < end_pos) && ((sd->glyphs[end_pos].flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE || (sd->glyphs[end_pos].flags & GRAPHEME_IS_BREAK_HARD) == GRAPHEME_IS_BREAK_HARD || (sd->glyphs[end_pos].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT)) { + sd->width -= sd->glyphs[end_pos].advance * sd->glyphs[end_pos].repeat; + sd->glyphs.write[end_pos].advance = 0; + end_pos -= sd->glyphs[end_pos].count; + } + } + + int space_count = 0; + for (int i = start_pos; i <= end_pos; i++) { + const Glyph &gl = sd->glyphs[i]; + if (gl.count > 0) { + if ((gl.flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE) { + space_count++; + } + } + } + + if ((space_count > 0) && ((p_jst_flags & JUSTIFICATION_WORD_BOUND) == JUSTIFICATION_WORD_BOUND)) { + float delta_width_per_space = (p_width - sd->width) / space_count; + for (int i = start_pos; i <= end_pos; i++) { + Glyph &gl = sd->glyphs.write[i]; + if (gl.count > 0) { + if ((gl.flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE) { + float old_adv = gl.advance; + gl.advance = MAX(gl.advance + delta_width_per_space, 0.05 * gl.font_size); + sd->width += (gl.advance - old_adv); + } + } + } + } + + return sd->width; +} + +float TextServerFallback::shaped_text_tab_align(RID p_shaped, const Vector<float> &p_tab_stops) { + _THREAD_SAFE_METHOD_ + ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, 0.f); + if (!sd->valid) { + const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + } + if (!sd->line_breaks_valid) { + const_cast<TextServerFallback *>(this)->shaped_text_update_breaks(p_shaped); + } + + int tab_index = 0; + float off = 0.f; + + int start, end, delta; + if (sd->para_direction == DIRECTION_LTR) { + start = 0; + end = sd->glyphs.size(); + delta = +1; + } else { + start = sd->glyphs.size() - 1; + end = -1; + delta = -1; + } + + for (int i = start; i != end; i += delta) { + if ((sd->glyphs[i].flags & GRAPHEME_IS_TAB) == GRAPHEME_IS_TAB) { + float tab_off = 0.f; + while (tab_off <= off) { + tab_off += p_tab_stops[tab_index]; + tab_index++; + if (tab_index >= p_tab_stops.size()) { + tab_index = 0; + } + } + float old_adv = sd->glyphs.write[i].advance; + sd->glyphs.write[i].advance = (tab_off - off); + sd->width += sd->glyphs.write[i].advance - old_adv; + off = 0; + continue; + } + off += sd->glyphs[i].advance * sd->glyphs[i].repeat; + } + + return 0.f; +} + +bool TextServerFallback::shaped_text_update_breaks(RID p_shaped) { + _THREAD_SAFE_METHOD_ + ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, false); + if (!sd->valid) { + shaped_text_shape(p_shaped); + } + + if (sd->line_breaks_valid) { + return true; // Noting to do. + } + + for (int i = 0; i < sd->glyphs.size(); i++) { + if (sd->glyphs[i].count > 0) { + char32_t c = sd->text[sd->glyphs[i].start]; + if (is_whitespace(c) && !is_linebreak(c)) { + sd->glyphs.write[i].flags |= GRAPHEME_IS_SPACE; + sd->glyphs.write[i].flags |= GRAPHEME_IS_BREAK_SOFT; + } + if (is_linebreak(c)) { + sd->glyphs.write[i].flags |= GRAPHEME_IS_BREAK_HARD; + } + if (c == 0x0009 || c == 0x000b) { + sd->glyphs.write[i].flags |= GRAPHEME_IS_TAB; + } + + i += (sd->glyphs[i].count - 1); + } + } + sd->line_breaks_valid = true; + return sd->line_breaks_valid; +} + +bool TextServerFallback::shaped_text_update_justification_ops(RID p_shaped) { + _THREAD_SAFE_METHOD_ + ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, false); + if (!sd->valid) { + shaped_text_shape(p_shaped); + } + if (!sd->line_breaks_valid) { + shaped_text_update_breaks(p_shaped); + } + + sd->justification_ops_valid = true; // Not supported by fallback server. + return true; +} + +bool TextServerFallback::shaped_text_shape(RID p_shaped) { + _THREAD_SAFE_METHOD_ + ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, false); + if (sd->valid) { + return true; + } + + if (sd->parent != RID()) { + full_copy(sd); + } + + // Cleanup. + sd->justification_ops_valid = false; + sd->line_breaks_valid = false; + sd->ascent = 0.f; + sd->descent = 0.f; + sd->width = 0.f; + sd->glyphs.clear(); + + if (sd->text.length() == 0) { + sd->valid = true; + return true; + } + + // "Shape" string. + for (int i = 0; i < sd->spans.size(); i++) { + const ShapedTextData::Span &span = sd->spans[i]; + if (span.embedded_key != Variant()) { + // Embedded object. + if (sd->orientation == ORIENTATION_HORIZONTAL) { + sd->objects[span.embedded_key].rect.position.x = sd->width; + sd->width += sd->objects[span.embedded_key].rect.size.x; + switch (sd->objects[span.embedded_key].inline_align) { + case VALIGN_TOP: { + sd->ascent = MAX(sd->ascent, sd->objects[span.embedded_key].rect.size.y); + } break; + case VALIGN_CENTER: { + sd->ascent = MAX(sd->ascent, sd->objects[span.embedded_key].rect.size.y / 2); + sd->descent = MAX(sd->descent, sd->objects[span.embedded_key].rect.size.y / 2); + } break; + case VALIGN_BOTTOM: { + sd->descent = MAX(sd->descent, sd->objects[span.embedded_key].rect.size.y); + } break; + } + } else { + sd->objects[span.embedded_key].rect.position.y = sd->width; + sd->width += sd->objects[span.embedded_key].rect.size.y; + switch (sd->objects[span.embedded_key].inline_align) { + case VALIGN_TOP: { + sd->ascent = MAX(sd->ascent, sd->objects[span.embedded_key].rect.size.x); + } break; + case VALIGN_CENTER: { + sd->ascent = MAX(sd->ascent, sd->objects[span.embedded_key].rect.size.x / 2); + sd->descent = MAX(sd->descent, sd->objects[span.embedded_key].rect.size.x / 2); + } break; + case VALIGN_BOTTOM: { + sd->descent = MAX(sd->descent, sd->objects[span.embedded_key].rect.size.x); + } break; + } + } + Glyph gl; + gl.start = span.start; + gl.end = span.end; + gl.count = 1; + gl.index = 0; + gl.flags = GRAPHEME_IS_VALID | GRAPHEME_IS_VIRTUAL; + if (sd->orientation == ORIENTATION_HORIZONTAL) { + gl.advance = sd->objects[span.embedded_key].rect.size.x; + } else { + gl.advance = sd->objects[span.embedded_key].rect.size.y; + } + sd->glyphs.push_back(gl); + } else { + // Text span. + for (int j = span.start; j < span.end; j++) { + const FontDataFallback *fd = nullptr; + + Glyph gl; + gl.start = j; + gl.end = j + 1; + gl.count = 1; + gl.font_size = span.font_size; + gl.index = (uint32_t)sd->text[j]; // Use codepoint. + if (gl.index == 0x0009 || gl.index == 0x000b) { + gl.index = 0x0020; + } + if (!sd->preserve_control && is_control(gl.index)) { + gl.index = 0x0020; + } + // Select first font which has character (font are already sorted by span language). + for (int k = 0; k < span.fonts.size(); k++) { + fd = font_owner.getornull(span.fonts[k]); + if (fd != nullptr && fd->has_char(gl.index)) { + gl.font_rid = span.fonts[k]; + break; + } + } + + if (gl.font_rid != RID()) { + if (sd->text[j] != 0 && !is_linebreak(sd->text[j])) { + if (sd->orientation == ORIENTATION_HORIZONTAL) { + gl.advance = fd->get_advance(gl.index, gl.font_size).x; + gl.x_off = 0; + gl.y_off = 0; + sd->ascent = MAX(sd->ascent, fd->get_ascent(gl.font_size)); + sd->descent = MAX(sd->descent, fd->get_descent(gl.font_size)); + } else { + gl.advance = fd->get_advance(gl.index, gl.font_size).y; + gl.x_off = -fd->get_advance(gl.index, gl.font_size).x * 0.5; + gl.y_off = fd->get_ascent(gl.font_size); + sd->ascent = MAX(sd->ascent, fd->get_advance(gl.index, gl.font_size).x * 0.5); + sd->descent = MAX(sd->descent, fd->get_advance(gl.index, gl.font_size).x * 0.5); + } + } + sd->upos = MAX(sd->upos, font_get_underline_position(gl.font_rid, gl.font_size)); + sd->uthk = MAX(sd->uthk, font_get_underline_thickness(gl.font_rid, gl.font_size)); + + // Add kerning to previous glyph. + if (sd->glyphs.size() > 0) { + Glyph &prev_gl = sd->glyphs.write[sd->glyphs.size() - 1]; + if (prev_gl.font_rid == gl.font_rid && prev_gl.font_size == gl.font_size) { + if (sd->orientation == ORIENTATION_HORIZONTAL) { + prev_gl.advance += fd->get_kerning(prev_gl.index, gl.index, gl.font_size).x; + } else { + prev_gl.advance += fd->get_kerning(prev_gl.index, gl.index, gl.font_size).y; + } + } + } + } else if (sd->preserve_invalid || (sd->preserve_control && is_control(gl.index))) { + // Glyph not found, replace with hex code box. + if (sd->orientation == ORIENTATION_HORIZONTAL) { + gl.advance = get_hex_code_box_size(gl.font_size, gl.index).x; + sd->ascent = MAX(sd->ascent, get_hex_code_box_size(gl.font_size, gl.index).y * 0.75f); + sd->descent = MAX(sd->descent, get_hex_code_box_size(gl.font_size, gl.index).y * 0.25f); + } else { + gl.advance = get_hex_code_box_size(gl.font_size, gl.index).y; + sd->ascent = MAX(sd->ascent, get_hex_code_box_size(gl.font_size, gl.index).x * 0.5f); + sd->descent = MAX(sd->descent, get_hex_code_box_size(gl.font_size, gl.index).x * 0.5f); + } + } + sd->width += gl.advance; + sd->glyphs.push_back(gl); + } + } + } + + // Align embedded objects to baseline. + for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = sd->objects.front(); E; E = E->next()) { + if (sd->orientation == ORIENTATION_HORIZONTAL) { + switch (E->get().inline_align) { + case VALIGN_TOP: { + E->get().rect.position.y = -sd->ascent; + } break; + case VALIGN_CENTER: { + E->get().rect.position.y = -(E->get().rect.size.y / 2); + } break; + case VALIGN_BOTTOM: { + E->get().rect.position.y = sd->descent - E->get().rect.size.y; + } break; + } + } else { + switch (E->get().inline_align) { + case VALIGN_TOP: { + E->get().rect.position.x = -sd->ascent; + } break; + case VALIGN_CENTER: { + E->get().rect.position.x = -(E->get().rect.size.x / 2); + } break; + case VALIGN_BOTTOM: { + E->get().rect.position.x = sd->descent - E->get().rect.size.x; + } break; + } + } + } + + sd->valid = true; + return sd->valid; +} + +bool TextServerFallback::shaped_text_is_ready(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, false); + return sd->valid; +} + +Vector<TextServer::Glyph> TextServerFallback::shaped_text_get_glyphs(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, Vector<TextServer::Glyph>()); + if (!sd->valid) { + const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + } + return sd->glyphs; +} + +Vector2i TextServerFallback::shaped_text_get_range(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, Vector2i()); + return Vector2(sd->start, sd->end); +} + +Vector<TextServer::Glyph> TextServerFallback::shaped_text_sort_logical(RID p_shaped) { + _THREAD_SAFE_METHOD_ + const ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, Vector<TextServer::Glyph>()); + if (!sd->valid) { + const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + } + + return sd->glyphs; // Already in the logical order, return as is. +} + +Array TextServerFallback::shaped_text_get_objects(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + Array ret; + const ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, ret); + for (const Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = sd->objects.front(); E; E = E->next()) { + ret.push_back(E->key()); + } + + return ret; +} + +Rect2 TextServerFallback::shaped_text_get_object_rect(RID p_shaped, Variant p_key) const { + _THREAD_SAFE_METHOD_ + const ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, Rect2()); + ERR_FAIL_COND_V(!sd->objects.has(p_key), Rect2()); + if (!sd->valid) { + const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + } + return sd->objects[p_key].rect; +} + +Size2 TextServerFallback::shaped_text_get_size(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, Size2()); + if (!sd->valid) { + const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + } + if (sd->orientation == TextServer::ORIENTATION_HORIZONTAL) { + return Size2(sd->width, sd->ascent + sd->descent); + } else { + return Size2(sd->ascent + sd->descent, sd->width); + } +} + +float TextServerFallback::shaped_text_get_ascent(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, 0.f); + if (!sd->valid) { + const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + } + return sd->ascent; +} + +float TextServerFallback::shaped_text_get_descent(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, 0.f); + if (!sd->valid) { + const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + } + return sd->descent; +} + +float TextServerFallback::shaped_text_get_width(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, 0.f); + if (!sd->valid) { + const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + } + return sd->width; +} + +float TextServerFallback::shaped_text_get_underline_position(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, 0.f); + if (!sd->valid) { + const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + } + + return sd->upos; +} + +float TextServerFallback::shaped_text_get_underline_thickness(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + const ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V(!sd, 0.f); + if (!sd->valid) { + const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + } + + return sd->uthk; +} + +TextServer *TextServerFallback::create_func(Error &r_error, void *p_user_data) { + r_error = OK; + return memnew(TextServerFallback()); +} + +void TextServerFallback::register_server() { + TextServerManager::register_create_function(interface_name, interface_features, create_func, nullptr); +} diff --git a/modules/text_server_fb/text_server_fb.h b/modules/text_server_fb/text_server_fb.h new file mode 100644 index 0000000000..56bb1f7bf9 --- /dev/null +++ b/modules/text_server_fb/text_server_fb.h @@ -0,0 +1,193 @@ +/*************************************************************************/ +/* text_server_fb.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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. */ +/*************************************************************************/ + +#ifndef TEXT_SERVER_FALLBACK_H +#define TEXT_SERVER_FALLBACK_H + +/*************************************************************************/ +/* Fallback Text Server provides simplified TS functionality, without */ +/* BiDi, shaping and advanced font features support. */ +/*************************************************************************/ + +#include "servers/text_server.h" + +#include "core/templates/rid_owner.h" + +#include "scene/resources/texture.h" + +#include "font_fb.h" + +class TextServerFallback : public TextServer { + GDCLASS(TextServerFallback, TextServer); + _THREAD_SAFE_CLASS_ + + float oversampling = 1.f; + mutable RID_PtrOwner<FontDataFallback> font_owner; + mutable RID_PtrOwner<ShapedTextData> shaped_owner; + + static String interface_name; + static uint32_t interface_features; + +protected: + static void _bind_methods(){}; + + void full_copy(ShapedTextData *p_shaped); + void invalidate(ShapedTextData *p_shaped); + +public: + virtual bool has_feature(Feature p_feature) override; + virtual String get_name() const override; + + virtual void free(RID p_rid) override; + virtual bool has(RID p_rid) override; + virtual bool load_support_data(const String &p_filename) override; + +#ifdef TOOLS_ENABLED + virtual String get_support_data_filename() override { return ""; }; + virtual String get_support_data_info() override { return "Not supported"; }; + virtual bool save_support_data(const String &p_filename) override; +#endif + + virtual bool is_locale_right_to_left(const String &p_locale) override; + + /* Font interface */ + virtual RID create_font_system(const String &p_name, int p_base_size = 16) override; + virtual RID create_font_resource(const String &p_filename, int p_base_size = 16) override; + virtual RID create_font_memory(const uint8_t *p_data, size_t p_size, const String &p_type, int p_base_size = 16) override; + + virtual float font_get_height(RID p_font, int p_size) const override; + virtual float font_get_ascent(RID p_font, int p_size) const override; + virtual float font_get_descent(RID p_font, int p_size) const override; + + virtual float font_get_underline_position(RID p_font, int p_size) const override; + virtual float font_get_underline_thickness(RID p_font, int p_size) const override; + + virtual void font_set_antialiased(RID p_font, bool p_antialiased) override; + virtual bool font_get_antialiased(RID p_font) const override; + + virtual void font_set_hinting(RID p_font, Hinting p_hinting) override; + virtual Hinting font_get_hinting(RID p_font) const override; + + virtual void font_set_force_autohinter(RID p_font, bool p_enabeld) override; + virtual bool font_get_force_autohinter(RID p_font) const override; + + virtual bool font_has_char(RID p_font, char32_t p_char) const override; + virtual String font_get_supported_chars(RID p_font) const override; + + virtual void font_set_distance_field_hint(RID p_font, bool p_distance_field) override; + virtual bool font_get_distance_field_hint(RID p_font) const override; + + virtual bool font_has_outline(RID p_font) const override; + virtual float font_get_base_size(RID p_font) const override; + + virtual bool font_is_language_supported(RID p_font, const String &p_language) const override; + virtual void font_set_language_support_override(RID p_font, const String &p_language, bool p_supported) override; + virtual bool font_get_language_support_override(RID p_font, const String &p_language) override; + virtual void font_remove_language_support_override(RID p_font, const String &p_language) override; + Vector<String> font_get_language_support_overrides(RID p_font) override; + + virtual bool font_is_script_supported(RID p_font, const String &p_script) const override; + virtual void font_set_script_support_override(RID p_font, const String &p_script, bool p_supported) override; + virtual bool font_get_script_support_override(RID p_font, const String &p_script) override; + virtual void font_remove_script_support_override(RID p_font, const String &p_script) override; + Vector<String> font_get_script_support_overrides(RID p_font) override; + + virtual uint32_t font_get_glyph_index(RID p_font, char32_t p_char, char32_t p_variation_selector = 0x0000) const override; + virtual Vector2 font_get_glyph_advance(RID p_font, uint32_t p_index, int p_size) const override; + virtual Vector2 font_get_glyph_kerning(RID p_font, uint32_t p_index_a, uint32_t p_index_b, int p_size) const override; + + virtual Vector2 font_draw_glyph(RID p_font, RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color = Color(1, 1, 1)) const override; + virtual Vector2 font_draw_glyph_outline(RID p_font, RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color = Color(1, 1, 1)) const override; + + virtual float font_get_oversampling() const override; + virtual void font_set_oversampling(float p_oversampling) override; + + virtual Vector<String> get_system_fonts() const override; + + /* Shaped text buffer interface */ + + virtual RID create_shaped_text(Direction p_direction = DIRECTION_AUTO, Orientation p_orientation = ORIENTATION_HORIZONTAL) override; + + virtual void shaped_text_clear(RID p_shaped) override; + + virtual void shaped_text_set_direction(RID p_shaped, Direction p_direction = DIRECTION_AUTO) override; + virtual Direction shaped_text_get_direction(RID p_shaped) const override; + + virtual void shaped_text_set_bidi_override(RID p_shaped, const Vector<Vector2i> &p_override) override; + + virtual void shaped_text_set_orientation(RID p_shaped, Orientation p_orientation = ORIENTATION_HORIZONTAL) override; + virtual Orientation shaped_text_get_orientation(RID p_shaped) const override; + + virtual void shaped_text_set_preserve_invalid(RID p_shaped, bool p_enabled) override; + virtual bool shaped_text_get_preserve_invalid(RID p_shaped) const override; + + virtual void shaped_text_set_preserve_control(RID p_shaped, bool p_enabled) override; + virtual bool shaped_text_get_preserve_control(RID p_shaped) const override; + + virtual bool shaped_text_add_string(RID p_shaped, const String &p_text, const Vector<RID> &p_fonts, int p_size, const Dictionary &p_opentype_features = Dictionary(), const String &p_language = "") override; + virtual bool shaped_text_add_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align = VALIGN_CENTER, int p_length = 1) override; + virtual bool shaped_text_resize_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align = VALIGN_CENTER) override; + + virtual RID shaped_text_substr(RID p_shaped, int p_start, int p_length) const override; + virtual RID shaped_text_get_parent(RID p_shaped) const override; + + virtual float shaped_text_fit_to_width(RID p_shaped, float p_width, uint8_t /*JustificationFlag*/ p_jst_flags = JUSTIFICATION_WORD_BOUND | JUSTIFICATION_KASHIDA) override; + virtual float shaped_text_tab_align(RID p_shaped, const Vector<float> &p_tab_stops) override; + + virtual bool shaped_text_shape(RID p_shaped) override; + virtual bool shaped_text_update_breaks(RID p_shaped) override; + virtual bool shaped_text_update_justification_ops(RID p_shaped) override; + + virtual bool shaped_text_is_ready(RID p_shaped) const override; + + virtual Vector<Glyph> shaped_text_get_glyphs(RID p_shaped) const override; + + virtual Vector2i shaped_text_get_range(RID p_shaped) const override; + + virtual Vector<Glyph> shaped_text_sort_logical(RID p_shaped) override; + + virtual Array shaped_text_get_objects(RID p_shaped) const override; + virtual Rect2 shaped_text_get_object_rect(RID p_shaped, Variant p_key) const override; + + virtual Size2 shaped_text_get_size(RID p_shaped) const override; + virtual float shaped_text_get_ascent(RID p_shaped) const override; + virtual float shaped_text_get_descent(RID p_shaped) const override; + virtual float shaped_text_get_width(RID p_shaped) const override; + virtual float shaped_text_get_underline_position(RID p_shaped) const override; + virtual float shaped_text_get_underline_thickness(RID p_shaped) const override; + + static TextServer *create_func(Error &r_error, void *p_user_data); + static void register_server(); + + TextServerFallback(){}; + ~TextServerFallback(){}; +}; + +#endif // TEXT_SERVER_FALLBACK_H diff --git a/modules/upnp/upnp.h b/modules/upnp/upnp.h index e87f93e697..81d770ec4c 100644 --- a/modules/upnp/upnp.h +++ b/modules/upnp/upnp.h @@ -57,7 +57,6 @@ protected: public: enum UPNPResult { - UPNP_RESULT_SUCCESS, UPNP_RESULT_NOT_AUTHORIZED, UPNP_RESULT_PORT_MAPPING_NOT_FOUND, diff --git a/modules/upnp/upnp_device.h b/modules/upnp/upnp_device.h index a287c99b0d..53d621c90a 100644 --- a/modules/upnp/upnp_device.h +++ b/modules/upnp/upnp_device.h @@ -38,7 +38,6 @@ class UPNPDevice : public Reference { public: enum IGDStatus { - IGD_STATUS_OK, IGD_STATUS_HTTP_ERROR, IGD_STATUS_HTTP_EMPTY, diff --git a/modules/visual_script/doc_classes/VisualScriptLists.xml b/modules/visual_script/doc_classes/VisualScriptLists.xml index 5b64d8438b..8a7254b46a 100644 --- a/modules/visual_script/doc_classes/VisualScriptLists.xml +++ b/modules/visual_script/doc_classes/VisualScriptLists.xml @@ -4,7 +4,7 @@ A Visual Script virtual class for in-graph editable nodes. </brief_description> <description> - A Visual Script virtual class that defines the shape and the default behaviour of the nodes that have to be in-graph editable nodes. + A Visual Script virtual class that defines the shape and the default behavior of the nodes that have to be in-graph editable nodes. </description> <tutorials> </tutorials> diff --git a/modules/visual_script/visual_script.cpp b/modules/visual_script/visual_script.cpp index 1c7d5472cb..b10d4523f2 100644 --- a/modules/visual_script/visual_script.cpp +++ b/modules/visual_script/visual_script.cpp @@ -2635,7 +2635,6 @@ void VisualScriptLanguage::debug_get_stack_level_locals(int p_level, List<String f->debug_get_stack_member_state(*_call_stack[l].line,&locals); for( List<Pair<StringName,int> >::Element *E = locals.front();E;E=E->next() ) { - p_locals->push_back(E->get().first); p_values->push_back(_call_stack[l].stack[E->get().second]); } diff --git a/modules/visual_script/visual_script_builtin_funcs.cpp b/modules/visual_script/visual_script_builtin_funcs.cpp index a27307aec2..fe0c399f8d 100644 --- a/modules/visual_script/visual_script_builtin_funcs.cpp +++ b/modules/visual_script/visual_script_builtin_funcs.cpp @@ -647,7 +647,6 @@ PropertyInfo VisualScriptBuiltinFunc::get_output_value_port_info(int p_idx) cons /* String VisualScriptBuiltinFunc::get_caption() const { - return "BuiltinFunc"; } diff --git a/modules/visual_script/visual_script_editor.cpp b/modules/visual_script/visual_script_editor.cpp index 1bb96a47f3..64abd3dd84 100644 --- a/modules/visual_script/visual_script_editor.cpp +++ b/modules/visual_script/visual_script_editor.cpp @@ -719,6 +719,7 @@ void VisualScriptEditor::_update_graph(int p_only_id) { line_edit->set_text(node->get_text()); line_edit->set_expand_to_text_length(true); line_edit->add_theme_font_override("font", get_theme_font("source", "EditorFonts")); + line_edit->add_theme_font_size_override("font_size", get_theme_font_size("source_size", "EditorFonts")); gnode->add_child(line_edit); line_edit->connect("text_changed", callable_mp(this, &VisualScriptEditor::_expression_text_changed), varray(E->get())); } else { @@ -4728,6 +4729,7 @@ VisualScriptEditor::VisualScriptEditor() { saved_position = Vector2(0, 0); edit_menu = memnew(MenuButton); + edit_menu->set_shortcut_context(this); edit_menu->set_text(TTR("Edit")); edit_menu->set_switch_on_hover(true); edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("visual_script_editor/delete_selected"), EDIT_DELETE_NODES); @@ -4929,7 +4931,6 @@ VisualScriptEditor::VisualScriptEditor() { updating_members = false; set_process_input(true); - set_process_unhandled_input(true); default_value_edit = memnew(CustomPropertyEditor); add_child(default_value_edit); diff --git a/modules/visual_script/visual_script_editor.h b/modules/visual_script/visual_script_editor.h index 66e435741f..5610e6b1b4 100644 --- a/modules/visual_script/visual_script_editor.h +++ b/modules/visual_script/visual_script_editor.h @@ -64,7 +64,6 @@ class VisualScriptEditor : public ScriptEditorBase { }; enum PortAction { - CREATE_CALL_SET_GET, CREATE_ACTION, }; diff --git a/modules/visual_script/visual_script_func_nodes.cpp b/modules/visual_script/visual_script_func_nodes.cpp index 34a1cfc4fc..b2aa42ef97 100644 --- a/modules/visual_script/visual_script_func_nodes.cpp +++ b/modules/visual_script/visual_script_func_nodes.cpp @@ -234,7 +234,6 @@ PropertyInfo VisualScriptFunctionCall::get_output_value_port_info(int p_idx) con /*MethodBind *mb = ClassDB::get_method(_get_base_type(),function); if (mb) { - ret = mb->get_argument_info(-1); } else {*/ diff --git a/modules/webm/doc_classes/VideoStreamWebm.xml b/modules/webm/doc_classes/VideoStreamWebm.xml index 2edbc08cc8..f3e13ba31a 100644 --- a/modules/webm/doc_classes/VideoStreamWebm.xml +++ b/modules/webm/doc_classes/VideoStreamWebm.xml @@ -5,6 +5,7 @@ </brief_description> <description> [VideoStream] resource handling the [url=https://www.webmproject.org/]WebM[/url] video format with [code].webm[/code] extension. Both the VP8 and VP9 codecs are supported. The VP8 and VP9 codecs are more efficient than [VideoStreamTheora], but they require more CPU resources to decode (especially VP9). Both the VP8 and VP9 codecs are decoded on the CPU. + [b]Note:[/b] Alpha channel (also known as transparency) is not supported. The video will always appear to have a black background, even if it originally contains an alpha channel. [b]Note:[/b] There are known bugs and performance issues with WebM video playback in Godot. If you run into problems, try using the Ogg Theora format instead: [VideoStreamTheora] </description> <tutorials> diff --git a/modules/webrtc/library_godot_webrtc.js b/modules/webrtc/library_godot_webrtc.js index b75996b1f3..f725a10a6f 100644 --- a/modules/webrtc/library_godot_webrtc.js +++ b/modules/webrtc/library_godot_webrtc.js @@ -28,12 +28,11 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -var GodotRTCDataChannel = { +const GodotRTCDataChannel = { // Our socket implementation that forwards events to C++. - $GodotRTCDataChannel__deps: ['$IDHandler', '$GodotOS'], + $GodotRTCDataChannel__deps: ['$IDHandler', '$GodotRuntime'], $GodotRTCDataChannel: { - - connect: function(p_id, p_on_open, p_on_message, p_on_error, p_on_close) { + connect: function (p_id, p_on_open, p_on_message, p_on_error, p_on_close) { const ref = IDHandler.get(p_id); if (!ref) { return; @@ -49,31 +48,31 @@ var GodotRTCDataChannel = { ref.onerror = function (event) { p_on_error(); }; - ref.onmessage = function(event) { - var buffer; - var is_string = 0; + ref.onmessage = function (event) { + let buffer; + let is_string = 0; if (event.data instanceof ArrayBuffer) { buffer = new Uint8Array(event.data); } else if (event.data instanceof Blob) { - console.error("Blob type not supported"); + GodotRuntime.error('Blob type not supported'); return; - } else if (typeof event.data === "string") { + } else if (typeof event.data === 'string') { is_string = 1; - var enc = new TextEncoder("utf-8"); + const enc = new TextEncoder('utf-8'); buffer = new Uint8Array(enc.encode(event.data)); } else { - console.error("Unknown message type"); + GodotRuntime.error('Unknown message type'); return; } - var len = buffer.length*buffer.BYTES_PER_ELEMENT; - var out = _malloc(len); + const len = buffer.length * buffer.BYTES_PER_ELEMENT; + const out = GodotRuntime.malloc(len); HEAPU8.set(buffer, out); p_on_message(out, len, is_string); - _free(out); - } + GodotRuntime.free(out); + }; }, - close: function(p_id) { + close: function (p_id) { const ref = IDHandler.get(p_id); if (!ref) { return; @@ -85,40 +84,40 @@ var GodotRTCDataChannel = { ref.close(); }, - get_prop: function(p_id, p_prop, p_def) { + get_prop: function (p_id, p_prop, p_def) { const ref = IDHandler.get(p_id); return (ref && ref[p_prop] !== undefined) ? ref[p_prop] : p_def; }, }, - godot_js_rtc_datachannel_ready_state_get: function(p_id) { + godot_js_rtc_datachannel_ready_state_get: function (p_id) { const ref = IDHandler.get(p_id); if (!ref) { return 3; // CLOSED } - switch(ref.readyState) { - case "connecting": - return 0; - case "open": - return 1; - case "closing": - return 2; - case "closed": - return 3; + switch (ref.readyState) { + case 'connecting': + return 0; + case 'open': + return 1; + case 'closing': + return 2; + case 'closed': + default: + return 3; } - return 3; // CLOSED }, - godot_js_rtc_datachannel_send: function(p_id, p_buffer, p_length, p_raw) { + godot_js_rtc_datachannel_send: function (p_id, p_buffer, p_length, p_raw) { const ref = IDHandler.get(p_id); if (!ref) { return 1; } const bytes_array = new Uint8Array(p_length); - for (var i = 0; i < p_length; i++) { - bytes_array[i] = getValue(p_buffer + i, 'i8'); + for (let i = 0; i < p_length; i++) { + bytes_array[i] = GodotRuntime.getHeapValue(p_buffer + i, 'i8'); } if (p_raw) { @@ -127,17 +126,18 @@ var GodotRTCDataChannel = { const string = new TextDecoder('utf-8').decode(bytes_array); ref.send(string); } + return 0; }, - godot_js_rtc_datachannel_is_ordered: function(p_id) { + godot_js_rtc_datachannel_is_ordered: function (p_id) { return IDHandler.get_prop(p_id, 'ordered', true); }, - godot_js_rtc_datachannel_id_get: function(p_id) { + godot_js_rtc_datachannel_id_get: function (p_id) { return IDHandler.get_prop(p_id, 'id', 65535); }, - godot_js_rtc_datachannel_max_packet_lifetime_get: function(p_id) { + godot_js_rtc_datachannel_max_packet_lifetime_get: function (p_id) { const ref = IDHandler.get(p_id); if (!ref) { return 65535; @@ -151,44 +151,44 @@ var GodotRTCDataChannel = { return 65535; }, - godot_js_rtc_datachannel_max_retransmits_get: function(p_id) { + godot_js_rtc_datachannel_max_retransmits_get: function (p_id) { return IDHandler.get_prop(p_id, 'maxRetransmits', 65535); }, - godot_js_rtc_datachannel_is_negotiated: function(p_id, p_def) { + godot_js_rtc_datachannel_is_negotiated: function (p_id, p_def) { return IDHandler.get_prop(p_id, 'negotiated', 65535); }, - godot_js_rtc_datachannel_label_get: function(p_id) { + godot_js_rtc_datachannel_label_get: function (p_id) { const ref = IDHandler.get(p_id); if (!ref || !ref.label) { return 0; } - return GodotOS.allocString(ref.label); + return GodotRuntime.allocString(ref.label); }, - godot_js_rtc_datachannel_protocol_get: function(p_id) { + godot_js_rtc_datachannel_protocol_get: function (p_id) { const ref = IDHandler.get(p_id); if (!ref || !ref.protocol) { return 0; } - return GodotOS.allocString(ref.protocol); + return GodotRuntime.allocString(ref.protocol); }, - godot_js_rtc_datachannel_destroy: function(p_id) { + godot_js_rtc_datachannel_destroy: function (p_id) { GodotRTCDataChannel.close(p_id); IDHandler.remove(p_id); }, - godot_js_rtc_datachannel_connect: function(p_id, p_ref, p_on_open, p_on_message, p_on_error, p_on_close) { - const onopen = GodotOS.get_func(p_on_open).bind(null, p_ref); - const onmessage = GodotOS.get_func(p_on_message).bind(null, p_ref); - const onerror = GodotOS.get_func(p_on_error).bind(null, p_ref); - const onclose = GodotOS.get_func(p_on_close).bind(null, p_ref); + godot_js_rtc_datachannel_connect: function (p_id, p_ref, p_on_open, p_on_message, p_on_error, p_on_close) { + const onopen = GodotRuntime.get_func(p_on_open).bind(null, p_ref); + const onmessage = GodotRuntime.get_func(p_on_message).bind(null, p_ref); + const onerror = GodotRuntime.get_func(p_on_error).bind(null, p_ref); + const onclose = GodotRuntime.get_func(p_on_close).bind(null, p_ref); GodotRTCDataChannel.connect(p_id, onopen, onmessage, onerror, onclose); }, - godot_js_rtc_datachannel_close: function(p_id) { + godot_js_rtc_datachannel_close: function (p_id) { const ref = IDHandler.get(p_id); if (!ref) { return; @@ -200,49 +200,55 @@ var GodotRTCDataChannel = { autoAddDeps(GodotRTCDataChannel, '$GodotRTCDataChannel'); mergeInto(LibraryManager.library, GodotRTCDataChannel); -var GodotRTCPeerConnection = { - - $GodotRTCPeerConnection__deps: ['$IDHandler', '$GodotOS', '$GodotRTCDataChannel'], +const GodotRTCPeerConnection = { + $GodotRTCPeerConnection__deps: ['$IDHandler', '$GodotRuntime', '$GodotRTCDataChannel'], $GodotRTCPeerConnection: { - onstatechange: function(p_id, p_conn, callback, event) { + onstatechange: function (p_id, p_conn, callback, event) { const ref = IDHandler.get(p_id); if (!ref) { return; } - var state = 5; // CLOSED - switch(p_conn.iceConnectionState) { - case "new": - state = 0; - case "checking": - state = 1; - case "connected": - case "completed": - state = 2; - case "disconnected": - state = 3; - case "failed": - state = 4; - case "closed": - state = 5; + let state; + switch (p_conn.iceConnectionState) { + case 'new': + state = 0; + break; + case 'checking': + state = 1; + break; + case 'connected': + case 'completed': + state = 2; + break; + case 'disconnected': + state = 3; + break; + case 'failed': + state = 4; + break; + case 'closed': + default: + state = 5; + break; } callback(state); }, - onicecandidate: function(p_id, callback, event) { + onicecandidate: function (p_id, callback, event) { const ref = IDHandler.get(p_id); if (!ref || !event.candidate) { return; } - let c = event.candidate; - let candidate_str = GodotOS.allocString(c.candidate); - let mid_str = GodotOS.allocString(c.sdpMid); + const c = event.candidate; + const candidate_str = GodotRuntime.allocString(c.candidate); + const mid_str = GodotRuntime.allocString(c.sdpMid); callback(mid_str, c.sdpMLineIndex, candidate_str); - _free(candidate_str); - _free(mid_str); + GodotRuntime.free(candidate_str); + GodotRuntime.free(mid_str); }, - ondatachannel: function(p_id, callback, event) { + ondatachannel: function (p_id, callback, event) { const ref = IDHandler.get(p_id); if (!ref) { return; @@ -252,39 +258,39 @@ var GodotRTCPeerConnection = { callback(cid); }, - onsession: function(p_id, callback, session) { + onsession: function (p_id, callback, session) { const ref = IDHandler.get(p_id); if (!ref) { return; } - let type_str = GodotOS.allocString(session.type); - let sdp_str = GodotOS.allocString(session.sdp); + const type_str = GodotRuntime.allocString(session.type); + const sdp_str = GodotRuntime.allocString(session.sdp); callback(type_str, sdp_str); - _free(type_str); - _free(sdp_str); + GodotRuntime.free(type_str); + GodotRuntime.free(sdp_str); }, - onerror: function(p_id, callback, error) { + onerror: function (p_id, callback, error) { const ref = IDHandler.get(p_id); if (!ref) { return; } - console.error(error); + GodotRuntime.error(error); callback(); }, }, - godot_js_rtc_pc_create: function(p_config, p_ref, p_on_state_change, p_on_candidate, p_on_datachannel) { - const onstatechange = GodotOS.get_func(p_on_state_change).bind(null, p_ref); - const oncandidate = GodotOS.get_func(p_on_candidate).bind(null, p_ref); - const ondatachannel = GodotOS.get_func(p_on_datachannel).bind(null, p_ref); + godot_js_rtc_pc_create: function (p_config, p_ref, p_on_state_change, p_on_candidate, p_on_datachannel) { + const onstatechange = GodotRuntime.get_func(p_on_state_change).bind(null, p_ref); + const oncandidate = GodotRuntime.get_func(p_on_candidate).bind(null, p_ref); + const ondatachannel = GodotRuntime.get_func(p_on_datachannel).bind(null, p_ref); - var config = JSON.parse(UTF8ToString(p_config)); - var conn = null; + const config = JSON.parse(GodotRuntime.parseString(p_config)); + let conn = null; try { conn = new RTCPeerConnection(config); } catch (e) { - console.error(e); + GodotRuntime.error(e); return 0; } @@ -296,7 +302,7 @@ var GodotRTCPeerConnection = { return id; }, - godot_js_rtc_pc_close: function(p_id) { + godot_js_rtc_pc_close: function (p_id) { const ref = IDHandler.get(p_id); if (!ref) { return; @@ -304,7 +310,7 @@ var GodotRTCPeerConnection = { ref.close(); }, - godot_js_rtc_pc_destroy: function(p_id) { + godot_js_rtc_pc_destroy: function (p_id) { const ref = IDHandler.get(p_id); if (!ref) { return; @@ -315,93 +321,93 @@ var GodotRTCPeerConnection = { IDHandler.remove(p_id); }, - godot_js_rtc_pc_offer_create: function(p_id, p_obj, p_on_session, p_on_error) { + godot_js_rtc_pc_offer_create: function (p_id, p_obj, p_on_session, p_on_error) { const ref = IDHandler.get(p_id); if (!ref) { return; } - const onsession = GodotOS.get_func(p_on_session).bind(null, p_obj); - const onerror = GodotOS.get_func(p_on_error).bind(null, p_obj); - ref.createOffer().then(function(session) { + const onsession = GodotRuntime.get_func(p_on_session).bind(null, p_obj); + const onerror = GodotRuntime.get_func(p_on_error).bind(null, p_obj); + ref.createOffer().then(function (session) { GodotRTCPeerConnection.onsession(p_id, onsession, session); - }).catch(function(error) { + }).catch(function (error) { GodotRTCPeerConnection.onerror(p_id, onerror, error); }); }, - godot_js_rtc_pc_local_description_set: function(p_id, p_type, p_sdp, p_obj, p_on_error) { + godot_js_rtc_pc_local_description_set: function (p_id, p_type, p_sdp, p_obj, p_on_error) { const ref = IDHandler.get(p_id); if (!ref) { return; } - const type = UTF8ToString(p_type); - const sdp = UTF8ToString(p_sdp); - const onerror = GodotOS.get_func(p_on_error).bind(null, p_obj); + const type = GodotRuntime.parseString(p_type); + const sdp = GodotRuntime.parseString(p_sdp); + const onerror = GodotRuntime.get_func(p_on_error).bind(null, p_obj); ref.setLocalDescription({ 'sdp': sdp, - 'type': type - }).catch(function(error) { + 'type': type, + }).catch(function (error) { GodotRTCPeerConnection.onerror(p_id, onerror, error); }); }, - godot_js_rtc_pc_remote_description_set: function(p_id, p_type, p_sdp, p_obj, p_session_created, p_on_error) { + godot_js_rtc_pc_remote_description_set: function (p_id, p_type, p_sdp, p_obj, p_session_created, p_on_error) { const ref = IDHandler.get(p_id); if (!ref) { return; } - const type = UTF8ToString(p_type); - const sdp = UTF8ToString(p_sdp); - const onerror = GodotOS.get_func(p_on_error).bind(null, p_obj); - const onsession = GodotOS.get_func(p_session_created).bind(null, p_obj); + const type = GodotRuntime.parseString(p_type); + const sdp = GodotRuntime.parseString(p_sdp); + const onerror = GodotRuntime.get_func(p_on_error).bind(null, p_obj); + const onsession = GodotRuntime.get_func(p_session_created).bind(null, p_obj); ref.setRemoteDescription({ 'sdp': sdp, - 'type': type - }).then(function() { - if (type != 'offer') { - return; + 'type': type, + }).then(function () { + if (type !== 'offer') { + return Promise.resolve(); } - return ref.createAnswer().then(function(session) { + return ref.createAnswer().then(function (session) { GodotRTCPeerConnection.onsession(p_id, onsession, session); }); - }).catch(function(error) { + }).catch(function (error) { GodotRTCPeerConnection.onerror(p_id, onerror, error); }); }, - godot_js_rtc_pc_ice_candidate_add: function(p_id, p_mid_name, p_mline_idx, p_sdp) { + godot_js_rtc_pc_ice_candidate_add: function (p_id, p_mid_name, p_mline_idx, p_sdp) { const ref = IDHandler.get(p_id); if (!ref) { return; } - var sdpMidName = UTF8ToString(p_mid_name); - var sdpName = UTF8ToString(p_sdp); + const sdpMidName = GodotRuntime.parseString(p_mid_name); + const sdpName = GodotRuntime.parseString(p_sdp); ref.addIceCandidate(new RTCIceCandidate({ - "candidate": sdpName, - "sdpMid": sdpMidName, - "sdpMlineIndex": p_mline_idx, + 'candidate': sdpName, + 'sdpMid': sdpMidName, + 'sdpMlineIndex': p_mline_idx, })); }, godot_js_rtc_pc_datachannel_create__deps: ['$GodotRTCDataChannel'], - godot_js_rtc_pc_datachannel_create: function(p_id, p_label, p_config) { + godot_js_rtc_pc_datachannel_create: function (p_id, p_label, p_config) { try { const ref = IDHandler.get(p_id); if (!ref) { return 0; } - const label = UTF8ToString(p_label); - const config = JSON.parse(UTF8ToString(p_config)); + const label = GodotRuntime.parseString(p_label); + const config = JSON.parse(GodotRuntime.parseString(p_config)); const channel = ref.createDataChannel(label, config); return IDHandler.add(channel); } catch (e) { - console.error(e); + GodotRuntime.error(e); return 0; } }, }; -autoAddDeps(GodotRTCPeerConnection, '$GodotRTCPeerConnection') +autoAddDeps(GodotRTCPeerConnection, '$GodotRTCPeerConnection'); mergeInto(LibraryManager.library, GodotRTCPeerConnection); diff --git a/modules/websocket/library_godot_websocket.js b/modules/websocket/library_godot_websocket.js index f7d3195807..6ada4e7335 100644 --- a/modules/websocket/library_godot_websocket.js +++ b/modules/websocket/library_godot_websocket.js @@ -28,52 +28,51 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -var GodotWebSocket = { - +const GodotWebSocket = { // Our socket implementation that forwards events to C++. - $GodotWebSocket__deps: ['$IDHandler'], + $GodotWebSocket__deps: ['$IDHandler', '$GodotRuntime'], $GodotWebSocket: { // Connection opened, report selected protocol - _onopen: function(p_id, callback, event) { + _onopen: function (p_id, callback, event) { const ref = IDHandler.get(p_id); if (!ref) { return; // Godot object is gone. } - let c_str = GodotOS.allocString(ref.protocol); + const c_str = GodotRuntime.allocString(ref.protocol); callback(c_str); - _free(c_str); + GodotRuntime.free(c_str); }, // Message received, report content and type (UTF8 vs binary) - _onmessage: function(p_id, callback, event) { + _onmessage: function (p_id, callback, event) { const ref = IDHandler.get(p_id); if (!ref) { return; // Godot object is gone. } - var buffer; - var is_string = 0; + let buffer; + let is_string = 0; if (event.data instanceof ArrayBuffer) { buffer = new Uint8Array(event.data); } else if (event.data instanceof Blob) { - alert("Blob type not supported"); + GodotRuntime.error('Blob type not supported'); return; - } else if (typeof event.data === "string") { + } else if (typeof event.data === 'string') { is_string = 1; - var enc = new TextEncoder("utf-8"); + const enc = new TextEncoder('utf-8'); buffer = new Uint8Array(enc.encode(event.data)); } else { - alert("Unknown message type"); + GodotRuntime.error('Unknown message type'); return; } - var len = buffer.length*buffer.BYTES_PER_ELEMENT; - var out = _malloc(len); + const len = buffer.length * buffer.BYTES_PER_ELEMENT; + const out = GodotRuntime.malloc(len); HEAPU8.set(buffer, out); callback(out, len, is_string); - _free(out); + GodotRuntime.free(out); }, // An error happened, 'onclose' will be called after this. - _onerror: function(p_id, callback, event) { + _onerror: function (p_id, callback, event) { const ref = IDHandler.get(p_id); if (!ref) { return; // Godot object is gone. @@ -82,27 +81,27 @@ var GodotWebSocket = { }, // Connection is closed, this is always fired. Report close code, reason, and clean status. - _onclose: function(p_id, callback, event) { + _onclose: function (p_id, callback, event) { const ref = IDHandler.get(p_id); if (!ref) { return; // Godot object is gone. } - let c_str = GodotOS.allocString(event.reason); + const c_str = GodotRuntime.allocString(event.reason); callback(event.code, c_str, event.wasClean ? 1 : 0); - _free(c_str); + GodotRuntime.free(c_str); }, // Send a message - send: function(p_id, p_data) { + send: function (p_id, p_data) { const ref = IDHandler.get(p_id); - if (!ref || ref.readyState != ref.OPEN) { + if (!ref || ref.readyState !== ref.OPEN) { return 1; // Godot object is gone or socket is not in a ready state. } ref.send(p_data); return 0; }, - create: function(socket, p_on_open, p_on_message, p_on_error, p_on_close) { + create: function (socket, p_on_open, p_on_message, p_on_error, p_on_close) { const id = IDHandler.add(socket); socket.onopen = GodotWebSocket._onopen.bind(null, id, p_on_open); socket.onmessage = GodotWebSocket._onmessage.bind(null, id, p_on_message); @@ -112,17 +111,17 @@ var GodotWebSocket = { }, // Closes the JavaScript WebSocket (if not already closing) associated to a given C++ object. - close: function(p_id, p_code, p_reason) { + close: function (p_id, p_code, p_reason) { const ref = IDHandler.get(p_id); if (ref && ref.readyState < ref.CLOSING) { const code = p_code; - const reason = UTF8ToString(p_reason); + const reason = GodotRuntime.parseString(p_reason); ref.close(code, reason); } }, // Deletes the reference to a C++ object (closing any connected socket if necessary). - destroy: function(p_id) { + destroy: function (p_id) { const ref = IDHandler.get(p_id); if (!ref) { return; @@ -136,52 +135,50 @@ var GodotWebSocket = { }, }, - godot_js_websocket_create: function(p_ref, p_url, p_proto, p_on_open, p_on_message, p_on_error, p_on_close) { - const on_open = GodotOS.get_func(p_on_open).bind(null, p_ref); - const on_message = GodotOS.get_func(p_on_message).bind(null, p_ref); - const on_error = GodotOS.get_func(p_on_error).bind(null, p_ref); - const on_close = GodotOS.get_func(p_on_close).bind(null, p_ref); - const url = UTF8ToString(p_url); - const protos = UTF8ToString(p_proto); - var socket = null; + godot_js_websocket_create: function (p_ref, p_url, p_proto, p_on_open, p_on_message, p_on_error, p_on_close) { + const on_open = GodotRuntime.get_func(p_on_open).bind(null, p_ref); + const on_message = GodotRuntime.get_func(p_on_message).bind(null, p_ref); + const on_error = GodotRuntime.get_func(p_on_error).bind(null, p_ref); + const on_close = GodotRuntime.get_func(p_on_close).bind(null, p_ref); + const url = GodotRuntime.parseString(p_url); + const protos = GodotRuntime.parseString(p_proto); + let socket = null; try { if (protos) { - socket = new WebSocket(url, protos.split(",")); + socket = new WebSocket(url, protos.split(',')); } else { socket = new WebSocket(url); } } catch (e) { return 0; } - socket.binaryType = "arraybuffer"; + socket.binaryType = 'arraybuffer'; return GodotWebSocket.create(socket, on_open, on_message, on_error, on_close); }, - godot_js_websocket_send: function(p_id, p_buf, p_buf_len, p_raw) { - var bytes_array = new Uint8Array(p_buf_len); - var i = 0; - for(i = 0; i < p_buf_len; i++) { - bytes_array[i] = getValue(p_buf + i, 'i8'); + godot_js_websocket_send: function (p_id, p_buf, p_buf_len, p_raw) { + const bytes_array = new Uint8Array(p_buf_len); + let i = 0; + for (i = 0; i < p_buf_len; i++) { + bytes_array[i] = GodotRuntime.getHeapValue(p_buf + i, 'i8'); } - var out = bytes_array; - if (p_raw) { - out = bytes_array.buffer; - } else { - out = new TextDecoder("utf-8").decode(bytes_array); + let out = bytes_array.buffer; + if (!p_raw) { + out = new TextDecoder('utf-8').decode(bytes_array); } return GodotWebSocket.send(p_id, out); }, - godot_js_websocket_close: function(p_id, p_code, p_reason) { + godot_js_websocket_close: function (p_id, p_code, p_reason) { const code = p_code; - const reason = UTF8ToString(p_reason); + const reason = GodotRuntime.parseString(p_reason); GodotWebSocket.close(p_id, code, reason); }, - godot_js_websocket_destroy: function(p_id) { + godot_js_websocket_destroy: function (p_id) { GodotWebSocket.destroy(p_id); }, }; -autoAddDeps(GodotWebSocket, '$GodotWebSocket') +autoAddDeps(GodotWebSocket, '$GodotWebSocket'); mergeInto(LibraryManager.library, GodotWebSocket); diff --git a/modules/xatlas_unwrap/register_types.cpp b/modules/xatlas_unwrap/register_types.cpp index 65350518c3..19b827929d 100644 --- a/modules/xatlas_unwrap/register_types.cpp +++ b/modules/xatlas_unwrap/register_types.cpp @@ -141,11 +141,11 @@ bool xatlas_mesh_lightmap_unwrap_callback(float p_texel_size, const float *p_ver xatlas::Atlas *atlas = xatlas::Create(); printf("Adding mesh..\n"); - xatlas::AddMeshError::Enum err = xatlas::AddMesh(atlas, input_mesh, 1); - ERR_FAIL_COND_V_MSG(err != xatlas::AddMeshError::Enum::Success, false, xatlas::StringForEnum(err)); + xatlas::AddMeshError err = xatlas::AddMesh(atlas, input_mesh, 1); + ERR_FAIL_COND_V_MSG(err != xatlas::AddMeshError::Success, false, xatlas::StringForEnum(err)); printf("Generate..\n"); - xatlas::Generate(atlas, chart_options, xatlas::ParameterizeOptions(), pack_options); + xatlas::Generate(atlas, chart_options, xatlas::PackOptions()); *r_size_hint_x = atlas->width; *r_size_hint_y = atlas->height; |