diff options
Diffstat (limited to 'modules')
361 files changed, 14408 insertions, 7257 deletions
diff --git a/modules/basis_universal/SCsub b/modules/basis_universal/SCsub index a44a7f0db3..161b0f3814 100644 --- a/modules/basis_universal/SCsub +++ b/modules/basis_universal/SCsub @@ -40,12 +40,12 @@ if not env.msvc: else: env_basisu.Prepend(CPPPATH=[thirdparty_dir]) -if env["target"] == "debug": +if env.dev_build: env_basisu.Append(CPPDEFINES=[("BASISU_DEVEL_MESSAGES", 1), ("BASISD_ENABLE_DEBUG_FLAGS", 1)]) env_thirdparty = env_basisu.Clone() env_thirdparty.disable_warnings() -if env["tools"]: +if env.editor_build: env_thirdparty.Append(CPPDEFINES=["BASISU_NO_IMG_LOADERS"]) env_thirdparty.add_source_files(thirdparty_obj, encoder_sources) env_thirdparty.add_source_files(thirdparty_obj, transcoder_sources) diff --git a/modules/basis_universal/register_types.cpp b/modules/basis_universal/register_types.cpp index e80d453df7..155f7809b0 100644 --- a/modules/basis_universal/register_types.cpp +++ b/modules/basis_universal/register_types.cpp @@ -253,7 +253,7 @@ static Ref<Image> basis_universal_unpacker_ptr(const uint8_t *p_data, int p_size }; image.instantiate(); - image->create(info.m_width, info.m_height, info.m_total_levels > 1, imgfmt, gpudata); + image->set_data(info.m_width, info.m_height, info.m_total_levels > 1, imgfmt, gpudata); return image; } diff --git a/modules/bmp/image_loader_bmp.cpp b/modules/bmp/image_loader_bmp.cpp index ae03abca50..681b3e74bc 100644 --- a/modules/bmp/image_loader_bmp.cpp +++ b/modules/bmp/image_loader_bmp.cpp @@ -156,7 +156,7 @@ Error ImageLoaderBMP::convert_to_image(Ref<Image> p_image, if (p_color_buffer == nullptr || color_table_size == 0) { // regular pixels - p_image->create(width, height, false, Image::FORMAT_RGBA8, data); + p_image->set_data(width, height, false, Image::FORMAT_RGBA8, data); } else { // data is in indexed format, extend it @@ -194,13 +194,13 @@ Error ImageLoaderBMP::convert_to_image(Ref<Image> p_image, dest += 4; } - p_image->create(width, height, false, Image::FORMAT_RGBA8, extended_data); + p_image->set_data(width, height, false, Image::FORMAT_RGBA8, extended_data); } } return err; } -Error ImageLoaderBMP::load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale) { +Error ImageLoaderBMP::load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale) { bmp_header_s bmp_header; Error err = ERR_INVALID_DATA; diff --git a/modules/bmp/image_loader_bmp.h b/modules/bmp/image_loader_bmp.h index cf8346ecad..0ca54de1dc 100644 --- a/modules/bmp/image_loader_bmp.h +++ b/modules/bmp/image_loader_bmp.h @@ -83,7 +83,7 @@ protected: const bmp_header_s &p_header); public: - virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale); + virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale); virtual void get_recognized_extensions(List<String> *p_extensions) const; ImageLoaderBMP(); }; diff --git a/modules/bmp/register_types.cpp b/modules/bmp/register_types.cpp index 7c4a2085b2..67858e9d46 100644 --- a/modules/bmp/register_types.cpp +++ b/modules/bmp/register_types.cpp @@ -32,14 +32,14 @@ #include "image_loader_bmp.h" -static ImageLoaderBMP *image_loader_bmp = nullptr; +static Ref<ImageLoaderBMP> image_loader_bmp; void initialize_bmp_module(ModuleInitializationLevel p_level) { if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) { return; } - image_loader_bmp = memnew(ImageLoaderBMP); + image_loader_bmp.instantiate(); ImageLoader::add_image_format_loader(image_loader_bmp); } @@ -48,5 +48,6 @@ void uninitialize_bmp_module(ModuleInitializationLevel p_level) { return; } - memdelete(image_loader_bmp); + ImageLoader::remove_image_format_loader(image_loader_bmp); + image_loader_bmp.unref(); } diff --git a/modules/camera/camera_macos.mm b/modules/camera/camera_macos.mm index 0b9696a3e9..0e61dde8e9 100644 --- a/modules/camera/camera_macos.mm +++ b/modules/camera/camera_macos.mm @@ -158,7 +158,7 @@ memcpy(w, dataY, new_width * new_height); img[0].instantiate(); - img[0]->create(new_width, new_height, 0, Image::FORMAT_R8, img_data[0]); + img[0]->set_data(new_width, new_height, 0, Image::FORMAT_R8, img_data[0]); } { @@ -177,7 +177,7 @@ ///TODO OpenGL doesn't support FORMAT_RG8, need to do some form of conversion img[1].instantiate(); - img[1]->create(new_width, new_height, 0, Image::FORMAT_RG8, img_data[1]); + img[1]->set_data(new_width, new_height, 0, Image::FORMAT_RG8, img_data[1]); } // set our texture... diff --git a/modules/csg/SCsub b/modules/csg/SCsub index 55f859db11..1cf9974fc1 100644 --- a/modules/csg/SCsub +++ b/modules/csg/SCsub @@ -7,5 +7,5 @@ env_csg = env_modules.Clone() # Godot source files env_csg.add_source_files(env.modules_sources, "*.cpp") -if env["tools"]: +if env.editor_build: env_csg.add_source_files(env.modules_sources, "editor/*.cpp") diff --git a/modules/csg/csg.h b/modules/csg/csg.h index 738e3d68ea..aae99c52a3 100644 --- a/modules/csg/csg.h +++ b/modules/csg/csg.h @@ -39,7 +39,6 @@ #include "core/object/ref_counted.h" #include "core/templates/list.h" #include "core/templates/oa_hash_map.h" -#include "core/templates/rb_map.h" #include "core/templates/vector.h" #include "scene/resources/material.h" diff --git a/modules/csg/csg_shape.cpp b/modules/csg/csg_shape.cpp index 3932c2377f..461960ab26 100644 --- a/modules/csg/csg_shape.cpp +++ b/modules/csg/csg_shape.cpp @@ -92,13 +92,13 @@ uint32_t CSGShape3D::get_collision_mask() const { void CSGShape3D::set_collision_layer_value(int p_layer_number, bool p_value) { ERR_FAIL_COND_MSG(p_layer_number < 1, "Collision layer number must be between 1 and 32 inclusive."); ERR_FAIL_COND_MSG(p_layer_number > 32, "Collision layer number must be between 1 and 32 inclusive."); - uint32_t collision_layer = get_collision_layer(); + uint32_t layer = get_collision_layer(); if (p_value) { - collision_layer |= 1 << (p_layer_number - 1); + layer |= 1 << (p_layer_number - 1); } else { - collision_layer &= ~(1 << (p_layer_number - 1)); + layer &= ~(1 << (p_layer_number - 1)); } - set_collision_layer(collision_layer); + set_collision_layer(layer); } bool CSGShape3D::get_collision_layer_value(int p_layer_number) const { @@ -690,7 +690,7 @@ CSGCombiner3D::CSGCombiner3D() { ///////////////////// CSGBrush *CSGPrimitive3D::_create_brush_from_arrays(const Vector<Vector3> &p_vertices, const Vector<Vector2> &p_uv, const Vector<bool> &p_smooth, const Vector<Ref<Material>> &p_materials) { - CSGBrush *brush = memnew(CSGBrush); + CSGBrush *new_brush = memnew(CSGBrush); Vector<bool> invert; invert.resize(p_vertices.size() / 3); @@ -701,9 +701,9 @@ CSGBrush *CSGPrimitive3D::_create_brush_from_arrays(const Vector<Vector3> &p_ver w[i] = flip_faces; } } - brush->build_from_faces(p_vertices, p_uv, p_smooth, p_materials, invert); + new_brush->build_from_faces(p_vertices, p_uv, p_smooth, p_materials, invert); - return brush; + return new_brush; } void CSGPrimitive3D::_bind_methods() { @@ -742,7 +742,7 @@ CSGBrush *CSGMesh3D::_build_brush() { Vector<bool> smooth; Vector<Ref<Material>> materials; Vector<Vector2> uvs; - Ref<Material> material = get_material(); + Ref<Material> base_material = get_material(); for (int i = 0; i < mesh->get_surface_count(); i++) { if (mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) { @@ -776,8 +776,8 @@ CSGBrush *CSGMesh3D::_build_brush() { } Ref<Material> mat; - if (material.is_valid()) { - mat = material; + if (base_material.is_valid()) { + mat = base_material; } else { mat = mesh->surface_get_material(i); } @@ -933,12 +933,12 @@ Ref<Mesh> CSGMesh3D::get_mesh() { CSGBrush *CSGSphere3D::_build_brush() { // set our bounding box - CSGBrush *brush = memnew(CSGBrush); + CSGBrush *new_brush = memnew(CSGBrush); int face_count = rings * radial_segments * 2 - radial_segments * 2; bool invert_val = get_flip_faces(); - Ref<Material> material = get_material(); + Ref<Material> base_material = get_material(); Vector<Vector3> faces; Vector<Vector2> uvs; @@ -1019,7 +1019,7 @@ CSGBrush *CSGSphere3D::_build_brush() { smoothw[face] = smooth_faces; invertw[face] = invert_val; - materialsw[face] = material; + materialsw[face] = base_material; face++; } @@ -1036,7 +1036,7 @@ CSGBrush *CSGSphere3D::_build_brush() { smoothw[face] = smooth_faces; invertw[face] = invert_val; - materialsw[face] = material; + materialsw[face] = base_material; face++; } @@ -1048,9 +1048,9 @@ CSGBrush *CSGSphere3D::_build_brush() { } } - brush->build_from_faces(faces, uvs, smooth, materials, invert); + new_brush->build_from_faces(faces, uvs, smooth, materials, invert); - return brush; + return new_brush; } void CSGSphere3D::_bind_methods() { @@ -1137,12 +1137,12 @@ CSGSphere3D::CSGSphere3D() { CSGBrush *CSGBox3D::_build_brush() { // set our bounding box - CSGBrush *brush = memnew(CSGBrush); + CSGBrush *new_brush = memnew(CSGBrush); int face_count = 12; //it's a cube.. bool invert_val = get_flip_faces(); - Ref<Material> material = get_material(); + Ref<Material> base_material = get_material(); Vector<Vector3> faces; Vector<Vector2> uvs; @@ -1204,7 +1204,7 @@ CSGBrush *CSGBox3D::_build_brush() { smoothw[face] = false; invertw[face] = invert_val; - materialsw[face] = material; + materialsw[face] = base_material; face++; //face 2 @@ -1218,7 +1218,7 @@ CSGBrush *CSGBox3D::_build_brush() { smoothw[face] = false; invertw[face] = invert_val; - materialsw[face] = material; + materialsw[face] = base_material; face++; } @@ -1229,9 +1229,9 @@ CSGBrush *CSGBox3D::_build_brush() { } } - brush->build_from_faces(faces, uvs, smooth, materials, invert); + new_brush->build_from_faces(faces, uvs, smooth, materials, invert); - return brush; + return new_brush; } void CSGBox3D::_bind_methods() { @@ -1270,12 +1270,12 @@ Ref<Material> CSGBox3D::get_material() const { CSGBrush *CSGCylinder3D::_build_brush() { // set our bounding box - CSGBrush *brush = memnew(CSGBrush); + CSGBrush *new_brush = memnew(CSGBrush); int face_count = sides * (cone ? 1 : 2) + sides + (cone ? 0 : sides); bool invert_val = get_flip_faces(); - Ref<Material> material = get_material(); + Ref<Material> base_material = get_material(); Vector<Vector3> faces; Vector<Vector2> uvs; @@ -1312,14 +1312,14 @@ CSGBrush *CSGCylinder3D::_build_brush() { float ang = inc * Math_TAU; float ang_n = inc_n * Math_TAU; - Vector3 base(Math::cos(ang), 0, Math::sin(ang)); - Vector3 base_n(Math::cos(ang_n), 0, Math::sin(ang_n)); + Vector3 face_base(Math::cos(ang), 0, Math::sin(ang)); + Vector3 face_base_n(Math::cos(ang_n), 0, Math::sin(ang_n)); Vector3 face_points[4] = { - base + Vector3(0, -1, 0), - base_n + Vector3(0, -1, 0), - base_n * (cone ? 0.0 : 1.0) + Vector3(0, 1, 0), - base * (cone ? 0.0 : 1.0) + Vector3(0, 1, 0), + face_base + Vector3(0, -1, 0), + face_base_n + Vector3(0, -1, 0), + face_base_n * (cone ? 0.0 : 1.0) + Vector3(0, 1, 0), + face_base * (cone ? 0.0 : 1.0) + Vector3(0, 1, 0), }; Vector2 u[4] = { @@ -1340,7 +1340,7 @@ CSGBrush *CSGCylinder3D::_build_brush() { smoothw[face] = smooth_faces; invertw[face] = invert_val; - materialsw[face] = material; + materialsw[face] = base_material; face++; @@ -1356,7 +1356,7 @@ CSGBrush *CSGCylinder3D::_build_brush() { smoothw[face] = smooth_faces; invertw[face] = invert_val; - materialsw[face] = material; + materialsw[face] = base_material; face++; } @@ -1371,7 +1371,7 @@ CSGBrush *CSGCylinder3D::_build_brush() { smoothw[face] = false; invertw[face] = invert_val; - materialsw[face] = material; + materialsw[face] = base_material; face++; if (!cone) { @@ -1386,7 +1386,7 @@ CSGBrush *CSGCylinder3D::_build_brush() { smoothw[face] = false; invertw[face] = invert_val; - materialsw[face] = material; + materialsw[face] = base_material; face++; } } @@ -1397,9 +1397,9 @@ CSGBrush *CSGCylinder3D::_build_brush() { } } - brush->build_from_faces(faces, uvs, smooth, materials, invert); + new_brush->build_from_faces(faces, uvs, smooth, materials, invert); - return brush; + return new_brush; } void CSGCylinder3D::_bind_methods() { @@ -1515,12 +1515,12 @@ CSGBrush *CSGTorus3D::_build_brush() { float radius = (max_radius - min_radius) * 0.5; - CSGBrush *brush = memnew(CSGBrush); + CSGBrush *new_brush = memnew(CSGBrush); int face_count = ring_sides * sides * 2; bool invert_val = get_flip_faces(); - Ref<Material> material = get_material(); + Ref<Material> base_material = get_material(); Vector<Vector3> faces; Vector<Vector2> uvs; @@ -1596,7 +1596,7 @@ CSGBrush *CSGTorus3D::_build_brush() { smoothw[face] = smooth_faces; invertw[face] = invert_val; - materialsw[face] = material; + materialsw[face] = base_material; face++; @@ -1611,7 +1611,7 @@ CSGBrush *CSGTorus3D::_build_brush() { smoothw[face] = smooth_faces; invertw[face] = invert_val; - materialsw[face] = material; + materialsw[face] = base_material; face++; } } @@ -1622,9 +1622,9 @@ CSGBrush *CSGTorus3D::_build_brush() { } } - brush->build_from_faces(faces, uvs, smooth, materials, invert); + new_brush->build_from_faces(faces, uvs, smooth, materials, invert); - return brush; + return new_brush; } void CSGTorus3D::_bind_methods() { @@ -1726,10 +1726,10 @@ CSGTorus3D::CSGTorus3D() { /////////////// CSGBrush *CSGPolygon3D::_build_brush() { - CSGBrush *brush = memnew(CSGBrush); + CSGBrush *new_brush = memnew(CSGBrush); if (polygon.size() < 3) { - return brush; + return new_brush; } // Triangulate polygon shape. @@ -1739,7 +1739,7 @@ CSGBrush *CSGPolygon3D::_build_brush() { } int shape_sides = shape_polygon.size(); Vector<int> shape_faces = Geometry2D::triangulate_polygon(shape_polygon); - ERR_FAIL_COND_V_MSG(shape_faces.size() < 3, brush, "Failed to triangulate CSGPolygon. Make sure the polygon doesn't have any intersecting edges."); + ERR_FAIL_COND_V_MSG(shape_faces.size() < 3, new_brush, "Failed to triangulate CSGPolygon. Make sure the polygon doesn't have any intersecting edges."); // Get polygon enclosing Rect2. Rect2 shape_rect(shape_polygon[0], Vector2()); @@ -1764,12 +1764,12 @@ CSGBrush *CSGPolygon3D::_build_brush() { } if (!path) { - return brush; + return new_brush; } curve = path->get_curve(); if (curve.is_null() || curve->get_point_count() < 2) { - return brush; + return new_brush; } } @@ -1806,7 +1806,7 @@ CSGBrush *CSGPolygon3D::_build_brush() { int face_count = extrusions * extrusion_face_count + end_count * shape_face_count; // Initialize variables used to create the mesh. - Ref<Material> material = get_material(); + Ref<Material> base_material = get_material(); Vector<Vector3> faces; Vector<Vector2> uvs; @@ -1896,7 +1896,7 @@ CSGBrush *CSGPolygon3D::_build_brush() { } smoothw[face] = false; - materialsw[face] = material; + materialsw[face] = base_material; invertw[face] = flip_faces; face++; } @@ -2003,7 +2003,7 @@ CSGBrush *CSGPolygon3D::_build_brush() { smoothw[face] = smooth_faces; invertw[face] = flip_faces; - materialsw[face] = material; + materialsw[face] = base_material; face++; @@ -2018,7 +2018,7 @@ CSGBrush *CSGPolygon3D::_build_brush() { smoothw[face] = smooth_faces; invertw[face] = flip_faces; - materialsw[face] = material; + materialsw[face] = base_material; face++; } @@ -2041,14 +2041,14 @@ CSGBrush *CSGPolygon3D::_build_brush() { } smoothw[face] = false; - materialsw[face] = material; + materialsw[face] = base_material; invertw[face] = flip_faces; face++; } } face_count -= faces_removed; - ERR_FAIL_COND_V_MSG(face != face_count, brush, "Bug: Failed to create the CSGPolygon mesh correctly."); + ERR_FAIL_COND_V_MSG(face != face_count, new_brush, "Bug: Failed to create the CSGPolygon mesh correctly."); } if (faces_removed > 0) { @@ -2059,9 +2059,9 @@ CSGBrush *CSGPolygon3D::_build_brush() { invert.resize(face_count); } - brush->build_from_faces(faces, uvs, smooth, materials, invert); + new_brush->build_from_faces(faces, uvs, smooth, materials, invert); - return brush; + return new_brush; } void CSGPolygon3D::_notification(int p_what) { diff --git a/modules/csg/doc_classes/CSGShape3D.xml b/modules/csg/doc_classes/CSGShape3D.xml index 7e92d667b3..06f8f5a403 100644 --- a/modules/csg/doc_classes/CSGShape3D.xml +++ b/modules/csg/doc_classes/CSGShape3D.xml @@ -64,9 +64,10 @@ A contact is detected if object A is in any of the layers that object B scans, or object B is in any layer scanned by object A. See [url=$DOCS_URL/tutorials/physics/physics_introduction.html#collision-layers-and-masks]Collision layers and masks[/url] in the documentation for more information. </member> <member name="collision_mask" type="int" setter="set_collision_mask" getter="get_collision_mask" default="1"> - The physics layers this CSG shape scans for collisions. See [url=$DOCS_URL/tutorials/physics/physics_introduction.html#collision-layers-and-masks]Collision layers and masks[/url] in the documentation for more information. + The physics layers this CSG shape scans for collisions. Only effective if [member use_collision] is [code]true[/code]. See [url=$DOCS_URL/tutorials/physics/physics_introduction.html#collision-layers-and-masks]Collision layers and masks[/url] in the documentation for more information. </member> <member name="collision_priority" type="float" setter="set_collision_priority" getter="get_collision_priority" default="1.0"> + The priority used to solve colliding when occurring penetration. Only effective if [member use_collision] is [code]true[/code]. The higher the priority is, the lower the penetration into the object will be. This can for example be used to prevent the player from breaking through the boundaries of a level. </member> <member name="operation" type="int" setter="set_operation" getter="get_operation" enum="CSGShape3D.Operation" default="0"> The operation that is performed on this shape. This is ignored for the first CSG child node as the operation is between this node and the previous child of this nodes parent. @@ -75,7 +76,7 @@ Snap makes the mesh snap to a given distance so that the faces of two meshes can be perfectly aligned. A lower value results in greater precision but may be harder to adjust. </member> <member name="use_collision" type="bool" setter="set_use_collision" getter="is_using_collision" default="false"> - Adds a collision shape to the physics engine for our CSG shape. This will always act like a static body. Note that the collision shape is still active even if the CSG shape itself is hidden. + Adds a collision shape to the physics engine for our CSG shape. This will always act like a static body. Note that the collision shape is still active even if the CSG shape itself is hidden. See also [member collision_mask] and [member collision_priority]. </member> </members> <constants> diff --git a/modules/csg/editor/csg_gizmos.cpp b/modules/csg/editor/csg_gizmos.cpp index ba9b96db74..73771b3639 100644 --- a/modules/csg/editor/csg_gizmos.cpp +++ b/modules/csg/editor/csg_gizmos.cpp @@ -57,7 +57,7 @@ CSGShape3DGizmoPlugin::CSGShape3DGizmoPlugin() { } String CSGShape3DGizmoPlugin::get_handle_name(const EditorNode3DGizmo *p_gizmo, int p_id, bool p_secondary) const { - CSGShape3D *cs = Object::cast_to<CSGShape3D>(p_gizmo->get_spatial_node()); + CSGShape3D *cs = Object::cast_to<CSGShape3D>(p_gizmo->get_node_3d()); if (Object::cast_to<CSGSphere3D>(cs)) { return "Radius"; @@ -79,7 +79,7 @@ String CSGShape3DGizmoPlugin::get_handle_name(const EditorNode3DGizmo *p_gizmo, } Variant CSGShape3DGizmoPlugin::get_handle_value(const EditorNode3DGizmo *p_gizmo, int p_id, bool p_secondary) const { - CSGShape3D *cs = Object::cast_to<CSGShape3D>(p_gizmo->get_spatial_node()); + CSGShape3D *cs = Object::cast_to<CSGShape3D>(p_gizmo->get_node_3d()); if (Object::cast_to<CSGSphere3D>(cs)) { CSGSphere3D *s = Object::cast_to<CSGSphere3D>(cs); @@ -105,7 +105,7 @@ Variant CSGShape3DGizmoPlugin::get_handle_value(const EditorNode3DGizmo *p_gizmo } void CSGShape3DGizmoPlugin::set_handle(const EditorNode3DGizmo *p_gizmo, int p_id, bool p_secondary, Camera3D *p_camera, const Point2 &p_point) { - CSGShape3D *cs = Object::cast_to<CSGShape3D>(p_gizmo->get_spatial_node()); + CSGShape3D *cs = Object::cast_to<CSGShape3D>(p_gizmo->get_node_3d()); Transform3D gt = cs->get_global_transform(); //gt.orthonormalize(); @@ -208,7 +208,7 @@ void CSGShape3DGizmoPlugin::set_handle(const EditorNode3DGizmo *p_gizmo, int p_i } void CSGShape3DGizmoPlugin::commit_handle(const EditorNode3DGizmo *p_gizmo, int p_id, bool p_secondary, const Variant &p_restore, bool p_cancel) { - CSGShape3D *cs = Object::cast_to<CSGShape3D>(p_gizmo->get_spatial_node()); + CSGShape3D *cs = Object::cast_to<CSGShape3D>(p_gizmo->get_node_3d()); if (Object::cast_to<CSGSphere3D>(cs)) { CSGSphere3D *s = Object::cast_to<CSGSphere3D>(cs); @@ -308,7 +308,7 @@ bool CSGShape3DGizmoPlugin::is_selectable_when_hidden() const { void CSGShape3DGizmoPlugin::redraw(EditorNode3DGizmo *p_gizmo) { p_gizmo->clear(); - CSGShape3D *cs = Object::cast_to<CSGShape3D>(p_gizmo->get_spatial_node()); + CSGShape3D *cs = Object::cast_to<CSGShape3D>(p_gizmo->get_node_3d()); Vector<Vector3> faces = cs->get_brush_faces(); diff --git a/modules/cvtt/config.py b/modules/cvtt/config.py index 53b8f2f2e3..eb565b85b9 100644 --- a/modules/cvtt/config.py +++ b/modules/cvtt/config.py @@ -1,5 +1,5 @@ def can_build(env, platform): - return env["tools"] + return env.editor_build def configure(env): diff --git a/modules/cvtt/image_compress_cvtt.cpp b/modules/cvtt/image_compress_cvtt.cpp index 3322ff0a1b..89705e4ee0 100644 --- a/modules/cvtt/image_compress_cvtt.cpp +++ b/modules/cvtt/image_compress_cvtt.cpp @@ -230,7 +230,7 @@ void image_compress_cvtt(Image *p_image, float p_lossy_quality, Image::UsedChann h = MAX(h / 2, 1); } - p_image->create(p_image->get_width(), p_image->get_height(), p_image->has_mipmaps(), target_format, data); + p_image->set_data(p_image->get_width(), p_image->get_height(), p_image->has_mipmaps(), target_format, data); } void image_decompress_cvtt(Image *p_image) { @@ -339,5 +339,5 @@ void image_decompress_cvtt(Image *p_image) { w >>= 1; h >>= 1; } - p_image->create(p_image->get_width(), p_image->get_height(), p_image->has_mipmaps(), target_format, data); + p_image->set_data(p_image->get_width(), p_image->get_height(), p_image->has_mipmaps(), target_format, data); } diff --git a/modules/denoise/SCsub b/modules/denoise/SCsub index 97feea2b44..779ce165d2 100644 --- a/modules/denoise/SCsub +++ b/modules/denoise/SCsub @@ -103,9 +103,9 @@ env_oidn.Append( "__STDC_LIMIT_MACROS", "DISABLE_VERBOSE", "MKLDNN_ENABLE_CONCURRENT_EXEC", - "NDEBUG", ] ) +env_oidn.AppendUnique(CPPDEFINES=["NDEBUG"]) # No assert() even in debug builds. env_thirdparty = env_oidn.Clone() env_thirdparty.disable_warnings() diff --git a/modules/denoise/config.py b/modules/denoise/config.py index 20a5e1da2f..27d2ffbf86 100644 --- a/modules/denoise/config.py +++ b/modules/denoise/config.py @@ -5,7 +5,7 @@ def can_build(env, platform): # as doing lightmap generation and denoising on Android or Web # would be a bit far-fetched. desktop_platforms = ["linuxbsd", "macos", "windows"] - return env["tools"] and platform in desktop_platforms and env["arch"] == "x86_64" + return env.editor_build and platform in desktop_platforms and env["arch"] == "x86_64" def configure(env): diff --git a/modules/denoise/lightmap_denoiser.cpp b/modules/denoise/lightmap_denoiser.cpp index a0dbd07b10..2b9221bc43 100644 --- a/modules/denoise/lightmap_denoiser.cpp +++ b/modules/denoise/lightmap_denoiser.cpp @@ -51,7 +51,7 @@ Ref<Image> LightmapDenoiserOIDN::denoise_image(const Ref<Image> &p_image) { return p_image; } - img->create(img->get_width(), img->get_height(), false, img->get_format(), data); + img->set_data(img->get_width(), img->get_height(), false, img->get_format(), data); return img; } diff --git a/modules/enet/doc_classes/ENetMultiplayerPeer.xml b/modules/enet/doc_classes/ENetMultiplayerPeer.xml index 5181ae76ce..2e0d1f5079 100644 --- a/modules/enet/doc_classes/ENetMultiplayerPeer.xml +++ b/modules/enet/doc_classes/ENetMultiplayerPeer.xml @@ -21,13 +21,6 @@ [b]Note:[/b] The [code]host[/code] must have exactly one peer in the [constant ENetPacketPeer.STATE_CONNECTED] state. </description> </method> - <method name="close_connection"> - <return type="void" /> - <param index="0" name="wait_usec" type="int" default="100" /> - <description> - Closes the connection. Ignored if no connection is currently established. If this is a server it tries to notify all clients before forcibly disconnecting them. If this is a client it simply closes the connection to the server. - </description> - </method> <method name="create_client"> <return type="int" enum="Error" /> <param index="0" name="address" type="String" /> @@ -37,7 +30,7 @@ <param index="4" name="out_bandwidth" type="int" default="0" /> <param index="5" name="local_port" type="int" default="0" /> <description> - Create client that connects to a server at [code]address[/code] using specified [code]port[/code]. The given address needs to be either a fully qualified domain name (e.g. [code]"www.example.com"[/code]) or an IP address in IPv4 or IPv6 format (e.g. [code]"192.168.1.1"[/code]). The [code]port[/code] is the port the server is listening on. The [code]channel_count[/code] parameter can be used to specify the number of ENet channels allocated for the connection. The [code]in_bandwidth[/code] and [code]out_bandwidth[/code] parameters can be used to limit the incoming and outgoing bandwidth to the given number of bytes per second. The default of 0 means unlimited bandwidth. Note that ENet will strategically drop packets on specific sides of a connection between peers to ensure the peer's bandwidth is not overwhelmed. The bandwidth parameters also determine the window size of a connection which limits the amount of reliable packets that may be in transit at any given time. Returns [constant OK] if a client was created, [constant ERR_ALREADY_IN_USE] if this ENetMultiplayerPeer instance already has an open connection (in which case you need to call [method close_connection] first) or [constant ERR_CANT_CREATE] if the client could not be created. If [code]local_port[/code] is specified, the client will also listen to the given port; this is useful for some NAT traversal techniques. + Create client that connects to a server at [code]address[/code] using specified [code]port[/code]. The given address needs to be either a fully qualified domain name (e.g. [code]"www.example.com"[/code]) or an IP address in IPv4 or IPv6 format (e.g. [code]"192.168.1.1"[/code]). The [code]port[/code] is the port the server is listening on. The [code]channel_count[/code] parameter can be used to specify the number of ENet channels allocated for the connection. The [code]in_bandwidth[/code] and [code]out_bandwidth[/code] parameters can be used to limit the incoming and outgoing bandwidth to the given number of bytes per second. The default of 0 means unlimited bandwidth. Note that ENet will strategically drop packets on specific sides of a connection between peers to ensure the peer's bandwidth is not overwhelmed. The bandwidth parameters also determine the window size of a connection which limits the amount of reliable packets that may be in transit at any given time. Returns [constant OK] if a client was created, [constant ERR_ALREADY_IN_USE] if this ENetMultiplayerPeer instance already has an open connection (in which case you need to call [method MultiplayerPeer.close] first) or [constant ERR_CANT_CREATE] if the client could not be created. If [code]local_port[/code] is specified, the client will also listen to the given port; this is useful for some NAT traversal techniques. </description> </method> <method name="create_mesh"> @@ -55,7 +48,7 @@ <param index="3" name="in_bandwidth" type="int" default="0" /> <param index="4" name="out_bandwidth" type="int" default="0" /> <description> - Create server that listens to connections via [code]port[/code]. The port needs to be an available, unused port between 0 and 65535. Note that ports below 1024 are privileged and may require elevated permissions depending on the platform. To change the interface the server listens on, use [method set_bind_ip]. The default IP is the wildcard [code]"*"[/code], which listens on all available interfaces. [code]max_clients[/code] is the maximum number of clients that are allowed at once, any number up to 4095 may be used, although the achievable number of simultaneous clients may be far lower and depends on the application. For additional details on the bandwidth parameters, see [method create_client]. Returns [constant OK] if a server was created, [constant ERR_ALREADY_IN_USE] if this ENetMultiplayerPeer instance already has an open connection (in which case you need to call [method close_connection] first) or [constant ERR_CANT_CREATE] if the server could not be created. + Create server that listens to connections via [code]port[/code]. The port needs to be an available, unused port between 0 and 65535. Note that ports below 1024 are privileged and may require elevated permissions depending on the platform. To change the interface the server listens on, use [method set_bind_ip]. The default IP is the wildcard [code]"*"[/code], which listens on all available interfaces. [code]max_clients[/code] is the maximum number of clients that are allowed at once, any number up to 4095 may be used, although the achievable number of simultaneous clients may be far lower and depends on the application. For additional details on the bandwidth parameters, see [method create_client]. Returns [constant OK] if a server was created, [constant ERR_ALREADY_IN_USE] if this ENetMultiplayerPeer instance already has an open connection (in which case you need to call [method MultiplayerPeer.close] first) or [constant ERR_CANT_CREATE] if the server could not be created. </description> </method> <method name="get_peer" qualifiers="const"> @@ -77,8 +70,5 @@ <member name="host" type="ENetConnection" setter="" getter="get_host"> The underlying [ENetConnection] created after [method create_client] and [method create_server]. </member> - <member name="server_relay" type="bool" setter="set_server_relay_enabled" getter="is_server_relay_enabled" default="true"> - Enable or disable the server feature that notifies clients of other peers' connection/disconnection, and relays messages between them. When this option is [code]false[/code], clients won't be automatically notified of other peers and won't be able to send them packets through the server. - </member> </members> </class> diff --git a/modules/enet/doc_classes/ENetPacketPeer.xml b/modules/enet/doc_classes/ENetPacketPeer.xml index 67760ba5e8..52f45b2338 100644 --- a/modules/enet/doc_classes/ENetPacketPeer.xml +++ b/modules/enet/doc_classes/ENetPacketPeer.xml @@ -80,7 +80,7 @@ <return type="void" /> <param index="0" name="ping_interval" type="int" /> <description> - Sets the [code]ping_interval[/code] in milliseconds at which pings will be sent to a peer. Pings are used both to monitor the liveness of the connection and also to dynamically adjust the throttle during periods of low traffic so that the throttle has reasonable responsiveness during traffic spikes. + Sets the [code]ping_interval[/code] in milliseconds at which pings will be sent to a peer. Pings are used both to monitor the liveness of the connection and also to dynamically adjust the throttle during periods of low traffic so that the throttle has reasonable responsiveness during traffic spikes. The default ping interval is [code]500[/code] milliseconds. </description> </method> <method name="reset"> @@ -115,33 +115,43 @@ <param index="2" name="deceleration" type="int" /> <description> Configures throttle parameter for a peer. - Unreliable packets are dropped by ENet in response to the varying conditions of the Internet connection to the peer. The throttle represents a probability that an unreliable packet should not be dropped and thus sent by ENet to the peer. By measuring fluctuations in round trip times of reliable packets over the specified [code]interval[/code], ENet will either increase the probably by the amount specified in the [code]acceleration[/code] parameter, or decrease it by the amount specified in the [code]deceleration[/code] parameter (both are ratios to [constant PACKET_THROTTLE_SCALE]). + Unreliable packets are dropped by ENet in response to the varying conditions of the Internet connection to the peer. The throttle represents a probability that an unreliable packet should not be dropped and thus sent by ENet to the peer. By measuring fluctuations in round trip times of reliable packets over the specified [code]interval[/code], ENet will either increase the probability by the amount specified in the [code]acceleration[/code] parameter, or decrease it by the amount specified in the [code]deceleration[/code] parameter (both are ratios to [constant PACKET_THROTTLE_SCALE]). When the throttle has a value of [constant PACKET_THROTTLE_SCALE], no unreliable packets are dropped by ENet, and so 100% of all unreliable packets will be sent. - When the throttle has a value of 0, all unreliable packets are dropped by ENet, and so 0% of all unreliable packets will be sent. + When the throttle has a value of [code]0[/code], all unreliable packets are dropped by ENet, and so 0% of all unreliable packets will be sent. Intermediate values for the throttle represent intermediate probabilities between 0% and 100% of unreliable packets being sent. The bandwidth limits of the local and foreign hosts are taken into account to determine a sensible limit for the throttle probability above which it should not raise even in the best of conditions. </description> </method> </methods> <constants> <constant name="STATE_DISCONNECTED" value="0" enum="PeerState"> + The peer is disconnected. </constant> <constant name="STATE_CONNECTING" value="1" enum="PeerState"> + The peer is currently attempting to connect. </constant> <constant name="STATE_ACKNOWLEDGING_CONNECT" value="2" enum="PeerState"> + The peer has acknowledged the connection request. </constant> <constant name="STATE_CONNECTION_PENDING" value="3" enum="PeerState"> + The peer is currently connecting. </constant> <constant name="STATE_CONNECTION_SUCCEEDED" value="4" enum="PeerState"> + The peer has successfully connected, but is not ready to communicate with yet ([constant STATE_CONNECTED]). </constant> <constant name="STATE_CONNECTED" value="5" enum="PeerState"> + The peer is currently connected and ready to communicate with. </constant> <constant name="STATE_DISCONNECT_LATER" value="6" enum="PeerState"> + The peer is slated to disconnect after it has no more outgoing packets to send. </constant> <constant name="STATE_DISCONNECTING" value="7" enum="PeerState"> + The peer is currently disconnecting. </constant> <constant name="STATE_ACKNOWLEDGING_DISCONNECT" value="8" enum="PeerState"> + The peer has acknowledged the disconnection request. </constant> <constant name="STATE_ZOMBIE" value="9" enum="PeerState"> + The peer has lost connection, but is not considered truly disconnected (as the peer didn't acknowledge the disconnection request). </constant> <constant name="PEER_PACKET_LOSS" value="0" enum="PeerStatistic"> Mean packet loss of reliable packets as a ratio with respect to the [constant PACKET_LOSS_SCALE]. @@ -150,6 +160,7 @@ Packet loss variance. </constant> <constant name="PEER_PACKET_LOSS_EPOCH" value="2" enum="PeerStatistic"> + The time at which packet loss statistics were last updated (in milliseconds since the connection started). The interval for packet loss statistics updates is 10 seconds, and at least one packet must have been sent since the last statistics update. </constant> <constant name="PEER_ROUND_TRIP_TIME" value="3" enum="PeerStatistic"> Mean packet round trip time for reliable packets. @@ -164,24 +175,31 @@ Variance of the last trip time recorded. </constant> <constant name="PEER_PACKET_THROTTLE" value="7" enum="PeerStatistic"> + The peer's current throttle status. </constant> <constant name="PEER_PACKET_THROTTLE_LIMIT" value="8" enum="PeerStatistic"> + The maximum number of unreliable packets that should not be dropped. This value is always greater than or equal to [code]1[/code]. The initial value is equal to [constant PACKET_THROTTLE_SCALE]. </constant> <constant name="PEER_PACKET_THROTTLE_COUNTER" value="9" enum="PeerStatistic"> + Internal value used to increment the packet throttle counter. The value is hardcoded to [code]7[/code] and cannot be changed. You probably want to look at [constant PEER_PACKET_THROTTLE_ACCELERATION] instead. </constant> <constant name="PEER_PACKET_THROTTLE_EPOCH" value="10" enum="PeerStatistic"> + The time at which throttle statistics were last updated (in milliseconds since the connection started). The interval for throttle statistics updates is [constant PEER_PACKET_THROTTLE_INTERVAL]. </constant> <constant name="PEER_PACKET_THROTTLE_ACCELERATION" value="11" enum="PeerStatistic"> + The throttle's acceleration factor. Higher values will make ENet adapt to fluctuating network conditions faster, causing unrelaible packets to be sent [i]more[/i] often. The default value is [code]2[/code]. </constant> <constant name="PEER_PACKET_THROTTLE_DECELERATION" value="12" enum="PeerStatistic"> + The throttle's deceleration factor. Higher values will make ENet adapt to fluctuating network conditions faster, causing unrelaible packets to be sent [i]less[/i] often. The default value is [code]2[/code]. </constant> <constant name="PEER_PACKET_THROTTLE_INTERVAL" value="13" enum="PeerStatistic"> + The interval over which the lowest mean round trip time should be measured for use by the throttle mechanism (in milliseconds). The default value is [code]5000[/code]. </constant> <constant name="PACKET_LOSS_SCALE" value="65536"> The reference scale for packet loss. See [method get_statistic] and [constant PEER_PACKET_LOSS]. </constant> <constant name="PACKET_THROTTLE_SCALE" value="32"> - The reference value for throttle configuration. See [method throttle_configure]. + The reference value for throttle configuration. The default value is [code]32[/code]. See [method throttle_configure]. </constant> <constant name="FLAG_RELIABLE" value="1"> Mark the packet to be sent as reliable. diff --git a/modules/enet/enet_multiplayer_peer.cpp b/modules/enet/enet_multiplayer_peer.cpp index dfdd08c9f4..43c512ae16 100644 --- a/modules/enet/enet_multiplayer_peer.cpp +++ b/modules/enet/enet_multiplayer_peer.cpp @@ -44,6 +44,22 @@ int ENetMultiplayerPeer::get_packet_peer() const { return incoming_packets.front()->get().from; } +MultiplayerPeer::TransferMode ENetMultiplayerPeer::get_packet_mode() const { + ERR_FAIL_COND_V_MSG(!_is_active(), TRANSFER_MODE_RELIABLE, "The multiplayer instance isn't currently active."); + ERR_FAIL_COND_V(incoming_packets.size() == 0, TRANSFER_MODE_RELIABLE); + return incoming_packets.front()->get().transfer_mode; +} + +int ENetMultiplayerPeer::get_packet_channel() const { + ERR_FAIL_COND_V_MSG(!_is_active(), 1, "The multiplayer instance isn't currently active."); + ERR_FAIL_COND_V(incoming_packets.size() == 0, 1); + int ch = incoming_packets.front()->get().channel; + if (ch >= SYSCH_MAX) { // First 2 channels are reserved. + return ch - SYSCH_MAX + 1; + } + return 0; +} + Error ENetMultiplayerPeer::create_server(int p_port, int p_max_clients, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth) { ERR_FAIL_COND_V_MSG(_is_active(), ERR_ALREADY_IN_USE, "The multiplayer instance is already active."); set_refuse_new_connections(false); @@ -114,182 +130,37 @@ Error ENetMultiplayerPeer::add_mesh_peer(int p_id, Ref<ENetConnection> p_host) { return OK; } -bool ENetMultiplayerPeer::_parse_server_event(ENetConnection::EventType p_type, ENetConnection::Event &p_event) { - switch (p_type) { - case ENetConnection::EVENT_CONNECT: { - if (is_refusing_new_connections()) { - p_event.peer->reset(); - return false; - } - // Client joined with invalid ID, probably trying to exploit us. - if (p_event.data < 2 || peers.has((int)p_event.data)) { - p_event.peer->reset(); - return false; - } - int id = p_event.data; - p_event.peer->set_meta(SNAME("_net_id"), id); - peers[id] = p_event.peer; - - emit_signal(SNAME("peer_connected"), id); - if (server_relay) { - _notify_peers(id, true); - } - return false; - } - case ENetConnection::EVENT_DISCONNECT: { - int id = p_event.peer->get_meta(SNAME("_net_id")); - if (!peers.has(id)) { - // Never fully connected. - return false; - } - - emit_signal(SNAME("peer_disconnected"), id); - peers.erase(id); - if (server_relay) { - _notify_peers(id, false); - } - return false; - } - case ENetConnection::EVENT_RECEIVE: { - if (p_event.channel_id == SYSCH_CONFIG) { - _destroy_unused(p_event.packet); - ERR_FAIL_V_MSG(false, "Only server can send config messages"); - } else { - if (p_event.packet->dataLength < 8) { - _destroy_unused(p_event.packet); - ERR_FAIL_V_MSG(false, "Invalid packet size"); - } - - uint32_t source = decode_uint32(&p_event.packet->data[0]); - int target = decode_uint32(&p_event.packet->data[4]); - - uint32_t id = p_event.peer->get_meta(SNAME("_net_id")); - // Someone is cheating and trying to fake the source! - if (source != id) { - _destroy_unused(p_event.packet); - ERR_FAIL_V_MSG(false, "Someone is cheating and trying to fake the source!"); - } - - Packet packet; - packet.packet = p_event.packet; - packet.channel = p_event.channel_id; - packet.from = id; - - // Even if relaying is disabled, these targets are valid as incoming packets. - if (target == 1 || target == 0 || target < -1) { - packet.packet->referenceCount++; - incoming_packets.push_back(packet); - } - - if (server_relay && target != 1) { - packet.packet->referenceCount++; - _relay(source, target, p_event.channel_id, p_event.packet); - packet.packet->referenceCount--; - _destroy_unused(p_event.packet); - } - // Destroy packet later - } - return false; - } - default: - return true; +void ENetMultiplayerPeer::_store_packet(int32_t p_source, ENetConnection::Event &p_event) { + Packet packet; + packet.packet = p_event.packet; + packet.channel = p_event.channel_id; + packet.from = p_source; + if (p_event.packet->flags & ENET_PACKET_FLAG_RELIABLE) { + packet.transfer_mode = TRANSFER_MODE_RELIABLE; + } else if (p_event.packet->flags & ENET_PACKET_FLAG_UNSEQUENCED) { + packet.transfer_mode = TRANSFER_MODE_UNRELIABLE; + } else { + packet.transfer_mode = TRANSFER_MODE_UNRELIABLE_ORDERED; } + packet.packet->referenceCount++; + incoming_packets.push_back(packet); } -bool ENetMultiplayerPeer::_parse_client_event(ENetConnection::EventType p_type, ENetConnection::Event &p_event) { - switch (p_type) { - case ENetConnection::EVENT_CONNECT: { - connection_status = CONNECTION_CONNECTED; - emit_signal(SNAME("peer_connected"), 1); - emit_signal(SNAME("connection_succeeded")); - return false; - } - case ENetConnection::EVENT_DISCONNECT: { - if (connection_status == CONNECTION_CONNECTED) { - // Client just disconnected from server. - emit_signal(SNAME("server_disconnected")); - } else { - emit_signal(SNAME("connection_failed")); - } - close_connection(); - return true; - } - case ENetConnection::EVENT_RECEIVE: { - if (p_event.channel_id == SYSCH_CONFIG) { - // Config message - if (p_event.packet->dataLength != 8) { - _destroy_unused(p_event.packet); - ERR_FAIL_V(false); - } - - int msg = decode_uint32(&p_event.packet->data[0]); - int id = decode_uint32(&p_event.packet->data[4]); - - switch (msg) { - case SYSMSG_ADD_PEER: { - peers[id] = Ref<ENetPacketPeer>(); - emit_signal(SNAME("peer_connected"), id); - - } break; - case SYSMSG_REMOVE_PEER: { - peers.erase(id); - emit_signal(SNAME("peer_disconnected"), id); - } break; - } - _destroy_unused(p_event.packet); - } else { - if (p_event.packet->dataLength < 8) { - _destroy_unused(p_event.packet); - ERR_FAIL_V_MSG(false, "Invalid packet size"); - } - - uint32_t source = decode_uint32(&p_event.packet->data[0]); - Packet packet; - packet.packet = p_event.packet; - packet.from = source; - packet.channel = p_event.channel_id; - - packet.packet->referenceCount++; - incoming_packets.push_back(packet); - // Destroy packet later - } - return false; +void ENetMultiplayerPeer::_disconnect_inactive_peers() { + HashSet<int> to_drop; + for (const KeyValue<int, Ref<ENetPacketPeer>> &E : peers) { + if (E.value->is_active()) { + continue; } - default: - return true; + to_drop.insert(E.key); } -} - -bool ENetMultiplayerPeer::_parse_mesh_event(ENetConnection::EventType p_type, ENetConnection::Event &p_event, int p_peer_id) { - switch (p_type) { - case ENetConnection::EVENT_CONNECT: - p_event.peer->reset(); - return false; - case ENetConnection::EVENT_DISCONNECT: - if (peers.has(p_peer_id)) { - emit_signal(SNAME("peer_disconnected"), p_peer_id); - peers.erase(p_peer_id); - } - hosts.erase(p_peer_id); - return true; - case ENetConnection::EVENT_RECEIVE: { - if (p_event.packet->dataLength < 8) { - _destroy_unused(p_event.packet); - ERR_FAIL_V_MSG(false, "Invalid packet size"); - } - - Packet packet; - packet.packet = p_event.packet; - packet.from = p_peer_id; - packet.channel = p_event.channel_id; - - packet.packet->referenceCount++; - incoming_packets.push_back(packet); - return false; - } break; - default: - // Nothing to do - return true; + for (const int &P : to_drop) { + peers.erase(P); + if (hosts.has(P)) { + hosts.erase(P); + } + ERR_CONTINUE(active_mode == MODE_CLIENT && P != TARGET_PEER_SERVER); + emit_signal(SNAME("peer_disconnected"), P); } } @@ -298,74 +169,92 @@ void ENetMultiplayerPeer::poll() { _pop_current_packet(); + _disconnect_inactive_peers(); + switch (active_mode) { case MODE_CLIENT: { - if (peers.has(1) && !peers[1]->is_active()) { - if (connection_status == CONNECTION_CONNECTED) { - // Client just disconnected from server. - emit_signal(SNAME("server_disconnected")); - } else { - emit_signal(SNAME("connection_failed")); - } - close_connection(); + if (!peers.has(1)) { + close(); return; } ENetConnection::Event event; ENetConnection::EventType ret = hosts[0]->service(0, event); - if (ret == ENetConnection::EVENT_ERROR) { - return; - } do { - if (_parse_client_event(ret, event)) { - return; + if (ret == ENetConnection::EVENT_CONNECT) { + connection_status = CONNECTION_CONNECTED; + emit_signal(SNAME("peer_connected"), 1); + } else if (ret == ENetConnection::EVENT_DISCONNECT) { + if (connection_status == CONNECTION_CONNECTED) { + // Client just disconnected from server. + emit_signal(SNAME("peer_disconnected"), 1); + } + close(); + } else if (ret == ENetConnection::EVENT_RECEIVE) { + _store_packet(1, event); + } else if (ret != ENetConnection::EVENT_NONE) { + close(); // Error. } - } while (hosts[0]->check_events(ret, event) > 0); + } while (hosts.has(0) && hosts[0]->check_events(ret, event) > 0); } break; case MODE_SERVER: { - for (const KeyValue<int, Ref<ENetPacketPeer>> &E : peers) { - if (!(E.value->is_active())) { - emit_signal(SNAME("peer_disconnected"), E.value->get_meta(SNAME("_net_id"))); - peers.erase(E.key); - } - } ENetConnection::Event event; ENetConnection::EventType ret = hosts[0]->service(0, event); - if (ret == ENetConnection::EVENT_ERROR) { - return; - } do { - if (_parse_server_event(ret, event)) { - return; + if (ret == ENetConnection::EVENT_CONNECT) { + if (is_refusing_new_connections()) { + event.peer->reset(); + continue; + } + // Client joined with invalid ID, probably trying to exploit us. + if (event.data < 2 || peers.has((int)event.data)) { + event.peer->reset(); + continue; + } + int id = event.data; + event.peer->set_meta(SNAME("_net_id"), id); + peers[id] = event.peer; + emit_signal(SNAME("peer_connected"), id); + } else if (ret == ENetConnection::EVENT_DISCONNECT) { + int id = event.peer->get_meta(SNAME("_net_id")); + if (!peers.has(id)) { + // Never fully connected. + continue; + } + emit_signal(SNAME("peer_disconnected"), id); + peers.erase(id); + } else if (ret == ENetConnection::EVENT_RECEIVE) { + int32_t source = event.peer->get_meta(SNAME("_net_id")); + _store_packet(source, event); + } else if (ret != ENetConnection::EVENT_NONE) { + close(); // Error } - } while (hosts[0]->check_events(ret, event) > 0); + } while (hosts.has(0) && hosts[0]->check_events(ret, event) > 0); } break; case MODE_MESH: { - for (const KeyValue<int, Ref<ENetPacketPeer>> &E : peers) { - if (!(E.value->is_active())) { - emit_signal(SNAME("peer_disconnected"), E.key); - peers.erase(E.key); - if (hosts.has(E.key)) { - hosts.erase(E.key); - } - } - } + HashSet<int> to_drop; for (KeyValue<int, Ref<ENetConnection>> &E : hosts) { ENetConnection::Event event; ENetConnection::EventType ret = E.value->service(0, event); - if (ret == ENetConnection::EVENT_ERROR) { - if (peers.has(E.key)) { - emit_signal(SNAME("peer_disconnected"), E.key); - peers.erase(E.key); - } - hosts.erase(E.key); - continue; - } do { - if (_parse_mesh_event(ret, event, E.key)) { + if (ret == ENetConnection::EVENT_CONNECT) { + event.peer->reset(); + } else if (ret == ENetConnection::EVENT_RECEIVE) { + _store_packet(E.key, event); + } else if (ret == ENetConnection::EVENT_NONE) { + break; // Keep polling the others. + } else { + to_drop.insert(E.key); // Error or disconnect. break; // Keep polling the others. } } while (E.value->check_events(ret, event) > 0); } + for (const int &P : to_drop) { + if (peers.has(P)) { + emit_signal(SNAME("peer_disconnected"), P); + peers.erase(P); + } + hosts.erase(P); + } } break; default: return; @@ -376,29 +265,45 @@ bool ENetMultiplayerPeer::is_server() const { return active_mode == MODE_SERVER; } -void ENetMultiplayerPeer::close_connection(uint32_t wait_usec) { +bool ENetMultiplayerPeer::is_server_relay_supported() const { + return active_mode == MODE_SERVER || active_mode == MODE_CLIENT; +} + +void ENetMultiplayerPeer::disconnect_peer(int p_peer, bool p_force) { + ERR_FAIL_COND(!_is_active() || !peers.has(p_peer)); + peers[p_peer]->peer_disconnect(0); // Will be removed during next poll. + if (active_mode == MODE_CLIENT || active_mode == MODE_SERVER) { + hosts[0]->flush(); + } else { + ERR_FAIL_COND(!hosts.has(p_peer)); + hosts[p_peer]->flush(); + } + if (p_force) { + peers.erase(p_peer); + if (hosts.has(p_peer)) { + hosts.erase(p_peer); + } + if (active_mode == MODE_CLIENT) { + hosts.clear(); // Avoid flushing again. + close(); + } + } +} + +void ENetMultiplayerPeer::close() { if (!_is_active()) { return; } _pop_current_packet(); - bool peers_disconnected = false; for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) { if (E.value.is_valid() && E.value->get_state() == ENetPacketPeer::STATE_CONNECTED) { - E.value->peer_disconnect_now(unique_id); - peers_disconnected = true; + E.value->peer_disconnect_now(0); } } - - if (peers_disconnected) { - for (KeyValue<int, Ref<ENetConnection>> &E : hosts) { - E.value->flush(); - } - - if (wait_usec > 0) { - OS::get_singleton()->delay_usec(wait_usec); // Wait for disconnection packets to send - } + for (KeyValue<int, Ref<ENetConnection>> &E : hosts) { + E.value->flush(); } active_mode = MODE_NONE; @@ -422,8 +327,8 @@ Error ENetMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_si current_packet = incoming_packets.front()->get(); incoming_packets.pop_front(); - *r_buffer = (const uint8_t *)(¤t_packet.packet->data[8]); - r_buffer_size = current_packet.packet->dataLength - 8; + *r_buffer = (const uint8_t *)(current_packet.packet->data); + r_buffer_size = current_packet.packet->dataLength; return OK; } @@ -436,9 +341,9 @@ Error ENetMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size int packet_flags = 0; int channel = SYSCH_RELIABLE; - int transfer_channel = get_transfer_channel(); - if (transfer_channel > 0) { - channel = SYSCH_MAX + transfer_channel - 1; + int tr_channel = get_transfer_channel(); + if (tr_channel > 0) { + channel = SYSCH_MAX + tr_channel - 1; } else { switch (get_transfer_mode()) { case TRANSFER_MODE_UNRELIABLE: { @@ -457,15 +362,13 @@ Error ENetMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size } #ifdef DEBUG_ENABLED - if ((packet_flags & ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT) && p_buffer_size + 8 > ENET_HOST_DEFAULT_MTU) { - WARN_PRINT_ONCE(vformat("Sending %d bytes unrealiably which is above the MTU (%d), this will result in higher packet loss", p_buffer_size + 8, ENET_HOST_DEFAULT_MTU)); + if ((packet_flags & ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT) && p_buffer_size > ENET_HOST_DEFAULT_MTU) { + WARN_PRINT_ONCE(vformat("Sending %d bytes unrealiably which is above the MTU (%d), this will result in higher packet loss", p_buffer_size, ENET_HOST_DEFAULT_MTU)); } #endif - ENetPacket *packet = enet_packet_create(nullptr, p_buffer_size + 8, packet_flags); - encode_uint32(unique_id, &packet->data[0]); // Source ID - encode_uint32(target_peer, &packet->data[4]); // Dest ID - memcpy(&packet->data[8], p_buffer, p_buffer_size); + ENetPacket *packet = enet_packet_create(nullptr, p_buffer_size, packet_flags); + memcpy(&packet->data[0], p_buffer, p_buffer_size); if (is_server()) { if (target_peer == 0) { @@ -548,16 +451,6 @@ void ENetMultiplayerPeer::set_refuse_new_connections(bool p_enabled) { MultiplayerPeer::set_refuse_new_connections(p_enabled); } -void ENetMultiplayerPeer::set_server_relay_enabled(bool p_enabled) { - ERR_FAIL_COND_MSG(_is_active(), "Server relaying can't be toggled while the multiplayer instance is active."); - - server_relay = p_enabled; -} - -bool ENetMultiplayerPeer::is_server_relay_enabled() const { - return server_relay; -} - Ref<ENetConnection> ENetMultiplayerPeer::get_host() const { ERR_FAIL_COND_V(!_is_active(), nullptr); ERR_FAIL_COND_V(active_mode == MODE_MESH, nullptr); @@ -577,84 +470,16 @@ void ENetMultiplayerPeer::_destroy_unused(ENetPacket *p_packet) { } } -void ENetMultiplayerPeer::_relay(int p_from, int p_to, enet_uint8 p_channel, ENetPacket *p_packet) { - if (p_to == 0) { - // Re-send to everyone but sender :| - for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) { - if (E.key == p_from) { - continue; - } - - E.value->send(p_channel, p_packet); - } - } else if (p_to < 0) { - // Re-send to everyone but excluded and sender. - for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) { - if (E.key == p_from || E.key == -p_to) { // Do not resend to self, also do not send to excluded - continue; - } - - E.value->send(p_channel, p_packet); - } - } else { - // To someone else, specifically - ERR_FAIL_COND(!peers.has(p_to)); - ENetPacket *packet = enet_packet_create(p_packet->data, p_packet->dataLength, p_packet->flags); - peers[p_to]->send(p_channel, packet); - } -} - -void ENetMultiplayerPeer::_notify_peers(int p_id, bool p_connected) { - if (p_connected) { - ERR_FAIL_COND(!peers.has(p_id)); - // Someone connected, notify all the peers available. - Ref<ENetPacketPeer> peer = peers[p_id]; - ENetPacket *packet = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE); - encode_uint32(SYSMSG_ADD_PEER, &packet->data[0]); - encode_uint32(p_id, &packet->data[4]); - for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) { - if (E.key == p_id) { - continue; - } - // Send new peer to existing peer. - E.value->send(SYSCH_CONFIG, packet); - // Send existing peer to new peer. - // This packet will be automatically destroyed by ENet after send. - ENetPacket *packet2 = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE); - encode_uint32(SYSMSG_ADD_PEER, &packet2->data[0]); - encode_uint32(E.key, &packet2->data[4]); - peer->send(SYSCH_CONFIG, packet2); - } - _destroy_unused(packet); - } else { - // Server just received a client disconnect and is in relay mode, notify everyone else. - ENetPacket *packet = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE); - encode_uint32(SYSMSG_REMOVE_PEER, &packet->data[0]); - encode_uint32(p_id, &packet->data[4]); - for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) { - if (E.key == p_id) { - continue; - } - E.value->send(SYSCH_CONFIG, packet); - } - _destroy_unused(packet); - } -} - void ENetMultiplayerPeer::_bind_methods() { ClassDB::bind_method(D_METHOD("create_server", "port", "max_clients", "max_channels", "in_bandwidth", "out_bandwidth"), &ENetMultiplayerPeer::create_server, DEFVAL(32), DEFVAL(0), DEFVAL(0), DEFVAL(0)); ClassDB::bind_method(D_METHOD("create_client", "address", "port", "channel_count", "in_bandwidth", "out_bandwidth", "local_port"), &ENetMultiplayerPeer::create_client, DEFVAL(0), DEFVAL(0), DEFVAL(0), DEFVAL(0)); ClassDB::bind_method(D_METHOD("create_mesh", "unique_id"), &ENetMultiplayerPeer::create_mesh); ClassDB::bind_method(D_METHOD("add_mesh_peer", "peer_id", "host"), &ENetMultiplayerPeer::add_mesh_peer); - ClassDB::bind_method(D_METHOD("close_connection", "wait_usec"), &ENetMultiplayerPeer::close_connection, DEFVAL(100)); ClassDB::bind_method(D_METHOD("set_bind_ip", "ip"), &ENetMultiplayerPeer::set_bind_ip); - ClassDB::bind_method(D_METHOD("set_server_relay_enabled", "enabled"), &ENetMultiplayerPeer::set_server_relay_enabled); - ClassDB::bind_method(D_METHOD("is_server_relay_enabled"), &ENetMultiplayerPeer::is_server_relay_enabled); ClassDB::bind_method(D_METHOD("get_host"), &ENetMultiplayerPeer::get_host); ClassDB::bind_method(D_METHOD("get_peer", "id"), &ENetMultiplayerPeer::get_peer); - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "server_relay"), "set_server_relay_enabled", "is_server_relay_enabled"); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "host", PROPERTY_HINT_RESOURCE_TYPE, "ENetConnection", PROPERTY_USAGE_NONE), "", "get_host"); } @@ -664,7 +489,7 @@ ENetMultiplayerPeer::ENetMultiplayerPeer() { ENetMultiplayerPeer::~ENetMultiplayerPeer() { if (_is_active()) { - close_connection(); + close(); } } diff --git a/modules/enet/enet_multiplayer_peer.h b/modules/enet/enet_multiplayer_peer.h index 3152068d46..2665b69669 100644 --- a/modules/enet/enet_multiplayer_peer.h +++ b/modules/enet/enet_multiplayer_peer.h @@ -47,10 +47,9 @@ private: }; enum { - SYSCH_CONFIG = 0, - SYSCH_RELIABLE = 1, - SYSCH_UNRELIABLE = 2, - SYSCH_MAX = 3 + SYSCH_RELIABLE = 0, + SYSCH_UNRELIABLE = 1, + SYSCH_MAX = 2 }; enum Mode { @@ -66,8 +65,6 @@ private: int target_peer = 0; - bool server_relay = true; - ConnectionStatus connection_status = CONNECTION_DISCONNECTED; HashMap<int, Ref<ENetConnection>> hosts; @@ -77,18 +74,16 @@ private: ENetPacket *packet = nullptr; int from = 0; int channel = 0; + TransferMode transfer_mode = TRANSFER_MODE_RELIABLE; }; List<Packet> incoming_packets; Packet current_packet; + void _store_packet(int32_t p_source, ENetConnection::Event &p_event); void _pop_current_packet(); - bool _parse_server_event(ENetConnection::EventType p_event_type, ENetConnection::Event &p_event); - bool _parse_client_event(ENetConnection::EventType p_event_type, ENetConnection::Event &p_event); - bool _parse_mesh_event(ENetConnection::EventType p_event_type, ENetConnection::Event &p_event, int p_peer_id); - void _relay(int p_from, int p_to, enet_uint8 p_channel, ENetPacket *p_packet); - void _notify_peers(int p_id, bool p_connected); + void _disconnect_inactive_peers(); void _destroy_unused(ENetPacket *p_packet); _FORCE_INLINE_ bool _is_active() const { return active_mode != MODE_NONE; } @@ -99,10 +94,18 @@ protected: public: virtual void set_target_peer(int p_peer) override; + virtual int get_packet_peer() const override; + virtual TransferMode get_packet_mode() const override; + virtual int get_packet_channel() const override; virtual void poll() override; + virtual void close() override; + virtual void disconnect_peer(int p_peer, bool p_force = false) override; + virtual bool is_server() const override; + virtual bool is_server_relay_supported() const override; + // Overridden so we can instrument the DTLSServer when needed. virtual void set_refuse_new_connections(bool p_enabled) override; @@ -120,13 +123,7 @@ public: Error create_mesh(int p_id); Error add_mesh_peer(int p_id, Ref<ENetConnection> p_host); - void close_connection(uint32_t wait_usec = 100); - - void disconnect_peer(int p_peer, bool now = false); - void set_bind_ip(const IPAddress &p_ip); - void set_server_relay_enabled(bool p_enabled); - bool is_server_relay_enabled() const; Ref<ENetConnection> get_host() const; Ref<ENetPacketPeer> get_peer(int p_id) const; diff --git a/modules/etcpak/config.py b/modules/etcpak/config.py index 53b8f2f2e3..eb565b85b9 100644 --- a/modules/etcpak/config.py +++ b/modules/etcpak/config.py @@ -1,5 +1,5 @@ def can_build(env, platform): - return env["tools"] + return env.editor_build def configure(env): diff --git a/modules/etcpak/image_compress_etcpak.cpp b/modules/etcpak/image_compress_etcpak.cpp index 7d5557d197..3d66b27556 100644 --- a/modules/etcpak/image_compress_etcpak.cpp +++ b/modules/etcpak/image_compress_etcpak.cpp @@ -233,7 +233,7 @@ void _compress_etcpak(EtcpakType p_compresstype, Image *r_img, float p_lossy_qua } // Replace original image with compressed one. - r_img->create(width, height, mipmaps, target_format, dest_data); + r_img->set_data(width, height, mipmaps, target_format, dest_data); print_verbose(vformat("ETCPAK encode took %s ms.", rtos(OS::get_singleton()->get_ticks_msec() - start_time))); } diff --git a/modules/freetype/SCsub b/modules/freetype/SCsub index 2680479acc..0b86bc569f 100644 --- a/modules/freetype/SCsub +++ b/modules/freetype/SCsub @@ -90,7 +90,7 @@ if env["builtin_freetype"]: env.Prepend(CPPPATH=[thirdparty_dir + "/include"]) env_freetype.Append(CPPDEFINES=["FT2_BUILD_LIBRARY", "FT_CONFIG_OPTION_USE_PNG", "FT_CONFIG_OPTION_SYSTEM_ZLIB"]) - if env["target"] == "debug": + if env.dev_build: env_freetype.Append(CPPDEFINES=["ZLIB_DEBUG"]) # Also requires libpng headers diff --git a/modules/gdscript/SCsub b/modules/gdscript/SCsub index 2f507db548..1dc4768186 100644 --- a/modules/gdscript/SCsub +++ b/modules/gdscript/SCsub @@ -7,7 +7,7 @@ env_gdscript = env_modules.Clone() env_gdscript.add_source_files(env.modules_sources, "*.cpp") -if env["tools"]: +if env.editor_build: env_gdscript.add_source_files(env.modules_sources, "./editor/*.cpp") SConscript("editor/script_templates/SCsub") diff --git a/modules/gdscript/doc_classes/@GDScript.xml b/modules/gdscript/doc_classes/@GDScript.xml index 4a38caea52..c8eda53a2d 100644 --- a/modules/gdscript/doc_classes/@GDScript.xml +++ b/modules/gdscript/doc_classes/@GDScript.xml @@ -18,13 +18,11 @@ <param index="2" name="b8" type="int" /> <param index="3" name="a8" type="int" default="255" /> <description> - Returns a color constructed from integer red, green, blue, and alpha channels. Each channel should have 8 bits of information ranging from 0 to 255. - [code]r8[/code] red channel - [code]g8[/code] green channel - [code]b8[/code] blue channel - [code]a8[/code] alpha channel + Returns a [Color] constructed from red ([param r8]), green ([param g8]), blue ([param b8]), and optionally alpha ([param a8]) integer channels, each divided by [code]255.0[/code] for their final value. [codeblock] - red = Color8(255, 0, 0) + var red = Color8(255, 0, 0) # Same as Color(1, 0, 0) + var dark_blue = Color8(0, 0, 51) # Same as Color(0, 0, 0.2). + var my_color = Color8(306, 255, 0, 102) # Same as Color(1.2, 1, 0, 0.4). [/codeblock] </description> </method> @@ -33,16 +31,16 @@ <param index="0" name="condition" type="bool" /> <param index="1" name="message" type="String" default="""" /> <description> - Asserts that the [code]condition[/code] is [code]true[/code]. If the [code]condition[/code] is [code]false[/code], an error is generated. When running from the editor, the running project will also be paused until you resume it. This can be used as a stronger form of [method @GlobalScope.push_error] for reporting errors to project developers or add-on users. - [b]Note:[/b] For performance reasons, the code inside [method assert] is only executed in debug builds or when running the project from the editor. Don't include code that has side effects in an [method assert] call. Otherwise, the project will behave differently when exported in release mode. - The optional [code]message[/code] argument, if given, is shown in addition to the generic "Assertion failed" message. You can use this to provide additional details about why the assertion failed. + Asserts that the [param condition] is [code]true[/code]. If the [param condition] is [code]false[/code], an error is generated. When running from the editor, the running project will also be paused until you resume it. This can be used as a stronger form of [method @GlobalScope.push_error] for reporting errors to project developers or add-on users. + An optional [param message] can be shown in addition to the generic "Assertion failed" message. You can use this to provide additional details about why the assertion failed. + [b]Warning:[/b] For performance reasons, the code inside [method assert] is only executed in debug builds or when running the project from the editor. Don't include code that has side effects in an [method assert] call. Otherwise, the project will behave differently when exported in release mode. [codeblock] # Imagine we always want speed to be between 0 and 20. var speed = -10 assert(speed < 20) # True, the program will continue assert(speed >= 0) # False, the program will stop assert(speed >= 0 and speed < 20) # You can also combine the two conditional statements in one check - assert(speed < 20, "speed = %f, but the speed limit is 20" % speed) # Show a message with clarifying details + assert(speed < 20, "the speed limit is 20") # Show a message [/codeblock] </description> </method> @@ -50,7 +48,7 @@ <return type="String" /> <param index="0" name="char" type="int" /> <description> - Returns a character as a String of the given Unicode code point (which is compatible with ASCII code). + Returns a single character (as a [String]) of the given Unicode code point (which is compatible with ASCII code). [codeblock] a = char(65) # a is "A" a = char(65 + 32) # a is "a" @@ -63,14 +61,14 @@ <param index="0" name="what" type="Variant" /> <param index="1" name="type" type="int" /> <description> - Converts from a type to another in the best way possible. The [code]type[/code] parameter uses the [enum Variant.Type] values. + Converts [param what] to [param type] in the best way possible. The [param type] uses the [enum Variant.Type] values. [codeblock] - a = Vector2(1, 0) - # Prints 1 - print(a.length()) - a = convert(a, TYPE_STRING) - # Prints 6 as "(1, 0)" is 6 characters - print(a.length()) + var a = [4, 2.5, 1.2] + print(a is Array) # Prints true + + var b = convert(a, TYPE_PACKED_BYTE_ARRAY) + print(b) # Prints [4, 2, 1] + print(b is Array) # Prints false [/codeblock] </description> </method> @@ -78,13 +76,13 @@ <return type="Object" /> <param index="0" name="dictionary" type="Dictionary" /> <description> - Converts a [param dictionary] (previously created with [method inst_to_dict]) back to an Object instance. Useful for deserializing. + Converts a [param dictionary] (created with [method inst_to_dict]) back to an Object instance. Can be useful for deserializing. </description> </method> <method name="get_stack"> <return type="Array" /> <description> - Returns an array of dictionaries representing the current call stack. + Returns an array of dictionaries representing the current call stack. See also [method print_stack]. [codeblock] func _ready(): foo() @@ -95,18 +93,19 @@ func bar(): print(get_stack()) [/codeblock] - would print + Starting from [code]_ready()[/code], [code]bar()[/code] would print: [codeblock] [{function:bar, line:12, source:res://script.gd}, {function:foo, line:9, source:res://script.gd}, {function:_ready, line:6, source:res://script.gd}] [/codeblock] - [b]Note:[/b] Not supported for calling from threads. Instead, this will return an empty array. + [b]Note:[/b] This function only works if the running instance is connected to a debugging server (i.e. an editor instance). [method get_stack] will not work in projects exported in release mode, or in projects exported in debug mode if not connected to a debugging server. + [b]Note:[/b] Calling this function from a [Thread] is not supported. Doing so will return an empty array. </description> </method> <method name="inst_to_dict"> <return type="Dictionary" /> <param index="0" name="instance" type="Object" /> <description> - Returns the passed [param instance] converted to a Dictionary (useful for serializing). + Returns the passed [param instance] converted to a Dictionary. Can be useful for serializing. [codeblock] var foo = "bar" func _ready(): @@ -125,11 +124,13 @@ <return type="int" /> <param index="0" name="var" type="Variant" /> <description> - Returns length of Variant [code]var[/code]. Length is the character count of String, element count of Array, size of Dictionary, etc. - [b]Note:[/b] Generates a fatal error if Variant can not provide a length. + Returns the length of the given Variant [param var]. The length can be the character count of a [String], the element count of any array type or the size of a [Dictionary]. For every other Variant type, a run-time error is generated and execution is stopped. [codeblock] a = [1, 2, 3, 4] len(a) # Returns 4 + + b = "Hello!" + len(b) # Returns 6 [/codeblock] </description> </method> @@ -137,25 +138,25 @@ <return type="Resource" /> <param index="0" name="path" type="String" /> <description> - Loads a resource from the filesystem located at [code]path[/code]. The resource is loaded on the method call (unless it's referenced already elsewhere, e.g. in another script or in the scene), which might cause slight delay, especially when loading scenes. To avoid unnecessary delays when loading something multiple times, either store the resource in a variable or use [method preload]. + Returns a [Resource] from the filesystem located at the absolute [param path]. Unless it's already referenced elsewhere (such as in another script or in the scene), the resource is loaded from disk on function call, which might cause a slight delay, especially when loading large scenes. To avoid unnecessary delays when loading something multiple times, either store the resource in a variable or use [method preload]. [b]Note:[/b] Resource paths can be obtained by right-clicking on a resource in the FileSystem dock and choosing "Copy Path" or by dragging the file from the FileSystem dock into the script. [codeblock] - # Load a scene called main located in the root of the project directory and cache it in a variable. + # Load a scene called "main" located in the root of the project directory and cache it in a variable. var main = load("res://main.tscn") # main will contain a PackedScene resource. [/codeblock] - [b]Important:[/b] The path must be absolute, a local path will just return [code]null[/code]. - This method is a simplified version of [method ResourceLoader.load], which can be used for more advanced scenarios. - [b]Note:[/b] You have to import the files into the engine first to load them using [method load]. If you want to load [Image]s at run-time, you may use [method Image.load]. If you want to import audio files, you can use the snippet described in [member AudioStreamMP3.data]. + [b]Important:[/b] The path must be absolute. A relative path will always return [code]null[/code]. + This function is a simplified version of [method ResourceLoader.load], which can be used for more advanced scenarios. + [b]Note:[/b] Files have to be imported into the engine first to load them using this function. If you want to load [Image]s at run-time, you may use [method Image.load]. If you want to import audio files, you can use the snippet described in [member AudioStreamMP3.data]. </description> </method> <method name="preload"> <return type="Resource" /> <param index="0" name="path" type="String" /> <description> - Returns a [Resource] from the filesystem located at [code]path[/code]. The resource is loaded during script parsing, i.e. is loaded with the script and [method preload] effectively acts as a reference to that resource. Note that the method requires a constant path. If you want to load a resource from a dynamic/variable path, use [method load]. + Returns a [Resource] from the filesystem located at [param path]. During run-time, the resource is loaded when the script is being parsed. This function effectively acts as a reference to that resource. Note that this function requires [param path] to be a constant [String]. If you want to load a resource from a dynamic/variable path, use [method load]. [b]Note:[/b] Resource paths can be obtained by right clicking on a resource in the Assets Panel and choosing "Copy Path" or by dragging the file from the FileSystem dock into the script. [codeblock] - # Instance a scene. + # Create instance of a scene. var diamond = preload("res://diamond.tscn").instantiate() [/codeblock] </description> @@ -164,23 +165,24 @@ <return type="void" /> <description> Like [method @GlobalScope.print], but includes the current stack frame when running with the debugger turned on. - Output in the console would look something like this: + The output in the console may look like the following: [codeblock] Test print - At: res://test.gd:15:_process() + At: res://test.gd:15:_process() [/codeblock] - [b]Note:[/b] Not supported for calling from threads. Instead of the stack frame, this will print the thread ID. + [b]Note:[/b] Calling this function from a [Thread] is not supported. Doing so will instead print the thread ID. </description> </method> <method name="print_stack"> <return type="void" /> <description> - Prints a stack trace at the current code location. Only works when running with debugger turned on. - Output in the console would look something like this: + Prints a stack trace at the current code location. See also [method get_stack]. + The output in the console may look like the following: [codeblock] Frame 0 - res://test.gd:16 in function '_process' [/codeblock] - [b]Note:[/b] Not supported for calling from threads. Instead of the stack trace, this will print the thread ID. + [b]Note:[/b] This function only works if the running instance is connected to a debugging server (i.e. an editor instance). [method print_stack] will not work in projects exported in release mode, or in projects exported in debug mode if not connected to a debugging server. + [b]Note:[/b] Calling this function from a [Thread] is not supported. Doing so will instead print the thread ID. </description> </method> <method name="range" qualifiers="vararg"> @@ -227,7 +229,7 @@ <method name="str" qualifiers="vararg"> <return type="String" /> <description> - Converts one or more arguments to string in the best way possible. + Converts one or more arguments to a [String] in the best way possible. [codeblock] var a = [10, 20, 30] var b = str(a); @@ -240,7 +242,7 @@ <return type="bool" /> <param index="0" name="type" type="StringName" /> <description> - Returns whether the given [Object]-derived class exists in [ClassDB]. Note that [Variant] data types are not registered in [ClassDB]. + Returns [code]true[/code] if the given [Object]-derived class exists in [ClassDB]. Note that [Variant] data types are not registered in [ClassDB]. [codeblock] type_exists("Sprite2D") # Returns true type_exists("NonExistentClass") # Returns false @@ -257,11 +259,11 @@ </constant> <constant name="INF" value="inf"> Positive floating-point infinity. This is the result of floating-point division when the divisor is [code]0.0[/code]. For negative infinity, use [code]-INF[/code]. Dividing by [code]-0.0[/code] will result in negative infinity if the numerator is positive, so dividing by [code]0.0[/code] is not the same as dividing by [code]-0.0[/code] (despite [code]0.0 == -0.0[/code] returning [code]true[/code]). - [b]Note:[/b] Numeric infinity is only a concept with floating-point numbers, and has no equivalent for integers. Dividing an integer number by [code]0[/code] will not result in [constant INF] and will result in a run-time error instead. + [b]Warning:[/b] Numeric infinity is only a concept with floating-point numbers, and has no equivalent for integers. Dividing an integer number by [code]0[/code] will not result in [constant INF] and will result in a run-time error instead. </constant> <constant name="NAN" value="nan"> "Not a Number", an invalid floating-point value. [constant NAN] has special properties, including that it is not equal to itself ([code]NAN == NAN[/code] returns [code]false[/code]). It is output by some invalid operations, such as dividing floating-point [code]0.0[/code] by [code]0.0[/code]. - [b]Note:[/b] "Not a Number" is only a concept with floating-point numbers, and has no equivalent for integers. Dividing an integer [code]0[/code] by [code]0[/code] will not result in [constant NAN] and will result in a run-time error instead. + [b]Warning:[/b] "Not a Number" is only a concept with floating-point numbers, and has no equivalent for integers. Dividing an integer [code]0[/code] by [code]0[/code] will not result in [constant NAN] and will result in a run-time error instead. </constant> </constants> <annotations> @@ -292,7 +294,7 @@ <annotation name="@export_color_no_alpha"> <return type="void" /> <description> - Export a [Color] property without an alpha (fixed as [code]1.0[/code]). + Export a [Color] property without transparency (its alpha fixed as [code]1.0[/code]). See also [constant PROPERTY_HINT_COLOR_NO_ALPHA]. [codeblock] @export_color_no_alpha var modulate_color: Color @@ -318,7 +320,7 @@ [codeblock] @export_enum("Rebecca", "Mary", "Leah") var character_name: String @export_enum("Warrior", "Magician", "Thief") var character_class: int - @export_enum("Walking:30", "Running:60", "Riding:200") var character_speed: int + @export_enum("Slow:30", "Average:60", "Very Fast:200") var character_speed: int [/codeblock] </description> </annotation> @@ -448,8 +450,8 @@ <param index="1" name="prefix" type="String" default="""" /> <description> Define a new group for the following exported properties. This helps to organize properties in the Inspector dock. Groups can be added with an optional [param prefix], which would make group to only consider properties that have this prefix. The grouping will break on the first property that doesn't have a prefix. The prefix is also removed from the property's name in the Inspector dock. - If no [param prefix] is provided, the every following property is added to the group. The group ends when then next group or category is defined. You can also force end a group by using this annotation with empty strings for paramters, [code]@export_group("", "")[/code]. - Groups cannot be nested, use [annotation @export_subgroup] to add subgroups to your groups. + If no [param prefix] is provided, the every following property is added to the group. The group ends when then next group or category is defined. You can also force end a group by using this annotation with empty strings for parameters, [code]@export_group("", "")[/code]. + Groups cannot be nested, use [annotation @export_subgroup] to add subgroups within groups. See also [constant PROPERTY_USAGE_GROUP]. [codeblock] @export_group("My Properties") @@ -471,7 +473,7 @@ Export a [String] property with a large [TextEdit] widget instead of a [LineEdit]. This adds support for multiline content and makes it easier to edit large amount of text stored in the property. See also [constant PROPERTY_HINT_MULTILINE_TEXT]. [codeblock] - @export_multiline var character_bio + @export_multiline var character_biography [/codeblock] </description> </annotation> @@ -505,7 +507,7 @@ <param index="3" name="extra_hints" type="String" default="""" /> <description> Export a numeric property as a range value. The range must be defined by [param min] and [param max], as well as an optional [param step] and a variety of extra hints. The [param step] defaults to [code]1[/code] for integer properties. For floating-point numbers this value depends on your [code]EditorSettings.interface/inspector/default_float_step[/code] setting. - If hints [code]"or_greater"[/code] and [code]"or_less"[/code] are provided, the editor widget will not cap the value at range boundaries. The [code]"exp"[/code] hint will make the edited values on range to change exponentially. The [code]"no_slider"[/code] hint will hide the slider element of the editor widget. + If hints [code]"or_greater"[/code] and [code]"or_less"[/code] are provided, the editor widget will not cap the value at range boundaries. The [code]"exp"[/code] hint will make the edited values on range to change exponentially. The [code]"hide_slider"[/code] hint will hide the slider element of the editor widget. Hints also allow to indicate the units for the edited value. Using [code]"radians"[/code] you can specify that the actual value is in radians, but should be displayed in degrees in the Inspector dock. [code]"degrees"[/code] allows to add a degree sign as a unit suffix. Finally, a custom suffix can be provided using [code]"suffix:unit"[/code], where "unit" can be any string. See also [constant PROPERTY_HINT_RANGE]. [codeblock] @@ -545,17 +547,17 @@ <return type="void" /> <param index="0" name="icon_path" type="String" /> <description> - Add a custom icon to the current script. The icon is displayed in the Scene dock for every node that the script is attached to. For named classes the icon is also displayed in various editor dialogs. + Add a custom icon to the current script. After loading an icon at [param icon_path], the icon is displayed in the Scene dock for every node that the script is attached to. For named classes, the icon is also displayed in various editor dialogs. [codeblock] @icon("res://path/to/class/icon.svg") [/codeblock] - [b]Note:[/b] Only the script can have a custom icon. Inner classes are not supported yet. + [b]Note:[/b] Only the script can have a custom icon. Inner classes are not supported. </description> </annotation> <annotation name="@onready"> <return type="void" /> <description> - Mark the following property as assigned on [Node]'s ready state change. Values for these properties are no assigned immediately upon the node's creation, and instead are computed and stored right before [method Node._ready]. + Mark the following property as assigned on [Node]'s ready state change. Values for these properties are not assigned immediately upon the node's creation, and instead are computed and stored right before [method Node._ready]. [codeblock] @onready var character_name: Label = $Label [/codeblock] @@ -588,7 +590,7 @@ <return type="void" /> <param index="0" name="warning" type="String" /> <description> - Mark the following statement to ignore the specified warning. See [url=$DOCS_URL/tutorials/scripting/gdscript/warning_system.html]GDScript warning system[/url]. + Mark the following statement to ignore the specified [param warning]. See [url=$DOCS_URL/tutorials/scripting/gdscript/warning_system.html]GDScript warning system[/url]. [codeblock] func test(): print("hello") diff --git a/modules/gdscript/doc_classes/GDScript.xml b/modules/gdscript/doc_classes/GDScript.xml index 578e7a34f3..8246c96c15 100644 --- a/modules/gdscript/doc_classes/GDScript.xml +++ b/modules/gdscript/doc_classes/GDScript.xml @@ -4,7 +4,7 @@ A script implemented in the GDScript programming language. </brief_description> <description> - A script implemented in the GDScript programming language. The script extends the functionality of all objects that instance it. + A script implemented in the GDScript programming language. The script extends the functionality of all objects that instantiate it. [method new] creates a new instance of the script. [method Object.set_script] extends an existing object, if that object's class matches one of the script's base classes. </description> <tutorials> diff --git a/modules/gdscript/editor/gdscript_highlighter.cpp b/modules/gdscript/editor/gdscript_highlighter.cpp index afb59b486c..420401cb79 100644 --- a/modules/gdscript/editor/gdscript_highlighter.cpp +++ b/modules/gdscript/editor/gdscript_highlighter.cpp @@ -39,30 +39,32 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l Type next_type = NONE; Type current_type = NONE; - Type previous_type = NONE; - - String previous_text = ""; - int previous_column = 0; + Type prev_type = NONE; + String prev_text = ""; + int prev_column = 0; bool prev_is_char = false; bool prev_is_digit = false; bool prev_is_binary_op = false; + bool in_keyword = false; bool in_word = false; bool in_number = false; - bool in_function_name = false; - bool in_lambda = false; - bool in_variable_declaration = false; - bool in_signal_declaration = false; - bool in_function_args = false; - bool in_member_variable = false; bool in_node_path = false; bool in_node_ref = false; bool in_annotation = false; bool in_string_name = false; bool is_hex_notation = false; bool is_bin_notation = false; + bool in_member_variable = false; + bool in_lambda = false; + + bool in_function_name = false; + bool in_function_args = false; + bool in_variable_declaration = false; + bool in_signal_declaration = false; bool expect_type = false; + Color keyword_color; Color color; @@ -224,9 +226,9 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l } } - previous_type = REGION; - previous_text = ""; - previous_column = j; + prev_type = REGION; + prev_text = ""; + prev_column = j; j = from + (end_key_length - 1); if (region_end_index == -1) { color_region_cache[p_line] = in_region; @@ -241,19 +243,22 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l } } - // A bit of a hack, but couldn't come up with anything better. + // VERY hacky... but couldn't come up with anything better. if (j > 0 && (str[j] == '&' || str[j] == '^' || str[j] == '%' || str[j] == '+' || str[j] == '-' || str[j] == '~' || str[j] == '.')) { - if (!keywords.has(previous_text)) { - if (previous_text == "PI" || previous_text == "TAU" || previous_text == "INF" || previous_text == "NAN") { + int to = j - 1; + // Find what the last text was (prev_text won't work if there's no whitespace, so we need to do it manually). + while (to > 0 && is_whitespace(str[to])) { + to--; + } + int from = to; + while (from > 0 && !is_symbol(str[from])) { + from--; + } + String word = str.substr(from + 1, to - from); + // Keywords need to be exceptions, except for keywords that represent a value. + if (word == "true" || word == "false" || word == "null" || word == "PI" || word == "TAU" || word == "INF" || word == "NAN" || word == "self" || word == "super" || !reserved_keywords.has(word)) { + if (!is_symbol(str[to]) || str[to] == '"' || str[to] == '\'' || str[to] == ')' || str[to] == ']' || str[to] == '}') { is_binary_op = true; - } else { - int k = j - 1; - while (k > 0 && is_whitespace(str[k])) { - k--; - } - if (!is_symbol(str[k]) || str[k] == '"' || str[k] == '\'' || str[k] == ')' || str[k] == ']' || str[k] == '}') { - is_binary_op = true; - } } } } @@ -287,16 +292,18 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l is_hex_notation = true; } else if (!((str[j] == '-' || str[j] == '+') && str[j - 1] == 'e' && !prev_is_digit) && !(str[j] == '_' && (prev_is_digit || str[j - 1] == 'b' || str[j - 1] == 'x' || str[j - 1] == '.')) && - !((str[j] == 'e' || str[j] == '.') && (prev_is_digit || str[j - 1] == '_')) && + !(str[j] == 'e' && (prev_is_digit || str[j - 1] == '_')) && + !(str[j] == '.' && (prev_is_digit || (!prev_is_binary_op && (j > 0 && (str[j - 1] == '-' || str[j - 1] == '+' || str[j - 1] == '~'))))) && !((str[j] == '-' || str[j] == '+' || str[j] == '~') && !prev_is_binary_op && str[j - 1] != 'e')) { - /* 1st row of condition: '+' or '-' after scientific notation; - 2nd row of condition: '_' as a numeric separator; - 3rd row of condition: Scientific notation 'e' and floating points; - 4th row of condition: Multiple unary operators. */ + /* This condition continues Number highlighting in special cases. + 1st row: '+' or '-' after scientific notation; + 2nd row: '_' as a numeric separator; + 3rd row: Scientific notation 'e' and floating points; + 4th row: Floating points inside the number, or leading if after a unary mathematical operator; + 5th row: Multiple unary mathematical operators */ in_number = false; } - } else if ((str[j] == '-' || str[j] == '+' || str[j] == '~' || (str[j] == '.' && str[j + 1] != '.' && (j == 0 || (j > 0 && str[j - 1] != '.')))) && !is_binary_op) { - // Start a number from unary mathematical operators and floating points, except for '..' + } else if (!is_binary_op && (str[j] == '-' || str[j] == '+' || str[j] == '~' || (str[j] == '.' && str[j + 1] != '.' && (j == 0 || (j > 0 && str[j - 1] != '.'))))) { in_number = true; } @@ -318,7 +325,7 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l Color col = Color(); if (global_functions.has(word)) { // "assert" and "preload" are reserved, so highlight even if not followed by a bracket. - if (word == "assert" || word == "preload") { + if (word == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::ASSERT) || word == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::PRELOAD)) { col = global_function_color; } else { // For other global functions, check if followed by bracket. @@ -331,8 +338,10 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l col = global_function_color; } } - } else if (keywords.has(word)) { - col = keywords[word]; + } else if (class_names.has(word)) { + col = class_names[word]; + } else if (reserved_keywords.has(word)) { + col = reserved_keywords[word]; } else if (member_keywords.has(word)) { col = member_keywords[word]; } @@ -355,7 +364,7 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l } if (!in_function_name && in_word && !in_keyword) { - if (previous_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::SIGNAL)) { + if (prev_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::SIGNAL)) { in_signal_declaration = true; } else { int k = j; @@ -370,12 +379,12 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l if (str[k] == '(') { in_function_name = true; - } else if (previous_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::VAR)) { + } else if (prev_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::VAR)) { in_variable_declaration = true; } // Check for lambda. - if (in_function_name && previous_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::FUNC)) { + if (in_function_name && prev_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::FUNC)) { k = j - 1; while (k > 0 && is_whitespace(str[k])) { k--; @@ -408,11 +417,11 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l in_function_args = false; } - if (expect_type && (prev_is_char || str[j] == '=')) { + if (expect_type && (prev_is_char || str[j] == '=') && str[j] != '[') { expect_type = false; } - if (j > 0 && str[j] == '>' && str[j - 1] == '-') { + if (j > 0 && str[j - 1] == '-' && str[j] == '>') { expect_type = true; } @@ -491,7 +500,7 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l } else if (in_function_name) { next_type = FUNCTION; - if (!in_lambda && previous_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::FUNC)) { + if (!in_lambda && prev_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::FUNC)) { color = function_definition_color; } else { color = function_color; @@ -513,20 +522,20 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l if (current_type == NONE) { current_type = next_type; } else { - previous_type = current_type; + prev_type = current_type; current_type = next_type; // no need to store regions... - if (previous_type == REGION) { - previous_text = ""; - previous_column = j; + if (prev_type == REGION) { + prev_text = ""; + prev_column = j; } else { - String text = str.substr(previous_column, j - previous_column).strip_edges(); - previous_column = j; + String text = str.substr(prev_column, j - prev_column).strip_edges(); + prev_column = j; // ignore if just whitespace if (!text.is_empty()) { - previous_text = text; + prev_text = text; } } } @@ -556,7 +565,8 @@ PackedStringArray GDScriptSyntaxHighlighter::_get_supported_languages() const { } void GDScriptSyntaxHighlighter::_update_cache() { - keywords.clear(); + class_names.clear(); + reserved_keywords.clear(); member_keywords.clear(); global_functions.clear(); color_regions.clear(); @@ -573,7 +583,7 @@ void GDScriptSyntaxHighlighter::_update_cache() { List<StringName> types; ClassDB::get_class_list(&types); for (const StringName &E : types) { - keywords[E] = types_color; + class_names[E] = types_color; } /* User types. */ @@ -581,14 +591,14 @@ void GDScriptSyntaxHighlighter::_update_cache() { List<StringName> global_classes; ScriptServer::get_global_class_list(&global_classes); for (const StringName &E : global_classes) { - keywords[E] = usertype_color; + class_names[E] = usertype_color; } /* Autoloads. */ for (const KeyValue<StringName, ProjectSettings::AutoloadInfo> &E : ProjectSettings::get_singleton()->get_autoload_list()) { const ProjectSettings::AutoloadInfo &info = E.value; if (info.is_singleton) { - keywords[info.name] = usertype_color; + class_names[info.name] = usertype_color; } } @@ -599,7 +609,7 @@ void GDScriptSyntaxHighlighter::_update_cache() { List<String> core_types; gdscript->get_core_type_words(&core_types); for (const String &E : core_types) { - keywords[StringName(E)] = basetype_color; + class_names[StringName(E)] = basetype_color; } /* Reserved words. */ @@ -609,9 +619,9 @@ void GDScriptSyntaxHighlighter::_update_cache() { gdscript->get_reserved_words(&keyword_list); for (const String &E : keyword_list) { if (gdscript->is_control_flow_keyword(E)) { - keywords[StringName(E)] = control_flow_keyword_color; + reserved_keywords[StringName(E)] = control_flow_keyword_color; } else { - keywords[StringName(E)] = keyword_color; + reserved_keywords[StringName(E)] = keyword_color; } } @@ -646,23 +656,23 @@ void GDScriptSyntaxHighlighter::_update_cache() { add_color_region(beg, end, string_color, end.is_empty()); } - const Ref<Script> script = _get_edited_resource(); - if (script.is_valid()) { + const Ref<Script> scr = _get_edited_resource(); + if (scr.is_valid()) { /* Member types. */ const Color member_variable_color = EDITOR_GET("text_editor/theme/highlighting/member_variable_color"); - StringName instance_base = script->get_instance_base_type(); + StringName instance_base = scr->get_instance_base_type(); if (instance_base != StringName()) { List<PropertyInfo> plist; ClassDB::get_property_list(instance_base, &plist); for (const PropertyInfo &E : plist) { - String name = E.name; + String prop_name = E.name; if (E.usage & PROPERTY_USAGE_CATEGORY || E.usage & PROPERTY_USAGE_GROUP || E.usage & PROPERTY_USAGE_SUBGROUP) { continue; } - if (name.contains("/")) { + if (prop_name.contains("/")) { continue; } - member_keywords[name] = member_variable_color; + member_keywords[prop_name] = member_variable_color; } List<String> clist; @@ -673,7 +683,7 @@ void GDScriptSyntaxHighlighter::_update_cache() { } } - const String text_edit_color_theme = EditorSettings::get_singleton()->get("text_editor/theme/color_theme"); + const String text_edit_color_theme = EDITOR_GET("text_editor/theme/color_theme"); const bool godot_2_theme = text_edit_color_theme == "Godot 2"; if (godot_2_theme || EditorSettings::get_singleton()->is_dark_theme()) { diff --git a/modules/gdscript/editor/gdscript_highlighter.h b/modules/gdscript/editor/gdscript_highlighter.h index 60b5b092d4..7c22eb30b1 100644 --- a/modules/gdscript/editor/gdscript_highlighter.h +++ b/modules/gdscript/editor/gdscript_highlighter.h @@ -47,7 +47,8 @@ private: Vector<ColorRegion> color_regions; HashMap<int, int> color_region_cache; - HashMap<StringName, Color> keywords; + HashMap<StringName, Color> class_names; + HashMap<StringName, Color> reserved_keywords; HashMap<StringName, Color> member_keywords; HashSet<StringName> global_functions; diff --git a/modules/gdscript/gdscript.cpp b/modules/gdscript/gdscript.cpp index 1cff2181af..bd6cef0b6e 100644 --- a/modules/gdscript/gdscript.cpp +++ b/modules/gdscript/gdscript.cpp @@ -111,9 +111,9 @@ GDScriptFunction *GDScript::_super_constructor(GDScript *p_script) { if (p_script->initializer) { return p_script->initializer; } else { - GDScript *base = p_script->_base; - if (base != nullptr) { - return _super_constructor(base); + GDScript *base_src = p_script->_base; + if (base_src != nullptr) { + return _super_constructor(base_src); } else { return nullptr; } @@ -121,9 +121,9 @@ GDScriptFunction *GDScript::_super_constructor(GDScript *p_script) { } void GDScript::_super_implicit_constructor(GDScript *p_script, GDScriptInstance *p_instance, Callable::CallError &r_error) { - GDScript *base = p_script->_base; - if (base != nullptr) { - _super_implicit_constructor(base, p_instance, r_error); + GDScript *base_src = p_script->_base; + if (base_src != nullptr) { + _super_implicit_constructor(base_src, p_instance, r_error); if (r_error.error != Callable::CallError::CALL_OK) { return; } @@ -151,7 +151,7 @@ GDScriptInstance *GDScript::_create_instance(const Variant **p_args, int p_argco /* STEP 2, INITIALIZE AND CONSTRUCT */ { - MutexLock lock(GDScriptLanguage::singleton->lock); + MutexLock lock(GDScriptLanguage::singleton->mutex); instances.insert(instance->owner); } @@ -160,7 +160,7 @@ GDScriptInstance *GDScript::_create_instance(const Variant **p_args, int p_argco instance->script = Ref<GDScript>(); instance->owner->set_script_instance(nullptr); { - MutexLock lock(GDScriptLanguage::singleton->lock); + MutexLock lock(GDScriptLanguage::singleton->mutex); instances.erase(p_owner); } ERR_FAIL_V_MSG(nullptr, "Error constructing a GDScriptInstance."); @@ -177,7 +177,7 @@ GDScriptInstance *GDScript::_create_instance(const Variant **p_args, int p_argco instance->script = Ref<GDScript>(); instance->owner->set_script_instance(nullptr); { - MutexLock lock(GDScriptLanguage::singleton->lock); + MutexLock lock(GDScriptLanguage::singleton->mutex); instances.erase(p_owner); } ERR_FAIL_V_MSG(nullptr, "Error constructing a GDScriptInstance."); @@ -396,9 +396,9 @@ ScriptInstance *GDScript::instance_create(Object *p_this) { if (top->native.is_valid()) { if (!ClassDB::is_parent_class(p_this->get_class_name(), top->native->get_name())) { if (EngineDebugger::is_active()) { - GDScriptLanguage::get_singleton()->debug_break_parse(_get_debug_path(), 1, "Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be instantiated in object of type: '" + p_this->get_class() + "'"); + GDScriptLanguage::get_singleton()->debug_break_parse(_get_debug_path(), 1, "Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be assigned to an object of type: '" + p_this->get_class() + "'"); } - ERR_FAIL_V_MSG(nullptr, "Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be instantiated in object of type '" + p_this->get_class() + "'" + "."); + ERR_FAIL_V_MSG(nullptr, "Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be assigned to an object of type '" + p_this->get_class() + "'" + "."); } } @@ -418,7 +418,7 @@ PlaceHolderScriptInstance *GDScript::placeholder_instance_create(Object *p_this) } bool GDScript::instance_has(const Object *p_this) const { - MutexLock lock(GDScriptLanguage::singleton->lock); + MutexLock lock(GDScriptLanguage::singleton->mutex); return instances.has((Object *)p_this); } @@ -620,19 +620,15 @@ void GDScript::_update_doc() { } if (!is_enum) { DocData::ConstantDoc constant_doc; - String doc_description; + String const_description; if (doc_constants.has(E.key)) { - doc_description = doc_constants[E.key]; + const_description = doc_constants[E.key]; } - DocData::constant_doc_from_variant(constant_doc, E.key, E.value, doc_description); + DocData::constant_doc_from_variant(constant_doc, E.key, E.value, const_description); doc.constants.push_back(constant_doc); } } - for (KeyValue<StringName, Ref<GDScript>> &E : subclasses) { - E.value->_update_doc(); - } - _add_doc(doc); } #endif @@ -674,36 +670,14 @@ bool GDScript::_update_exports(bool *r_err, bool p_recursive_call, PlaceHolderSc base_cache = Ref<GDScript>(); } - if (c->extends_used) { - String path = ""; - if (String(c->extends_path) != "" && String(c->extends_path) != get_path()) { - path = c->extends_path; - if (path.is_relative_path()) { - String base = get_path(); - if (base.is_empty() || base.is_relative_path()) { - ERR_PRINT(("Could not resolve relative path for parent class: " + path).utf8().get_data()); - } else { - path = base.get_base_dir().path_join(path); - } - } - } else if (c->extends.size() != 0) { - const StringName &base = c->extends[0]; - - if (ScriptServer::is_global_class(base)) { - path = ScriptServer::get_global_class_path(base); - } - } - - if (!path.is_empty()) { - if (path != get_path()) { - Ref<GDScript> bf = ResourceLoader::load(path); - - if (bf.is_valid()) { - base_cache = bf; - bf->inheriters_cache.insert(get_instance_id()); - } - } else { - ERR_PRINT(("Path extending itself in " + path).utf8().get_data()); + GDScriptParser::DataType base_type = parser.get_tree()->base_type; + if (base_type.kind == GDScriptParser::DataType::CLASS) { + Ref<GDScript> bf = GDScriptCache::get_full_script(base_type.script_path, err, path); + if (err == OK) { + bf = Ref<GDScript>(bf->find_class(base_type.class_type->fqcn)); + if (bf.is_valid()) { + base_cache = bf; + bf->inheriters_cache.insert(get_instance_id()); } } } @@ -825,13 +799,6 @@ void GDScript::update_exports() { #endif } -void GDScript::_set_subclass_path(Ref<GDScript> &p_sc, const String &p_path) { - p_sc->path = p_path; - for (KeyValue<StringName, Ref<GDScript>> &E : p_sc->subclasses) { - _set_subclass_path(E.value, p_path); - } -} - String GDScript::_get_debug_path() const { if (is_built_in() && !get_name().is_empty()) { return get_name() + " (" + get_path() + ")"; @@ -843,7 +810,7 @@ String GDScript::_get_debug_path() const { Error GDScript::reload(bool p_keep_state) { bool has_instances; { - MutexLock lock(GDScriptLanguage::singleton->lock); + MutexLock lock(GDScriptLanguage::singleton->mutex); has_instances = instances.size(); } @@ -860,7 +827,7 @@ Error GDScript::reload(bool p_keep_state) { basedir = basedir.get_base_dir(); } -// Loading a template, don't parse. + // Loading a template, don't parse. #ifdef TOOLS_ENABLED if (EditorPaths::get_singleton() && basedir.begins_with(EditorPaths::get_singleton()->get_project_script_templates_dir())) { return OK; @@ -913,10 +880,6 @@ Error GDScript::reload(bool p_keep_state) { GDScriptCompiler compiler; err = compiler.compile(&parser, this, p_keep_state); -#ifdef TOOLS_ENABLED - _update_doc(); -#endif - if (err) { if (can_run) { if (EngineDebugger::is_active()) { @@ -937,14 +900,6 @@ Error GDScript::reload(bool p_keep_state) { } #endif - valid = true; - - for (KeyValue<StringName, Ref<GDScript>> &E : subclasses) { - _set_subclass_path(E.value, path); - } - - _init_rpc_methods_properties(); - return OK; } @@ -1050,6 +1005,16 @@ Error GDScript::load_byte_code(const String &p_path) { return ERR_COMPILATION_FAILED; } +void GDScript::set_path(const String &p_path, bool p_take_over) { + if (is_root_script()) { + Script::set_path(p_path, p_take_over); + } + this->path = p_path; + for (KeyValue<StringName, Ref<GDScript>> &kv : subclasses) { + kv.value->set_path(p_path, p_take_over); + } +} + Error GDScript::load_source_code(const String &p_path) { Vector<uint8_t> sourcef; Error err; @@ -1122,6 +1087,52 @@ bool GDScript::inherits_script(const Ref<Script> &p_script) const { return false; } +GDScript *GDScript::find_class(const String &p_qualified_name) { + String first = p_qualified_name.get_slice("::", 0); + + GDScript *result = nullptr; + if (first.is_empty() || first == name) { + result = this; + } else if (first == get_root_script()->path) { + result = get_root_script(); + } else if (HashMap<StringName, Ref<GDScript>>::Iterator E = subclasses.find(first)) { + result = E->value.ptr(); + } else if (_owner != nullptr) { + // Check parent scope. + return _owner->find_class(p_qualified_name); + } + + int name_count = p_qualified_name.get_slice_count("::"); + for (int i = 1; result != nullptr && i < name_count; i++) { + String current_name = p_qualified_name.get_slice("::", i); + if (HashMap<StringName, Ref<GDScript>>::Iterator E = result->subclasses.find(current_name)) { + result = E->value.ptr(); + } else { + // Couldn't find inner class. + return nullptr; + } + } + + return result; +} + +bool GDScript::is_subclass(const GDScript *p_script) { + String fqn = p_script->fully_qualified_name; + if (!fqn.is_empty() && fqn != fully_qualified_name && fqn.begins_with(fully_qualified_name)) { + String fqn_rest = fqn.substr(fully_qualified_name.length()); + return find_class(fqn_rest) == p_script; + } + return false; +} + +GDScript *GDScript::get_root_script() { + GDScript *result = this; + while (result->_owner) { + result = result->_owner; + } + return result; +} + bool GDScript::has_script_signal(const StringName &p_signal) const { if (_signals.has(p_signal)) { return true; @@ -1187,7 +1198,7 @@ GDScript::GDScript() : script_list(this) { #ifdef DEBUG_ENABLED { - MutexLock lock(GDScriptLanguage::get_singleton()->lock); + MutexLock lock(GDScriptLanguage::get_singleton()->mutex); GDScriptLanguage::get_singleton()->script_list.add(&script_list); } @@ -1233,32 +1244,18 @@ void GDScript::_init_rpc_methods_properties() { rpc_config = base->rpc_config.duplicate(); } - GDScript *cscript = this; - HashMap<StringName, Ref<GDScript>>::Iterator sub_E = subclasses.begin(); - while (cscript) { - // RPC Methods - for (KeyValue<StringName, GDScriptFunction *> &E : cscript->member_functions) { - Variant config = E.value->get_rpc_config(); - if (config.get_type() != Variant::NIL) { - rpc_config[E.value->get_name()] = config; - } - } - - if (cscript != this) { - ++sub_E; - } - - if (sub_E) { - cscript = sub_E->value.ptr(); - } else { - cscript = nullptr; + // RPC Methods + for (KeyValue<StringName, GDScriptFunction *> &E : member_functions) { + Variant config = E.value->get_rpc_config(); + if (config.get_type() != Variant::NIL) { + rpc_config[E.value->get_name()] = config; } } } GDScript::~GDScript() { { - MutexLock lock(GDScriptLanguage::get_singleton()->lock); + MutexLock lock(GDScriptLanguage::get_singleton()->mutex); while (SelfList<GDScriptFunctionState> *E = pending_func_states.first()) { // Order matters since clearing the stack may already cause @@ -1295,7 +1292,7 @@ GDScript::~GDScript() { #ifdef DEBUG_ENABLED { - MutexLock lock(GDScriptLanguage::get_singleton()->lock); + MutexLock lock(GDScriptLanguage::get_singleton()->mutex); GDScriptLanguage::get_singleton()->script_list.remove(&script_list); } @@ -1722,7 +1719,7 @@ GDScriptInstance::GDScriptInstance() { } GDScriptInstance::~GDScriptInstance() { - MutexLock lock(GDScriptLanguage::get_singleton()->lock); + MutexLock lock(GDScriptLanguage::get_singleton()->mutex); while (SelfList<GDScriptFunctionState> *E = pending_func_states.first()) { // Order matters since clearing the stack may already cause @@ -1825,7 +1822,7 @@ void GDScriptLanguage::finish() { void GDScriptLanguage::profiling_start() { #ifdef DEBUG_ENABLED - MutexLock lock(this->lock); + MutexLock lock(this->mutex); SelfList<GDScriptFunction> *elem = function_list.first(); while (elem) { @@ -1847,7 +1844,7 @@ void GDScriptLanguage::profiling_start() { void GDScriptLanguage::profiling_stop() { #ifdef DEBUG_ENABLED - MutexLock lock(this->lock); + MutexLock lock(this->mutex); profiling = false; #endif @@ -1857,7 +1854,7 @@ int GDScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int current = 0; #ifdef DEBUG_ENABLED - MutexLock lock(this->lock); + MutexLock lock(this->mutex); SelfList<GDScriptFunction> *elem = function_list.first(); while (elem) { @@ -1880,7 +1877,7 @@ int GDScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_ int current = 0; #ifdef DEBUG_ENABLED - MutexLock lock(this->lock); + MutexLock lock(this->mutex); SelfList<GDScriptFunction> *elem = function_list.first(); while (elem) { @@ -1926,7 +1923,7 @@ void GDScriptLanguage::reload_all_scripts() { print_verbose("GDScript: Reloading all scripts"); List<Ref<GDScript>> scripts; { - MutexLock lock(this->lock); + MutexLock lock(this->mutex); SelfList<GDScript> *elem = script_list.first(); while (elem) { @@ -1942,10 +1939,10 @@ void GDScriptLanguage::reload_all_scripts() { scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order - for (Ref<GDScript> &script : scripts) { - print_verbose("GDScript: Reloading: " + script->get_path()); - script->load_source_code(script->get_path()); - script->reload(true); + for (Ref<GDScript> &scr : scripts) { + print_verbose("GDScript: Reloading: " + scr->get_path()); + scr->load_source_code(scr->get_path()); + scr->reload(true); } #endif } @@ -1955,7 +1952,7 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_so List<Ref<GDScript>> scripts; { - MutexLock lock(this->lock); + MutexLock lock(this->mutex); SelfList<GDScript> *elem = script_list.first(); while (elem) { @@ -1974,21 +1971,21 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_so scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order - for (Ref<GDScript> &script : scripts) { - bool reload = script == p_script || to_reload.has(script->get_base()); + for (Ref<GDScript> &scr : scripts) { + bool reload = scr == p_script || to_reload.has(scr->get_base()); if (!reload) { continue; } - to_reload.insert(script, HashMap<ObjectID, List<Pair<StringName, Variant>>>()); + to_reload.insert(scr, HashMap<ObjectID, List<Pair<StringName, Variant>>>()); if (!p_soft_reload) { //save state and remove script from instances - HashMap<ObjectID, List<Pair<StringName, Variant>>> &map = to_reload[script]; + HashMap<ObjectID, List<Pair<StringName, Variant>>> &map = to_reload[scr]; - while (script->instances.front()) { - Object *obj = script->instances.front()->get(); + while (scr->instances.front()) { + Object *obj = scr->instances.front()->get(); //save instance info List<Pair<StringName, Variant>> state; if (obj->get_script_instance()) { @@ -2001,8 +1998,8 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_so //same thing for placeholders #ifdef TOOLS_ENABLED - while (script->placeholders.size()) { - Object *obj = (*script->placeholders.begin())->get_owner(); + while (scr->placeholders.size()) { + Object *obj = (*scr->placeholders.begin())->get_owner(); //save instance info if (obj->get_script_instance()) { @@ -2012,13 +2009,13 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_so obj->set_script(Variant()); } else { // no instance found. Let's remove it so we don't loop forever - script->placeholders.erase(*script->placeholders.begin()); + scr->placeholders.erase(*scr->placeholders.begin()); } } #endif - for (const KeyValue<ObjectID, List<Pair<StringName, Variant>>> &F : script->pending_reload_state) { + for (const KeyValue<ObjectID, List<Pair<StringName, Variant>>> &F : scr->pending_reload_state) { map[F.key] = F.value; //pending to reload, use this one instead } } @@ -2043,9 +2040,9 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_so } obj->set_script(scr); - ScriptInstance *script_instance = obj->get_script_instance(); + ScriptInstance *script_inst = obj->get_script_instance(); - if (!script_instance) { + if (!script_inst) { //failed, save reload state for next time if not saved if (!scr->pending_reload_state.has(obj->get_instance_id())) { scr->pending_reload_state[obj->get_instance_id()] = saved_state; @@ -2053,14 +2050,14 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_so continue; } - if (script_instance->is_placeholder() && scr->is_placeholder_fallback_enabled()) { - PlaceHolderScriptInstance *placeholder = static_cast<PlaceHolderScriptInstance *>(script_instance); + if (script_inst->is_placeholder() && scr->is_placeholder_fallback_enabled()) { + PlaceHolderScriptInstance *placeholder = static_cast<PlaceHolderScriptInstance *>(script_inst); for (List<Pair<StringName, Variant>>::Element *G = saved_state.front(); G; G = G->next()) { placeholder->property_set_fallback(G->get().first, G->get().second); } } else { for (List<Pair<StringName, Variant>>::Element *G = saved_state.front(); G; G = G->next()) { - script_instance->set(G->get().first, G->get().second); + script_inst->set(G->get().first, G->get().second); } } @@ -2078,7 +2075,7 @@ void GDScriptLanguage::frame() { #ifdef DEBUG_ENABLED if (profiling) { - MutexLock lock(this->lock); + MutexLock lock(this->mutex); SelfList<GDScriptFunction> *elem = function_list.first(); while (elem) { @@ -2339,26 +2336,26 @@ GDScriptLanguage::~GDScriptLanguage() { // Clear dependencies between scripts, to ensure cyclic references are broken (to avoid leaks at exit). SelfList<GDScript> *s = script_list.first(); while (s) { - GDScript *script = s->self(); + GDScript *scr = s->self(); // This ensures the current script is not released before we can check what's the next one // in the list (we can't get the next upfront because we don't know if the reference breaking // will cause it -or any other after it, for that matter- to be released so the next one // is not the same as before). - script->reference(); + scr->reference(); - for (KeyValue<StringName, GDScriptFunction *> &E : script->member_functions) { + for (KeyValue<StringName, GDScriptFunction *> &E : scr->member_functions) { GDScriptFunction *func = E.value; for (int i = 0; i < func->argument_types.size(); i++) { func->argument_types.write[i].script_type_ref = Ref<Script>(); } func->return_type.script_type_ref = Ref<Script>(); } - for (KeyValue<StringName, GDScript::MemberInfo> &E : script->member_indices) { + for (KeyValue<StringName, GDScript::MemberInfo> &E : scr->member_indices) { E.value.data_type.script_type_ref = Ref<Script>(); } s = s->next(); - script->unreference(); + scr->unreference(); } singleton = nullptr; @@ -2390,20 +2387,20 @@ Ref<Resource> ResourceFormatLoaderGDScript::load(const String &p_path, const Str } Error err; - Ref<GDScript> script = GDScriptCache::get_full_script(p_path, err); + Ref<GDScript> scr = GDScriptCache::get_full_script(p_path, err, "", p_cache_mode == CACHE_MODE_IGNORE); // TODO: Reintroduce binary and encrypted scripts. - if (script.is_null()) { + if (scr.is_null()) { // Don't fail loading because of parsing error. - script.instantiate(); + scr.instantiate(); } if (r_error) { *r_error = OK; } - return script; + return scr; } void ResourceFormatLoaderGDScript::get_recognized_extensions(List<String> *p_extensions) const { diff --git a/modules/gdscript/gdscript.h b/modules/gdscript/gdscript.h index e4b12d4ddb..61600b1258 100644 --- a/modules/gdscript/gdscript.h +++ b/modules/gdscript/gdscript.h @@ -137,7 +137,6 @@ class GDScript : public Script { void _super_implicit_constructor(GDScript *p_script, GDScriptInstance *p_instance, Callable::CallError &r_error); GDScriptInstance *_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_is_ref_counted, Callable::CallError &r_error); - void _set_subclass_path(Ref<GDScript> &p_sc, const String &p_path); String _get_debug_path() const; #ifdef TOOLS_ENABLED @@ -178,6 +177,11 @@ public: bool inherits_script(const Ref<Script> &p_script) const override; + GDScript *find_class(const String &p_qualified_name); + bool is_subclass(const GDScript *p_script); + GDScript *get_root_script(); + bool is_root_script() const { return _owner == nullptr; } + String get_fully_qualified_name() const { return fully_qualified_name; } const HashMap<StringName, Ref<GDScript>> &get_subclasses() const { return subclasses; } const HashMap<StringName, Variant> &get_constants() const { return constants; } const HashSet<StringName> &get_members() const { return members; } @@ -222,7 +226,7 @@ public: virtual Error reload(bool p_keep_state = false) override; - void set_script_path(const String &p_path) { path = p_path; } //because subclasses need a path too... + virtual void set_path(const String &p_path, bool p_take_over = false) override; Error load_source_code(const String &p_path); Error load_byte_code(const String &p_path); @@ -342,7 +346,7 @@ class GDScriptLanguage : public ScriptLanguage { friend class GDScriptInstance; - Mutex lock; + Mutex mutex; friend class GDScript; diff --git a/modules/gdscript/gdscript_analyzer.cpp b/modules/gdscript/gdscript_analyzer.cpp index e37ac1dc3b..8da77b9e5b 100644 --- a/modules/gdscript/gdscript_analyzer.cpp +++ b/modules/gdscript/gdscript_analyzer.cpp @@ -213,16 +213,6 @@ Error GDScriptAnalyzer::resolve_inheritance(GDScriptParser::ClassNode *p_class, return OK; } - if (p_class == parser->head) { - if (p_class->identifier) { - p_class->fqcn = p_class->identifier->name; - } else { - p_class->fqcn = parser->script_path; - } - } else { - p_class->fqcn = p_class->outer->fqcn + "::" + String(p_class->identifier->name); - } - if (p_class->identifier) { StringName class_name = p_class->identifier->name; if (class_exists(class_name)) { @@ -262,19 +252,19 @@ Error GDScriptAnalyzer::resolve_inheritance(GDScriptParser::ClassNode *p_class, if (p_class->extends_path.is_relative_path()) { p_class->extends_path = class_type.script_path.get_base_dir().path_join(p_class->extends_path).simplify_path(); } - Ref<GDScriptParserRef> parser = get_parser_for(p_class->extends_path); - if (parser.is_null()) { + Ref<GDScriptParserRef> ext_parser = get_parser_for(p_class->extends_path); + if (ext_parser.is_null()) { push_error(vformat(R"(Could not resolve super class path "%s".)", p_class->extends_path), p_class); return ERR_PARSE_ERROR; } - Error err = parser->raise_status(GDScriptParserRef::INTERFACE_SOLVED); + Error err = ext_parser->raise_status(GDScriptParserRef::INTERFACE_SOLVED); if (err != OK) { push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", p_class->extends_path), p_class); return err; } - base = parser->get_parser()->head->get_datatype(); + base = ext_parser->get_parser()->head->get_datatype(); } else { if (p_class->extends.is_empty()) { push_error("Could not resolve an empty super class path.", p_class); @@ -289,18 +279,18 @@ Error GDScriptAnalyzer::resolve_inheritance(GDScriptParser::ClassNode *p_class, if (base_path == parser->script_path) { base = parser->head->get_datatype(); } else { - Ref<GDScriptParserRef> parser = get_parser_for(base_path); - if (parser.is_null()) { + Ref<GDScriptParserRef> base_parser = get_parser_for(base_path); + if (base_parser.is_null()) { push_error(vformat(R"(Could not resolve super class "%s".)", name), p_class); return ERR_PARSE_ERROR; } - Error err = parser->raise_status(GDScriptParserRef::INTERFACE_SOLVED); + Error err = base_parser->raise_status(GDScriptParserRef::INTERFACE_SOLVED); if (err != OK) { push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), p_class); return err; } - base = parser->get_parser()->head->get_datatype(); + base = base_parser->get_parser()->head->get_datatype(); } } else if (ProjectSettings::get_singleton()->has_autoload(name) && ProjectSettings::get_singleton()->get_autoload(name).is_singleton) { const ProjectSettings::AutoloadInfo &info = ProjectSettings::get_singleton()->get_autoload(name); @@ -309,13 +299,13 @@ Error GDScriptAnalyzer::resolve_inheritance(GDScriptParser::ClassNode *p_class, return ERR_PARSE_ERROR; } - Ref<GDScriptParserRef> parser = get_parser_for(info.path); - if (parser.is_null()) { + Ref<GDScriptParserRef> info_parser = get_parser_for(info.path); + if (info_parser.is_null()) { push_error(vformat(R"(Could not parse singleton from "%s".)", info.path), p_class); return ERR_PARSE_ERROR; } - Error err = parser->raise_status(GDScriptParserRef::INTERFACE_SOLVED); + Error err = info_parser->raise_status(GDScriptParserRef::INTERFACE_SOLVED); if (err != OK) { push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), p_class); return err; @@ -484,12 +474,23 @@ GDScriptParser::DataType GDScriptAnalyzer::resolve_datatype(GDScriptParser::Type if (parser->script_path == ScriptServer::get_global_class_path(first)) { result = parser->head->get_datatype(); } else { - Ref<GDScriptParserRef> ref = get_parser_for(ScriptServer::get_global_class_path(first)); - if (!ref.is_valid() || ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED) != OK) { - push_error(vformat(R"(Could not parse global class "%s" from "%s".)", first, ScriptServer::get_global_class_path(first)), p_type); - return GDScriptParser::DataType(); + String path = ScriptServer::get_global_class_path(first); + String ext = path.get_extension(); + if (ext == GDScriptLanguage::get_singleton()->get_extension()) { + Ref<GDScriptParserRef> ref = get_parser_for(path); + if (!ref.is_valid() || ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED) != OK) { + push_error(vformat(R"(Could not parse global class "%s" from "%s".)", first, ScriptServer::get_global_class_path(first)), p_type); + return GDScriptParser::DataType(); + } + result = ref->get_parser()->head->get_datatype(); + } else { + result.kind = GDScriptParser::DataType::SCRIPT; + result.native_type = ScriptServer::get_global_class_native_base(first); + result.script_type = ResourceLoader::load(path, "Script"); + result.script_path = path; + result.is_constant = true; + result.is_meta_type = false; } - result = ref->get_parser()->head->get_datatype(); } } else if (ProjectSettings::get_singleton()->has_autoload(first) && ProjectSettings::get_singleton()->get_autoload(first).is_singleton) { const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(first); @@ -540,12 +541,13 @@ GDScriptParser::DataType GDScriptAnalyzer::resolve_datatype(GDScriptParser::Type result = ref->get_parser()->head->get_datatype(); result.is_meta_type = false; } else { - Ref<GDScript> script = member.constant->initializer->reduced_value; + Ref<Script> script = member.constant->initializer->reduced_value; result.kind = GDScriptParser::DataType::SCRIPT; result.builtin_type = Variant::OBJECT; result.script_type = script; result.script_path = script->get_path(); result.native_type = script->get_instance_base_type(); + result.is_meta_type = false; } break; } @@ -973,21 +975,26 @@ void GDScriptAnalyzer::resolve_class_body(GDScriptParser::ClassNode *p_class) { if (getter_function == nullptr) { push_error(vformat(R"(Getter "%s" not found.)", member.variable->getter_pointer->name), member.variable); - - } else if (getter_function->parameters.size() != 0 || getter_function->datatype.has_no_type()) { - push_error(vformat(R"(Function "%s" cannot be used as getter because of its signature.)", getter_function->identifier->name), member.variable); - - } else if (!is_type_compatible(member.variable->datatype, getter_function->datatype, true)) { - push_error(vformat(R"(Function with return type "%s" cannot be used as getter for a property of type "%s".)", getter_function->datatype.to_string(), member.variable->datatype.to_string()), member.variable); - } else { - has_valid_getter = true; + GDScriptParser::DataType return_datatype = getter_function->datatype; + if (getter_function->return_type != nullptr) { + return_datatype = getter_function->return_type->datatype; + return_datatype.is_meta_type = false; + } + if (getter_function->parameters.size() != 0 || return_datatype.has_no_type()) { + push_error(vformat(R"(Function "%s" cannot be used as getter because of its signature.)", getter_function->identifier->name), member.variable); + } else if (!is_type_compatible(member.variable->datatype, return_datatype, true)) { + push_error(vformat(R"(Function with return type "%s" cannot be used as getter for a property of type "%s".)", return_datatype.to_string(), member.variable->datatype.to_string()), member.variable); + + } else { + has_valid_getter = true; #ifdef DEBUG_ENABLED - if (member.variable->datatype.builtin_type == Variant::INT && getter_function->datatype.builtin_type == Variant::FLOAT) { - parser->push_warning(member.variable, GDScriptWarning::NARROWING_CONVERSION); - } + if (member.variable->datatype.builtin_type == Variant::INT && return_datatype.builtin_type == Variant::FLOAT) { + parser->push_warning(member.variable, GDScriptWarning::NARROWING_CONVERSION); + } #endif + } } } @@ -1029,7 +1036,7 @@ void GDScriptAnalyzer::resolve_class_body(GDScriptParser::ClassNode *p_class) { } } -void GDScriptAnalyzer::resolve_node(GDScriptParser::Node *p_node) { +void GDScriptAnalyzer::resolve_node(GDScriptParser::Node *p_node, bool p_is_root) { ERR_FAIL_COND_MSG(p_node == nullptr, "Trying to resolve type of a null node."); switch (p_node->type) { @@ -1102,7 +1109,7 @@ void GDScriptAnalyzer::resolve_node(GDScriptParser::Node *p_node) { case GDScriptParser::Node::SUBSCRIPT: case GDScriptParser::Node::TERNARY_OPERATOR: case GDScriptParser::Node::UNARY_OPERATOR: - reduce_expression(static_cast<GDScriptParser::ExpressionNode *>(p_node), true); + reduce_expression(static_cast<GDScriptParser::ExpressionNode *>(p_node), p_is_root); break; case GDScriptParser::Node::BREAK: case GDScriptParser::Node::BREAKPOINT: @@ -1365,7 +1372,7 @@ void GDScriptAnalyzer::resolve_for(GDScriptParser::ForNode *p_for) { if (all_is_constant) { switch (args.size()) { case 1: - reduced = args[0]; + reduced = (int32_t)args[0]; break; case 2: reduced = Vector2i(args[0], args[1]); @@ -1399,7 +1406,7 @@ void GDScriptAnalyzer::resolve_for(GDScriptParser::ForNode *p_for) { variable_type.builtin_type = Variant::INT; // Can this ever be a float or something else? p_for->variable->set_datatype(variable_type); } else if (p_for->list) { - resolve_node(p_for->list); + resolve_node(p_for->list, false); if (p_for->list->datatype.has_container_element_type()) { variable_type = p_for->list->datatype.get_container_element_type(); variable_type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED; @@ -1427,7 +1434,7 @@ void GDScriptAnalyzer::resolve_for(GDScriptParser::ForNode *p_for) { } void GDScriptAnalyzer::resolve_while(GDScriptParser::WhileNode *p_while) { - resolve_node(p_while->condition); + resolve_node(p_while->condition, false); resolve_suite(p_while->loop); p_while->set_datatype(p_while->loop->get_datatype()); @@ -1590,8 +1597,8 @@ void GDScriptAnalyzer::resolve_assert(GDScriptParser::AssertNode *p_assert) { reduce_expression(p_assert->condition); if (p_assert->message != nullptr) { reduce_expression(p_assert->message); - if (!p_assert->message->is_constant || p_assert->message->reduced_value.get_type() != Variant::STRING) { - push_error(R"(Expected constant string for assert error message.)", p_assert->message); + if (!p_assert->message->get_datatype().has_no_type() && (p_assert->message->get_datatype().kind != GDScriptParser::DataType::BUILTIN || p_assert->message->get_datatype().builtin_type != Variant::STRING)) { + push_error(R"(Expected string for assert error message.)", p_assert->message); } } @@ -1812,7 +1819,7 @@ void GDScriptAnalyzer::reduce_expression(GDScriptParser::ExpressionNode *p_expre reduce_binary_op(static_cast<GDScriptParser::BinaryOpNode *>(p_expression)); break; case GDScriptParser::Node::CALL: - reduce_call(static_cast<GDScriptParser::CallNode *>(p_expression), p_is_root); + reduce_call(static_cast<GDScriptParser::CallNode *>(p_expression), false, p_is_root); break; case GDScriptParser::Node::CAST: reduce_cast(static_cast<GDScriptParser::CastNode *>(p_expression)); @@ -2413,9 +2420,15 @@ void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool p_is_a switch (err.error) { case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT: { - PropertyInfo wrong_arg = function_info.arguments[err.argument]; + String expected_type_name; + if (err.argument < function_info.arguments.size()) { + expected_type_name = type_from_property(function_info.arguments[err.argument]).to_string(); + } else { + expected_type_name = Variant::get_type_name((Variant::Type)err.expected); + } + push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be %s but is %s.)*", function_name, err.argument + 1, - type_from_property(wrong_arg).to_string(), p_call->arguments[err.argument]->get_datatype().to_string()), + expected_type_name, p_call->arguments[err.argument]->get_datatype().to_string()), p_call->arguments[err.argument]); } break; case Callable::CallError::CALL_ERROR_INVALID_METHOD: @@ -2536,6 +2549,16 @@ void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool p_is_a mark_lambda_use_self(); } +#ifdef DEBUG_ENABLED + if (p_is_root && return_type.kind != GDScriptParser::DataType::UNRESOLVED && return_type.builtin_type != Variant::NIL) { + parser->push_warning(p_call, GDScriptWarning::RETURN_VALUE_DISCARDED, p_call->function_name); + } + + if (is_static && !base_type.is_meta_type && !(callee_type != GDScriptParser::Node::SUBSCRIPT && parser->current_function != nullptr && parser->current_function->is_static)) { + parser->push_warning(p_call, GDScriptWarning::STATIC_CALLED_ON_INSTANCE, p_call->function_name, base_type.to_string()); + } +#endif // DEBUG_ENABLED + call_type = return_type; } else { bool found = false; @@ -2676,31 +2699,45 @@ void GDScriptAnalyzer::reduce_get_node(GDScriptParser::GetNodeNode *p_get_node) GDScriptParser::DataType GDScriptAnalyzer::make_global_class_meta_type(const StringName &p_class_name, const GDScriptParser::Node *p_source) { GDScriptParser::DataType type; - Ref<GDScriptParserRef> ref = get_parser_for(ScriptServer::get_global_class_path(p_class_name)); - if (ref.is_null()) { - push_error(vformat(R"(Could not find script for class "%s".)", p_class_name), p_source); - type.type_source = GDScriptParser::DataType::UNDETECTED; - type.kind = GDScriptParser::DataType::VARIANT; + String path = ScriptServer::get_global_class_path(p_class_name); + String ext = path.get_extension(); + if (ext == GDScriptLanguage::get_singleton()->get_extension()) { + Ref<GDScriptParserRef> ref = get_parser_for(path); + if (ref.is_null()) { + push_error(vformat(R"(Could not find script for class "%s".)", p_class_name), p_source); + type.type_source = GDScriptParser::DataType::UNDETECTED; + type.kind = GDScriptParser::DataType::VARIANT; + return type; + } + + 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); + type.type_source = GDScriptParser::DataType::UNDETECTED; + type.kind = GDScriptParser::DataType::VARIANT; + return type; + } + + type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; + type.kind = GDScriptParser::DataType::CLASS; + type.builtin_type = Variant::OBJECT; + type.native_type = ScriptServer::get_global_class_native_base(p_class_name); + type.class_type = ref->get_parser()->head; + type.script_path = ref->get_parser()->script_path; + type.is_constant = true; + type.is_meta_type = true; return type; - } - - 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); - type.type_source = GDScriptParser::DataType::UNDETECTED; - type.kind = GDScriptParser::DataType::VARIANT; + } else { + type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; + type.kind = GDScriptParser::DataType::SCRIPT; + type.builtin_type = Variant::OBJECT; + type.native_type = ScriptServer::get_global_class_native_base(p_class_name); + type.script_type = ResourceLoader::load(path, "Script"); + type.script_path = path; + type.is_constant = true; + type.is_meta_type = true; return type; } - - type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; - type.kind = GDScriptParser::DataType::CLASS; - type.builtin_type = Variant::OBJECT; - type.native_type = ScriptServer::get_global_class_native_base(p_class_name); - type.class_type = ref->get_parser()->head; - type.script_path = ref->get_parser()->script_path; - type.is_constant = true; - type.is_meta_type = true; - return type; } void GDScriptAnalyzer::reduce_identifier_from_base(GDScriptParser::IdentifierNode *p_identifier, GDScriptParser::DataType *p_base) { @@ -3067,11 +3104,11 @@ void GDScriptAnalyzer::reduce_identifier(GDScriptParser::IdentifierNode *p_ident result.kind = GDScriptParser::DataType::NATIVE; result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; if (autoload.path.to_lower().ends_with(GDScriptLanguage::get_singleton()->get_extension())) { - Ref<GDScriptParserRef> parser = get_parser_for(autoload.path); - if (parser.is_valid()) { - Error err = parser->raise_status(GDScriptParserRef::INTERFACE_SOLVED); + Ref<GDScriptParserRef> singl_parser = get_parser_for(autoload.path); + if (singl_parser.is_valid()) { + Error err = singl_parser->raise_status(GDScriptParserRef::INTERFACE_SOLVED); if (err == OK) { - result = type_from_metatype(parser->get_parser()->head->get_datatype()); + result = type_from_metatype(singl_parser->get_parser()->head->get_datatype()); } } } @@ -3189,8 +3226,14 @@ void GDScriptAnalyzer::reduce_preload(GDScriptParser::PreloadNode *p_preload) { p_preload->resolved_path = parser->script_path.get_base_dir().path_join(p_preload->resolved_path); } p_preload->resolved_path = p_preload->resolved_path.simplify_path(); - if (!FileAccess::exists(p_preload->resolved_path)) { - push_error(vformat(R"(Preload file "%s" does not exist.)", p_preload->resolved_path), p_preload->path); + if (!ResourceLoader::exists(p_preload->resolved_path)) { + Ref<FileAccess> file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES); + + if (file_check->file_exists(p_preload->resolved_path)) { + push_error(vformat(R"(Preload file "%s" has no resource loaders (unrecognized file extension).)", p_preload->resolved_path), p_preload->path); + } else { + push_error(vformat(R"(Preload file "%s" does not exist.)", p_preload->resolved_path), p_preload->path); + } } else { // TODO: Don't load if validating: use completion cache. p_preload->resource = ResourceLoader::load(p_preload->resolved_path); @@ -3808,7 +3851,7 @@ bool GDScriptAnalyzer::get_function_signature(GDScriptParser::Node *p_source, bo Ref<Script> base_script = p_base_type.script_type; - while (base_script.is_valid() && base_script->is_valid()) { + while (base_script.is_valid() && base_script->has_method(function_name)) { MethodInfo info = base_script->get_method_info(function_name); if (!(info == MethodInfo())) { diff --git a/modules/gdscript/gdscript_analyzer.h b/modules/gdscript/gdscript_analyzer.h index 3966b81b6e..217a856ce0 100644 --- a/modules/gdscript/gdscript_analyzer.h +++ b/modules/gdscript/gdscript_analyzer.h @@ -63,7 +63,7 @@ class GDScriptAnalyzer { void resolve_class_body(GDScriptParser::ClassNode *p_class); void resolve_function_signature(GDScriptParser::FunctionNode *p_function); void resolve_function_body(GDScriptParser::FunctionNode *p_function); - void resolve_node(GDScriptParser::Node *p_node); + void resolve_node(GDScriptParser::Node *p_node, bool p_is_root = true); void resolve_suite(GDScriptParser::SuiteNode *p_suite); void resolve_if(GDScriptParser::IfNode *p_if); void resolve_for(GDScriptParser::ForNode *p_for); diff --git a/modules/gdscript/gdscript_cache.cpp b/modules/gdscript/gdscript_cache.cpp index 48d5fbc569..03a101b9fc 100644 --- a/modules/gdscript/gdscript_cache.cpp +++ b/modules/gdscript/gdscript_cache.cpp @@ -34,6 +34,7 @@ #include "core/templates/vector.h" #include "gdscript.h" #include "gdscript_analyzer.h" +#include "gdscript_compiler.h" #include "gdscript_parser.h" bool GDScriptParserRef::is_valid() const { @@ -146,9 +147,7 @@ String GDScriptCache::get_source_code(const String &p_path) { Vector<uint8_t> source_file; Error err; Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err); - if (err) { - ERR_FAIL_COND_V(err, ""); - } + ERR_FAIL_COND_V(err, ""); uint64_t len = f->get_length(); source_file.resize(len + 1); @@ -163,7 +162,7 @@ String GDScriptCache::get_source_code(const String &p_path) { return source; } -Ref<GDScript> GDScriptCache::get_shallow_script(const String &p_path, const String &p_owner) { +Ref<GDScript> GDScriptCache::get_shallow_script(const String &p_path, Error &r_error, const String &p_owner) { MutexLock lock(singleton->lock); if (!p_owner.is_empty()) { singleton->dependencies[p_owner].insert(p_path); @@ -175,38 +174,53 @@ Ref<GDScript> GDScriptCache::get_shallow_script(const String &p_path, const Stri return singleton->shallow_gdscript_cache[p_path]; } + Ref<GDScriptParserRef> parser_ref = get_parser(p_path, GDScriptParserRef::PARSED, r_error); + if (r_error != OK) { + return Ref<GDScript>(); + } + Ref<GDScript> script; script.instantiate(); script->set_path(p_path, true); - script->set_script_path(p_path); script->load_source_code(p_path); + GDScriptCompiler::make_scripts(script.ptr(), parser_ref->get_parser()->get_tree(), true); singleton->shallow_gdscript_cache[p_path] = script.ptr(); return script; } -Ref<GDScript> GDScriptCache::get_full_script(const String &p_path, Error &r_error, const String &p_owner) { +Ref<GDScript> GDScriptCache::get_full_script(const String &p_path, Error &r_error, const String &p_owner, bool p_update_from_disk) { MutexLock lock(singleton->lock); if (!p_owner.is_empty()) { singleton->dependencies[p_owner].insert(p_path); } + Ref<GDScript> script; r_error = OK; if (singleton->full_gdscript_cache.has(p_path)) { - return singleton->full_gdscript_cache[p_path]; + script = Ref<GDScript>(singleton->full_gdscript_cache[p_path]); + if (!p_update_from_disk) { + return script; + } } - Ref<GDScript> script = get_shallow_script(p_path); - ERR_FAIL_COND_V(script.is_null(), Ref<GDScript>()); + if (script.is_null()) { + script = get_shallow_script(p_path, r_error); + if (r_error) { + return script; + } + } - r_error = script->load_source_code(p_path); + if (p_update_from_disk) { + r_error = script->load_source_code(p_path); + } if (r_error) { return script; } - r_error = script->reload(); + r_error = script->reload(true); if (r_error) { return script; } @@ -217,9 +231,25 @@ Ref<GDScript> GDScriptCache::get_full_script(const String &p_path, Error &r_erro return script; } +Ref<GDScript> GDScriptCache::get_cached_script(const String &p_path) { + MutexLock lock(singleton->lock); + + if (singleton->full_gdscript_cache.has(p_path)) { + return singleton->full_gdscript_cache[p_path]; + } + + if (singleton->shallow_gdscript_cache.has(p_path)) { + return singleton->shallow_gdscript_cache[p_path]; + } + + return Ref<GDScript>(); +} + Error GDScriptCache::finish_compiling(const String &p_owner) { + MutexLock lock(singleton->lock); + // Mark this as compiled. - Ref<GDScript> script = get_shallow_script(p_owner); + Ref<GDScript> script = get_cached_script(p_owner); singleton->full_gdscript_cache[p_owner] = script.ptr(); singleton->shallow_gdscript_cache.erase(p_owner); diff --git a/modules/gdscript/gdscript_cache.h b/modules/gdscript/gdscript_cache.h index b971bdd984..fcd240ba8d 100644 --- a/modules/gdscript/gdscript_cache.h +++ b/modules/gdscript/gdscript_cache.h @@ -87,8 +87,9 @@ class GDScriptCache { public: static Ref<GDScriptParserRef> get_parser(const String &p_path, GDScriptParserRef::Status status, Error &r_error, const String &p_owner = String()); static String get_source_code(const String &p_path); - static Ref<GDScript> get_shallow_script(const String &p_path, const String &p_owner = String()); - static Ref<GDScript> get_full_script(const String &p_path, Error &r_error, const String &p_owner = String()); + static Ref<GDScript> get_shallow_script(const String &p_path, Error &r_error, const String &p_owner = String()); + static Ref<GDScript> get_full_script(const String &p_path, Error &r_error, const String &p_owner = String(), bool p_update_from_disk = false); + static Ref<GDScript> get_cached_script(const String &p_path); static Error finish_compiling(const String &p_owner); GDScriptCache(); diff --git a/modules/gdscript/gdscript_compiler.cpp b/modules/gdscript/gdscript_compiler.cpp index 00e8223b9a..aa1356d8c0 100644 --- a/modules/gdscript/gdscript_compiler.cpp +++ b/modules/gdscript/gdscript_compiler.cpp @@ -80,7 +80,7 @@ void GDScriptCompiler::_set_error(const String &p_error, const GDScriptParser::N } } -GDScriptDataType GDScriptCompiler::_gdtype_from_datatype(const GDScriptParser::DataType &p_datatype, GDScript *p_owner) const { +GDScriptDataType GDScriptCompiler::_gdtype_from_datatype(const GDScriptParser::DataType &p_datatype, GDScript *p_owner) { if (!p_datatype.is_set() || !p_datatype.is_hard_type()) { return GDScriptDataType(); } @@ -103,75 +103,44 @@ GDScriptDataType GDScriptCompiler::_gdtype_from_datatype(const GDScriptParser::D } break; case GDScriptParser::DataType::SCRIPT: { result.kind = GDScriptDataType::SCRIPT; - result.script_type_ref = Ref<Script>(p_datatype.script_type); + result.builtin_type = p_datatype.builtin_type; + result.script_type_ref = p_datatype.script_type; result.script_type = result.script_type_ref.ptr(); - result.native_type = result.script_type->get_instance_base_type(); + result.native_type = p_datatype.native_type; } break; case GDScriptParser::DataType::CLASS: { - // Locate class by constructing the path to it and following that path. - GDScriptParser::ClassNode *class_type = p_datatype.class_type; - if (class_type) { - result.kind = GDScriptDataType::GDSCRIPT; - result.builtin_type = p_datatype.builtin_type; - - String class_name = class_type->fqcn.split("::")[0]; - const bool is_inner_by_path = (!main_script->path.is_empty()) && (class_name == main_script->path); - const bool is_inner_by_name = (!main_script->name.is_empty()) && (class_name == main_script->name); - if (is_inner_by_path || is_inner_by_name) { - // Local class. - List<StringName> names; - while (class_type->outer) { - names.push_back(class_type->identifier->name); - class_type = class_type->outer; - } + result.kind = GDScriptDataType::GDSCRIPT; + result.builtin_type = p_datatype.builtin_type; + result.native_type = p_datatype.native_type; - Ref<GDScript> script = Ref<GDScript>(main_script); - while (names.back()) { - if (!script->subclasses.has(names.back()->get())) { - ERR_PRINT("Parser bug: Cannot locate datatype class."); - result.has_type = false; - return GDScriptDataType(); - } - script = script->subclasses[names.back()->get()]; - names.pop_back(); - } - result.script_type = script.ptr(); - result.native_type = script->get_instance_base_type(); - } else { - // Inner class. - PackedStringArray classes = class_type->fqcn.split("::"); - if (!classes.is_empty()) { - for (GDScript *script : parsed_classes) { - // Checking of inheritance structure of inner class to find a correct script link. - if (script->name == classes[classes.size() - 1]) { - PackedStringArray classes2 = script->fully_qualified_name.split("::"); - bool valid = true; - if (classes.size() != classes2.size()) { - valid = false; - } else { - for (int i = 0; i < classes.size(); i++) { - if (classes[i] != classes2[i]) { - valid = false; - break; - } - } - } - if (!valid) { - continue; - } - result.script_type_ref = Ref<GDScript>(script); - break; - } - } - } - if (result.script_type_ref.is_null()) { - result.script_type_ref = GDScriptCache::get_shallow_script(p_datatype.script_path, main_script->path); - } + String root_name = p_datatype.class_type->fqcn.get_slice("::", 0); + bool is_local_class = !root_name.is_empty() && root_name == main_script->fully_qualified_name; - result.script_type = result.script_type_ref.ptr(); - result.native_type = p_datatype.native_type; + Ref<GDScript> script; + if (is_local_class) { + script = Ref<GDScript>(main_script); + } else { + Error err = OK; + script = GDScriptCache::get_shallow_script(p_datatype.script_path, err, p_owner->path); + if (err) { + _set_error(vformat(R"(Could not find script "%s": %s)", p_datatype.script_path, error_names[err]), nullptr); } } + + if (script.is_valid()) { + script = Ref<GDScript>(script->find_class(p_datatype.class_type->fqcn)); + } + + if (script.is_null()) { + _set_error(vformat(R"(Could not find class "%s" in "%s".)", p_datatype.class_type->fqcn, p_datatype.script_path), nullptr); + } else { + // Only hold a strong reference if the owner of the element qualified with this type is not local, to avoid cyclic references (leaks). + // TODO: Might lead to use after free if script_type is a subclass and is used after its parent is freed. + if (!is_local_class) { + result.script_type_ref = script; + } + result.script_type = script.ptr(); + } } break; case GDScriptParser::DataType::ENUM: result.has_type = true; @@ -189,13 +158,7 @@ GDScriptDataType GDScriptCompiler::_gdtype_from_datatype(const GDScriptParser::D } if (p_datatype.has_container_element_type()) { - result.set_container_element_type(_gdtype_from_datatype(p_datatype.get_container_element_type())); - } - - // Only hold strong reference to the script if it's not the owner of the - // element qualified with this type, to avoid cyclic references (leaks). - if (result.script_type && result.script_type == p_owner) { - result.script_type_ref = Ref<Script>(); + result.set_container_element_type(_gdtype_from_datatype(p_datatype.get_container_element_type(), p_owner)); } return result; @@ -367,7 +330,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code // This is so one autoload doesn't try to load another before it's compiled. HashMap<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list(); if (autoloads.has(identifier) && autoloads[identifier].is_singleton) { - GDScriptCodeGenerator::Address global = codegen.add_temporary(_gdtype_from_datatype(in->get_datatype())); + GDScriptCodeGenerator::Address global = codegen.add_temporary(_gdtype_from_datatype(in->get_datatype(), codegen.script)); int idx = GDScriptLanguage::get_singleton()->get_global_map()[identifier]; gen->write_store_global(global, idx); return global; @@ -434,7 +397,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code Vector<GDScriptCodeGenerator::Address> values; // Create the result temporary first since it's the last to be killed. - GDScriptDataType array_type = _gdtype_from_datatype(an->get_datatype()); + GDScriptDataType array_type = _gdtype_from_datatype(an->get_datatype(), codegen.script); GDScriptCodeGenerator::Address result = codegen.add_temporary(array_type); for (int i = 0; i < an->elements.size(); i++) { @@ -511,7 +474,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code case GDScriptParser::Node::CAST: { const GDScriptParser::CastNode *cn = static_cast<const GDScriptParser::CastNode *>(p_expression); GDScriptParser::DataType og_cast_type = cn->cast_type->get_datatype(); - GDScriptDataType cast_type = _gdtype_from_datatype(og_cast_type); + GDScriptDataType cast_type = _gdtype_from_datatype(og_cast_type, codegen.script); if (og_cast_type.kind == GDScriptParser::DataType::ENUM) { // Enum types are usually treated as dictionaries, but in this case we want to cast to an integer. @@ -522,11 +485,11 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code // Create temporary for result first since it will be deleted last. GDScriptCodeGenerator::Address result = codegen.add_temporary(cast_type); - GDScriptCodeGenerator::Address source = _parse_expression(codegen, r_error, cn->operand); + GDScriptCodeGenerator::Address src = _parse_expression(codegen, r_error, cn->operand); - gen->write_cast(result, source, cast_type); + gen->write_cast(result, src, cast_type); - if (source.mode == GDScriptCodeGenerator::Address::TEMPORARY) { + if (src.mode == GDScriptCodeGenerator::Address::TEMPORARY) { gen->pop_temporary(); } @@ -534,7 +497,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code } break; case GDScriptParser::Node::CALL: { const GDScriptParser::CallNode *call = static_cast<const GDScriptParser::CallNode *>(p_expression); - GDScriptDataType type = _gdtype_from_datatype(call->get_datatype()); + GDScriptDataType type = _gdtype_from_datatype(call->get_datatype(), codegen.script); GDScriptCodeGenerator::Address result = codegen.add_temporary(type); GDScriptCodeGenerator::Address nil = GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::NIL); @@ -670,7 +633,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code Vector<GDScriptCodeGenerator::Address> args; args.push_back(codegen.add_constant(NodePath(get_node->full_path))); - GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(get_node->get_datatype())); + GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(get_node->get_datatype(), codegen.script)); MethodBind *get_node_method = ClassDB::get_method("Node", "get_node"); gen->write_call_ptrcall(result, GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::SELF), get_node_method, args); @@ -686,7 +649,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code case GDScriptParser::Node::AWAIT: { const GDScriptParser::AwaitNode *await = static_cast<const GDScriptParser::AwaitNode *>(p_expression); - GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(p_expression->get_datatype())); + GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(p_expression->get_datatype(), codegen.script)); within_await = true; GDScriptCodeGenerator::Address argument = _parse_expression(codegen, r_error, await->to_await); within_await = false; @@ -705,7 +668,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code // Indexing operator. case GDScriptParser::Node::SUBSCRIPT: { const GDScriptParser::SubscriptNode *subscript = static_cast<const GDScriptParser::SubscriptNode *>(p_expression); - GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(subscript->get_datatype())); + GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(subscript->get_datatype(), codegen.script)); GDScriptCodeGenerator::Address base = _parse_expression(codegen, r_error, subscript->base); if (r_error) { @@ -735,7 +698,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code // Remove result temp as we don't need it. gen->pop_temporary(); // Faster than indexing self (as if no self. had been used). - return GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::MEMBER, MI->value.index, _gdtype_from_datatype(subscript->get_datatype())); + return GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::MEMBER, MI->value.index, _gdtype_from_datatype(subscript->get_datatype(), codegen.script)); } } @@ -773,7 +736,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code case GDScriptParser::Node::UNARY_OPERATOR: { const GDScriptParser::UnaryOpNode *unary = static_cast<const GDScriptParser::UnaryOpNode *>(p_expression); - GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(unary->get_datatype())); + GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(unary->get_datatype(), codegen.script)); GDScriptCodeGenerator::Address operand = _parse_expression(codegen, r_error, unary->operand); if (r_error) { @@ -791,7 +754,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code case GDScriptParser::Node::BINARY_OPERATOR: { const GDScriptParser::BinaryOpNode *binary = static_cast<const GDScriptParser::BinaryOpNode *>(p_expression); - GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(binary->get_datatype())); + GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(binary->get_datatype(), codegen.script)); switch (binary->operation) { case GDScriptParser::BinaryOpNode::OP_LOGIC_AND: { @@ -867,7 +830,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code case GDScriptParser::Node::TERNARY_OPERATOR: { // x IF a ELSE y operator with early out on failure. const GDScriptParser::TernaryOpNode *ternary = static_cast<const GDScriptParser::TernaryOpNode *>(p_expression); - GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(ternary->get_datatype())); + GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(ternary->get_datatype(), codegen.script)); gen->write_start_ternary(result); @@ -985,7 +948,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code break; } const GDScriptParser::SubscriptNode *subscript_elem = E->get(); - GDScriptCodeGenerator::Address value = codegen.add_temporary(_gdtype_from_datatype(subscript_elem->get_datatype())); + GDScriptCodeGenerator::Address value = codegen.add_temporary(_gdtype_from_datatype(subscript_elem->get_datatype(), codegen.script)); GDScriptCodeGenerator::Address key; StringName name; @@ -1024,8 +987,8 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code // Perform operator if any. if (assignment->operation != GDScriptParser::AssignmentNode::OP_NONE) { - GDScriptCodeGenerator::Address op_result = codegen.add_temporary(_gdtype_from_datatype(assignment->get_datatype())); - GDScriptCodeGenerator::Address value = codegen.add_temporary(_gdtype_from_datatype(subscript->get_datatype())); + GDScriptCodeGenerator::Address op_result = codegen.add_temporary(_gdtype_from_datatype(assignment->get_datatype(), codegen.script)); + GDScriptCodeGenerator::Address value = codegen.add_temporary(_gdtype_from_datatype(subscript->get_datatype(), codegen.script)); if (subscript->is_attribute) { gen->write_get_named(value, name, prev_base); } else { @@ -1130,8 +1093,8 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code StringName name = static_cast<GDScriptParser::IdentifierNode *>(assignment->assignee)->name; if (has_operation) { - GDScriptCodeGenerator::Address op_result = codegen.add_temporary(_gdtype_from_datatype(assignment->get_datatype())); - GDScriptCodeGenerator::Address member = codegen.add_temporary(_gdtype_from_datatype(assignment->assignee->get_datatype())); + GDScriptCodeGenerator::Address op_result = codegen.add_temporary(_gdtype_from_datatype(assignment->get_datatype(), codegen.script)); + GDScriptCodeGenerator::Address member = codegen.add_temporary(_gdtype_from_datatype(assignment->assignee->get_datatype(), codegen.script)); gen->write_get_member(member, name); gen->write_binary_operator(op_result, assignment->variant_op, member, assigned_value); gen->pop_temporary(); // Pop member temp. @@ -1184,7 +1147,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code bool has_operation = assignment->operation != GDScriptParser::AssignmentNode::OP_NONE; if (has_operation) { // Perform operation. - GDScriptCodeGenerator::Address op_result = codegen.add_temporary(_gdtype_from_datatype(assignment->get_datatype())); + GDScriptCodeGenerator::Address op_result = codegen.add_temporary(_gdtype_from_datatype(assignment->get_datatype(), codegen.script)); GDScriptCodeGenerator::Address og_value = _parse_expression(codegen, r_error, assignment->assignee); gen->write_binary_operator(op_result, assignment->variant_op, og_value, assigned_value); to_assign = op_result; @@ -1196,7 +1159,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code to_assign = assigned_value; } - GDScriptDataType assign_type = _gdtype_from_datatype(assignment->assignee->get_datatype()); + GDScriptDataType assign_type = _gdtype_from_datatype(assignment->assignee->get_datatype(), codegen.script); if (has_setter && !is_in_setter) { // Call setter. @@ -1226,7 +1189,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code } break; case GDScriptParser::Node::LAMBDA: { const GDScriptParser::LambdaNode *lambda = static_cast<const GDScriptParser::LambdaNode *>(p_expression); - GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(lambda->get_datatype())); + GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(lambda->get_datatype(), codegen.script)); Vector<GDScriptCodeGenerator::Address> captures; captures.resize(lambda->captures.size()); @@ -1645,12 +1608,12 @@ void GDScriptCompiler::_add_locals_in_block(CodeGen &codegen, const GDScriptPars // Parameters are added directly from function and loop variables are declared explicitly. continue; } - codegen.add_local(p_block->locals[i].name, _gdtype_from_datatype(p_block->locals[i].get_datatype())); + codegen.add_local(p_block->locals[i].name, _gdtype_from_datatype(p_block->locals[i].get_datatype(), codegen.script)); } } Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::SuiteNode *p_block, bool p_add_locals) { - Error error = OK; + Error err = OK; GDScriptCodeGenerator *gen = codegen.generator; codegen.start_block(); @@ -1675,10 +1638,10 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui codegen.start_block(); // Evaluate the match expression. - GDScriptCodeGenerator::Address value = codegen.add_local("@match_value", _gdtype_from_datatype(match->test->get_datatype())); - GDScriptCodeGenerator::Address value_expr = _parse_expression(codegen, error, match->test); - if (error) { - return error; + GDScriptCodeGenerator::Address value = codegen.add_local("@match_value", _gdtype_from_datatype(match->test->get_datatype(), codegen.script)); + GDScriptCodeGenerator::Address value_expr = _parse_expression(codegen, err, match->test); + if (err) { + return err; } // Assign to local. @@ -1723,9 +1686,9 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui // For each pattern in branch. GDScriptCodeGenerator::Address pattern_result = codegen.add_temporary(); for (int k = 0; k < branch->patterns.size(); k++) { - pattern_result = _parse_match_pattern(codegen, error, branch->patterns[k], value, type, pattern_result, k == 0, false); - if (error != OK) { - return error; + pattern_result = _parse_match_pattern(codegen, err, branch->patterns[k], value, type, pattern_result, k == 0, false); + if (err != OK) { + return err; } } @@ -1736,9 +1699,9 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui gen->pop_temporary(); // Parse the branch block. - error = _parse_block(codegen, branch->block, false); // Don't add locals again. - if (error) { - return error; + err = _parse_block(codegen, branch->block, false); // Don't add locals again. + if (err) { + return err; } codegen.end_block(); // Get out of extra block. @@ -1753,9 +1716,9 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui } break; case GDScriptParser::Node::IF: { const GDScriptParser::IfNode *if_n = static_cast<const GDScriptParser::IfNode *>(s); - GDScriptCodeGenerator::Address condition = _parse_expression(codegen, error, if_n->condition); - if (error) { - return error; + GDScriptCodeGenerator::Address condition = _parse_expression(codegen, err, if_n->condition); + if (err) { + return err; } gen->write_if(condition); @@ -1764,17 +1727,17 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui codegen.generator->pop_temporary(); } - error = _parse_block(codegen, if_n->true_block); - if (error) { - return error; + err = _parse_block(codegen, if_n->true_block); + if (err) { + return err; } if (if_n->false_block) { gen->write_else(); - error = _parse_block(codegen, if_n->false_block); - if (error) { - return error; + err = _parse_block(codegen, if_n->false_block); + if (err) { + return err; } } @@ -1784,13 +1747,13 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui const GDScriptParser::ForNode *for_n = static_cast<const GDScriptParser::ForNode *>(s); codegen.start_block(); - GDScriptCodeGenerator::Address iterator = codegen.add_local(for_n->variable->name, _gdtype_from_datatype(for_n->variable->get_datatype())); + GDScriptCodeGenerator::Address iterator = codegen.add_local(for_n->variable->name, _gdtype_from_datatype(for_n->variable->get_datatype(), codegen.script)); - gen->start_for(iterator.type, _gdtype_from_datatype(for_n->list->get_datatype())); + gen->start_for(iterator.type, _gdtype_from_datatype(for_n->list->get_datatype(), codegen.script)); - GDScriptCodeGenerator::Address list = _parse_expression(codegen, error, for_n->list); - if (error) { - return error; + GDScriptCodeGenerator::Address list = _parse_expression(codegen, err, for_n->list); + if (err) { + return err; } gen->write_for_assignment(iterator, list); @@ -1801,9 +1764,9 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui gen->write_for(); - error = _parse_block(codegen, for_n->loop); - if (error) { - return error; + err = _parse_block(codegen, for_n->loop); + if (err) { + return err; } gen->write_endfor(); @@ -1815,9 +1778,9 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui gen->start_while_condition(); - GDScriptCodeGenerator::Address condition = _parse_expression(codegen, error, while_n->condition); - if (error) { - return error; + GDScriptCodeGenerator::Address condition = _parse_expression(codegen, err, while_n->condition); + if (err) { + return err; } gen->write_while(condition); @@ -1826,9 +1789,9 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui codegen.generator->pop_temporary(); } - error = _parse_block(codegen, while_n->loop); - if (error) { - return error; + err = _parse_block(codegen, while_n->loop); + if (err) { + return err; } gen->write_endwhile(); @@ -1850,9 +1813,9 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui GDScriptCodeGenerator::Address return_value; if (return_n->return_value != nullptr) { - return_value = _parse_expression(codegen, error, return_n->return_value); - if (error) { - return error; + return_value = _parse_expression(codegen, err, return_n->return_value); + if (err) { + return err; } } @@ -1865,17 +1828,17 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui #ifdef DEBUG_ENABLED const GDScriptParser::AssertNode *as = static_cast<const GDScriptParser::AssertNode *>(s); - GDScriptCodeGenerator::Address condition = _parse_expression(codegen, error, as->condition); - if (error) { - return error; + GDScriptCodeGenerator::Address condition = _parse_expression(codegen, err, as->condition); + if (err) { + return err; } GDScriptCodeGenerator::Address message; if (as->message) { - message = _parse_expression(codegen, error, as->message); - if (error) { - return error; + message = _parse_expression(codegen, err, as->message); + if (err) { + return err; } } gen->write_assert(condition, message); @@ -1897,20 +1860,20 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui const GDScriptParser::VariableNode *lv = static_cast<const GDScriptParser::VariableNode *>(s); // Should be already in stack when the block began. GDScriptCodeGenerator::Address local = codegen.locals[lv->identifier->name]; - GDScriptParser::DataType local_type = lv->get_datatype(); + GDScriptDataType local_type = _gdtype_from_datatype(lv->get_datatype(), codegen.script); if (lv->initializer != nullptr) { // For typed arrays we need to make sure this is already initialized correctly so typed assignment work. - if (local_type.is_hard_type() && local_type.builtin_type == Variant::ARRAY) { + if (local_type.has_type && local_type.builtin_type == Variant::ARRAY) { if (local_type.has_container_element_type()) { - codegen.generator->write_construct_typed_array(local, _gdtype_from_datatype(local_type.get_container_element_type(), codegen.script), Vector<GDScriptCodeGenerator::Address>()); + codegen.generator->write_construct_typed_array(local, local_type.get_container_element_type(), Vector<GDScriptCodeGenerator::Address>()); } else { codegen.generator->write_construct_array(local, Vector<GDScriptCodeGenerator::Address>()); } } - GDScriptCodeGenerator::Address src_address = _parse_expression(codegen, error, lv->initializer); - if (error) { - return error; + GDScriptCodeGenerator::Address src_address = _parse_expression(codegen, err, lv->initializer); + if (err) { + return err; } if (lv->use_conversion_assign) { gen->write_assign_with_conversion(local, src_address); @@ -1920,11 +1883,11 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui if (src_address.mode == GDScriptCodeGenerator::Address::TEMPORARY) { codegen.generator->pop_temporary(); } - } else if (lv->get_datatype().is_hard_type()) { + } else if (local_type.has_type) { // Initialize with default for type. if (local_type.has_container_element_type()) { - codegen.generator->write_construct_typed_array(local, _gdtype_from_datatype(local_type.get_container_element_type(), codegen.script), Vector<GDScriptCodeGenerator::Address>()); - } else if (local_type.kind == GDScriptParser::DataType::BUILTIN) { + codegen.generator->write_construct_typed_array(local, local_type.get_container_element_type(), Vector<GDScriptCodeGenerator::Address>()); + } else if (local_type.kind == GDScriptDataType::BUILTIN) { codegen.generator->write_construct(local, local_type.builtin_type, Vector<GDScriptCodeGenerator::Address>()); } // The `else` branch is for objects, in such case we leave it as `null`. @@ -1946,9 +1909,9 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui default: { // Expression. if (s->is_expression()) { - GDScriptCodeGenerator::Address expr = _parse_expression(codegen, error, static_cast<const GDScriptParser::ExpressionNode *>(s), true); - if (error) { - return error; + GDScriptCodeGenerator::Address expr = _parse_expression(codegen, err, static_cast<const GDScriptParser::ExpressionNode *>(s), true); + if (err) { + return err; } if (expr.mode == GDScriptCodeGenerator::Address::TEMPORARY) { codegen.generator->pop_temporary(); @@ -2033,17 +1996,17 @@ GDScriptFunction *GDScriptCompiler::_parse_function(Error &r_error, GDScript *p_ continue; } - GDScriptParser::DataType field_type = field->get_datatype(); + GDScriptDataType field_type = _gdtype_from_datatype(field->get_datatype(), codegen.script); - GDScriptCodeGenerator::Address dst_address(GDScriptCodeGenerator::Address::MEMBER, codegen.script->member_indices[field->identifier->name].index, _gdtype_from_datatype(field->get_datatype())); + GDScriptCodeGenerator::Address dst_address(GDScriptCodeGenerator::Address::MEMBER, codegen.script->member_indices[field->identifier->name].index, field_type); if (field->initializer) { // Emit proper line change. codegen.generator->write_newline(field->initializer->start_line); // For typed arrays we need to make sure this is already initialized correctly so typed assignment work. - if (field_type.is_hard_type() && field_type.builtin_type == Variant::ARRAY && field_type.has_container_element_type()) { + if (field_type.has_type && field_type.builtin_type == Variant::ARRAY) { if (field_type.has_container_element_type()) { - codegen.generator->write_construct_typed_array(dst_address, _gdtype_from_datatype(field_type.get_container_element_type(), codegen.script), Vector<GDScriptCodeGenerator::Address>()); + codegen.generator->write_construct_typed_array(dst_address, field_type.get_container_element_type(), Vector<GDScriptCodeGenerator::Address>()); } else { codegen.generator->write_construct_array(dst_address, Vector<GDScriptCodeGenerator::Address>()); } @@ -2062,13 +2025,13 @@ GDScriptFunction *GDScriptCompiler::_parse_function(Error &r_error, GDScript *p_ if (src_address.mode == GDScriptCodeGenerator::Address::TEMPORARY) { codegen.generator->pop_temporary(); } - } else if (field->get_datatype().is_hard_type()) { + } else if (field_type.has_type) { codegen.generator->write_newline(field->start_line); // Initialize with default for type. if (field_type.has_container_element_type()) { - codegen.generator->write_construct_typed_array(dst_address, _gdtype_from_datatype(field_type.get_container_element_type(), codegen.script), Vector<GDScriptCodeGenerator::Address>()); - } else if (field_type.kind == GDScriptParser::DataType::BUILTIN) { + codegen.generator->write_construct_typed_array(dst_address, field_type.get_container_element_type(), Vector<GDScriptCodeGenerator::Address>()); + } else if (field_type.kind == GDScriptDataType::BUILTIN) { codegen.generator->write_construct(dst_address, field_type.builtin_type, Vector<GDScriptCodeGenerator::Address>()); } // The `else` branch is for objects, in such case we leave it as `null`. @@ -2180,7 +2143,7 @@ GDScriptFunction *GDScriptCompiler::_parse_function(Error &r_error, GDScript *p_ } Error GDScriptCompiler::_parse_setter_getter(GDScript *p_script, const GDScriptParser::ClassNode *p_class, const GDScriptParser::VariableNode *p_variable, bool p_is_setter) { - Error error = OK; + Error err = OK; GDScriptParser::FunctionNode *function; @@ -2190,28 +2153,24 @@ Error GDScriptCompiler::_parse_setter_getter(GDScript *p_script, const GDScriptP function = p_variable->getter; } - _parse_function(error, p_script, p_class, function); + _parse_function(err, p_script, p_class, function); - return error; + return err; } -Error GDScriptCompiler::_parse_class_level(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) { - parsing_classes.insert(p_script); +Error GDScriptCompiler::_populate_class_members(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) { + if (parsed_classes.has(p_script)) { + return OK; + } - if (p_class->outer && p_class->outer->outer) { - // Owner is not root - if (!parsed_classes.has(p_script->_owner)) { - if (parsing_classes.has(p_script->_owner)) { - _set_error("Cyclic class reference for '" + String(p_class->identifier->name) + "'.", p_class); - return ERR_PARSE_ERROR; - } - Error err = _parse_class_level(p_script->_owner, p_class->outer, p_keep_state); - if (err) { - return err; - } - } + if (parsing_classes.has(p_script)) { + String class_name = p_class->identifier ? String(p_class->identifier->name) : p_class->fqcn; + _set_error(vformat(R"(Cyclic class reference for "%s".)", class_name), p_class); + return ERR_PARSE_ERROR; } + parsing_classes.insert(p_script); + #ifdef TOOLS_ENABLED p_script->doc_functions.clear(); p_script->doc_variables.clear(); @@ -2253,7 +2212,6 @@ Error GDScriptCompiler::_parse_class_level(GDScript *p_script, const GDScriptPar p_script->implicit_ready = nullptr; p_script->tool = parser->is_tool(); - p_script->name = p_class->identifier ? p_class->identifier->name : ""; if (!p_script->name.is_empty()) { if (ClassDB::class_exists(p_script->name) && ClassDB::is_class_exposed(p_script->name)) { @@ -2262,53 +2220,50 @@ Error GDScriptCompiler::_parse_class_level(GDScript *p_script, const GDScriptPar } } - Ref<GDScriptNativeClass> native; + GDScriptDataType base_type = _gdtype_from_datatype(p_class->base_type, p_script); - GDScriptDataType base_type = _gdtype_from_datatype(p_class->base_type); // Inheritance switch (base_type.kind) { case GDScriptDataType::NATIVE: { int native_idx = GDScriptLanguage::get_singleton()->get_global_map()[base_type.native_type]; - native = GDScriptLanguage::get_singleton()->get_global_array()[native_idx]; - ERR_FAIL_COND_V(native.is_null(), ERR_BUG); - p_script->native = native; + p_script->native = GDScriptLanguage::get_singleton()->get_global_array()[native_idx]; + ERR_FAIL_COND_V(p_script->native.is_null(), ERR_BUG); } break; case GDScriptDataType::GDSCRIPT: { Ref<GDScript> base = Ref<GDScript>(base_type.script_type); - p_script->base = base; - p_script->_base = base.ptr(); + if (base.is_null()) { + return ERR_COMPILATION_FAILED; + } - if (p_class->base_type.kind == GDScriptParser::DataType::CLASS && p_class->base_type.class_type != nullptr) { - if (p_class->base_type.script_path == main_script->path) { - if (!parsed_classes.has(p_script->_base)) { - if (parsing_classes.has(p_script->_base)) { - String class_name = p_class->identifier ? p_class->identifier->name : "<main>"; - _set_error("Cyclic class reference for '" + class_name + "'.", p_class); - return ERR_PARSE_ERROR; - } - Error err = _parse_class_level(p_script->_base, p_class->base_type.class_type, p_keep_state); - if (err) { - return err; - } - } - } else { - Error err = OK; - base = GDScriptCache::get_full_script(p_class->base_type.script_path, err, main_script->path); - if (err) { - return err; - } - if (base.is_null() || !base->is_valid()) { - return ERR_COMPILATION_FAILED; - } + if (base.ptr() == main_script || main_script->is_subclass(base.ptr())) { + Error err = _populate_class_members(base.ptr(), p_class->base_type.class_type, p_keep_state); + if (err) { + return err; + } + } else if (!base->is_valid()) { + Error err = OK; + Ref<GDScript> base_root = GDScriptCache::get_full_script(base->path, err, p_script->path); + if (err) { + _set_error(vformat(R"(Could not compile base class "%s" from "%s": %s)", base->fully_qualified_name, base->path, error_names[err]), nullptr); + return err; + } + if (base_root.is_valid()) { + base = Ref<GDScript>(base_root->find_class(base->fully_qualified_name)); } + if (base.is_null()) { + _set_error(vformat(R"(Could not find class "%s" in "%s".)", base->fully_qualified_name, base->path), nullptr); + return ERR_COMPILATION_FAILED; + } + ERR_FAIL_COND_V(!base->is_valid(), ERR_BUG); } + p_script->base = base; + p_script->_base = base.ptr(); p_script->member_indices = base->member_indices; - native = base->native; - p_script->native = native; + p_script->native = base->native; } break; default: { - _set_error("Parser bug: invalid inheritance.", p_class); + _set_error("Parser bug: invalid inheritance.", nullptr); return ERR_BUG; } break; } @@ -2432,9 +2387,8 @@ Error GDScriptCompiler::_parse_class_level(GDScript *p_script, const GDScriptPar // TODO: Make enums not be just a dictionary? Dictionary new_enum; for (int j = 0; j < enum_n->values.size(); j++) { - int value = enum_n->values[j].value; // Needs to be string because Variant::get will convert to String. - new_enum[String(enum_n->values[j].identifier->name)] = value; + new_enum[String(enum_n->values[j].identifier->name)] = enum_n->values[j].value; } p_script->constants.insert(enum_n->identifier->name, new_enum); @@ -2479,8 +2433,7 @@ Error GDScriptCompiler::_parse_class_level(GDScript *p_script, const GDScriptPar parsed_classes.insert(p_script); parsing_classes.erase(p_script); - //parse sub-classes - + // Populate sub-classes. for (int i = 0; i < p_class->members.size(); i++) { const GDScriptParser::ClassNode::Member &member = p_class->members[i]; if (member.type != member.CLASS) { @@ -2492,8 +2445,8 @@ Error GDScriptCompiler::_parse_class_level(GDScript *p_script, const GDScriptPar GDScript *subclass_ptr = subclass.ptr(); // Subclass might still be parsing, just skip it - if (!parsed_classes.has(subclass_ptr) && !parsing_classes.has(subclass_ptr)) { - Error err = _parse_class_level(subclass_ptr, inner_class, p_keep_state); + if (!parsing_classes.has(subclass_ptr)) { + Error err = _populate_class_members(subclass_ptr, inner_class, p_keep_state); if (err) { return err; } @@ -2510,9 +2463,8 @@ Error GDScriptCompiler::_parse_class_level(GDScript *p_script, const GDScriptPar return OK; } -Error GDScriptCompiler::_parse_class_blocks(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) { - //parse methods - +Error GDScriptCompiler::_compile_class(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) { + // Compile member functions, getters, and setters. for (int i = 0; i < p_class->members.size(); i++) { const GDScriptParser::ClassNode::Member &member = p_class->members[i]; if (member.type == member.FUNCTION) { @@ -2616,17 +2568,26 @@ Error GDScriptCompiler::_parse_class_blocks(GDScript *p_script, const GDScriptPa StringName name = inner_class->identifier->name; GDScript *subclass = p_script->subclasses[name].ptr(); - Error err = _parse_class_blocks(subclass, inner_class, p_keep_state); + Error err = _compile_class(subclass, inner_class, p_keep_state); if (err) { return err; } } +#ifdef TOOLS_ENABLED + p_script->_update_doc(); +#endif + + p_script->_init_rpc_methods_properties(); + p_script->valid = true; return OK; } -void GDScriptCompiler::_make_scripts(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) { +void GDScriptCompiler::make_scripts(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) { + p_script->fully_qualified_name = p_class->fqcn; + p_script->name = p_class->identifier ? p_class->identifier->name : ""; + HashMap<StringName, Ref<GDScript>> old_subclasses; if (p_keep_state) { @@ -2643,24 +2604,22 @@ void GDScriptCompiler::_make_scripts(GDScript *p_script, const GDScriptParser::C StringName name = inner_class->identifier->name; Ref<GDScript> subclass; - String fully_qualified_name = p_script->fully_qualified_name + "::" + name; if (old_subclasses.has(name)) { subclass = old_subclasses[name]; } else { - Ref<GDScript> orphan_subclass = GDScriptLanguage::get_singleton()->get_orphan_subclass(fully_qualified_name); - if (orphan_subclass.is_valid()) { - subclass = orphan_subclass; - } else { - subclass.instantiate(); - } + subclass = GDScriptLanguage::get_singleton()->get_orphan_subclass(inner_class->fqcn); + } + + if (subclass.is_null()) { + subclass.instantiate(); } subclass->_owner = p_script; - subclass->fully_qualified_name = fully_qualified_name; + subclass->path = p_script->path; p_script->subclasses.insert(name, subclass); - _make_scripts(subclass.ptr(), inner_class, false); + make_scripts(subclass.ptr(), inner_class, p_keep_state); } } @@ -2674,26 +2633,22 @@ Error GDScriptCompiler::compile(const GDScriptParser *p_parser, GDScript *p_scri source = p_script->get_path(); - // The best fully qualified name for a base level script is its file path - p_script->fully_qualified_name = p_script->path; - // Create scripts for subclasses beforehand so they can be referenced - _make_scripts(p_script, root, p_keep_state); + make_scripts(p_script, root, p_keep_state); - p_script->_owner = nullptr; - Error err = _parse_class_level(p_script, root, p_keep_state); + main_script->_owner = nullptr; + Error err = _populate_class_members(main_script, parser->get_tree(), p_keep_state); if (err) { return err; } - err = _parse_class_blocks(p_script, root, p_keep_state); - + err = _compile_class(main_script, root, p_keep_state); if (err) { return err; } - return GDScriptCache::finish_compiling(p_script->get_path()); + return GDScriptCache::finish_compiling(main_script->get_path()); } String GDScriptCompiler::get_error() const { diff --git a/modules/gdscript/gdscript_compiler.h b/modules/gdscript/gdscript_compiler.h index 4841884e2d..45ca4fe342 100644 --- a/modules/gdscript/gdscript_compiler.h +++ b/modules/gdscript/gdscript_compiler.h @@ -81,10 +81,10 @@ class GDScriptCompiler { type.kind = GDScriptDataType::NATIVE; type.native_type = obj->get_class_name(); - Ref<Script> script = obj->get_script(); - if (script.is_valid()) { - type.script_type = script.ptr(); - Ref<GDScript> gdscript = script; + Ref<Script> scr = obj->get_script(); + if (scr.is_valid()) { + type.script_type = scr.ptr(); + Ref<GDScript> gdscript = scr; if (gdscript.is_valid()) { type.kind = GDScriptDataType::GDSCRIPT; } else { @@ -121,7 +121,7 @@ class GDScriptCompiler { Error _create_binary_operator(CodeGen &codegen, const GDScriptParser::BinaryOpNode *on, Variant::Operator op, bool p_initializer = false, const GDScriptCodeGenerator::Address &p_index_addr = GDScriptCodeGenerator::Address()); Error _create_binary_operator(CodeGen &codegen, const GDScriptParser::ExpressionNode *p_left_operand, const GDScriptParser::ExpressionNode *p_right_operand, Variant::Operator op, bool p_initializer = false, const GDScriptCodeGenerator::Address &p_index_addr = GDScriptCodeGenerator::Address()); - GDScriptDataType _gdtype_from_datatype(const GDScriptParser::DataType &p_datatype, GDScript *p_owner = nullptr) const; + GDScriptDataType _gdtype_from_datatype(const GDScriptParser::DataType &p_datatype, GDScript *p_owner); GDScriptCodeGenerator::Address _parse_assign_right_expression(CodeGen &codegen, Error &r_error, const GDScriptParser::AssignmentNode *p_assignmentint, const GDScriptCodeGenerator::Address &p_index_addr = GDScriptCodeGenerator::Address()); GDScriptCodeGenerator::Address _parse_expression(CodeGen &codegen, Error &r_error, const GDScriptParser::ExpressionNode *p_expression, bool p_root = false, bool p_initializer = false, const GDScriptCodeGenerator::Address &p_index_addr = GDScriptCodeGenerator::Address()); @@ -130,9 +130,8 @@ class GDScriptCompiler { Error _parse_block(CodeGen &codegen, const GDScriptParser::SuiteNode *p_block, bool p_add_locals = true); GDScriptFunction *_parse_function(Error &r_error, GDScript *p_script, const GDScriptParser::ClassNode *p_class, const GDScriptParser::FunctionNode *p_func, bool p_for_ready = false, bool p_for_lambda = false); Error _parse_setter_getter(GDScript *p_script, const GDScriptParser::ClassNode *p_class, const GDScriptParser::VariableNode *p_variable, bool p_is_setter); - Error _parse_class_level(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state); - Error _parse_class_blocks(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state); - void _make_scripts(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state); + Error _populate_class_members(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state); + Error _compile_class(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state); int err_line = 0; int err_column = 0; StringName source; @@ -140,6 +139,7 @@ class GDScriptCompiler { bool within_await = false; public: + static void make_scripts(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state); Error compile(const GDScriptParser *p_parser, GDScript *p_script, bool p_keep_state = false); String get_error() const; diff --git a/modules/gdscript/gdscript_disassembler.cpp b/modules/gdscript/gdscript_disassembler.cpp index b38c7c6699..b5a209c805 100644 --- a/modules/gdscript/gdscript_disassembler.cpp +++ b/modules/gdscript/gdscript_disassembler.cpp @@ -104,10 +104,10 @@ void GDScriptFunction::disassemble(const Vector<String> &p_code_lines) const { text += ": "; // This makes the compiler complain if some opcode is unchecked in the switch. - Opcode code = Opcode(_code_ptr[ip] & INSTR_MASK); + Opcode opcode = Opcode(_code_ptr[ip] & INSTR_MASK); int instr_var_args = (_code_ptr[ip] & INSTR_ARGS_MASK) >> INSTR_BITS; - switch (code) { + switch (opcode) { case OPCODE_OPERATOR: { int operation = _code_ptr[ip + 4]; diff --git a/modules/gdscript/gdscript_editor.cpp b/modules/gdscript/gdscript_editor.cpp index d626d5cf2e..68508b20da 100644 --- a/modules/gdscript/gdscript_editor.cpp +++ b/modules/gdscript/gdscript_editor.cpp @@ -61,8 +61,8 @@ bool GDScriptLanguage::is_using_templates() { } Ref<Script> GDScriptLanguage::make_template(const String &p_template, const String &p_class_name, const String &p_base_class_name) const { - Ref<GDScript> script; - script.instantiate(); + Ref<GDScript> scr; + scr.instantiate(); String processed_template = p_template; bool type_hints = false; #ifdef TOOLS_ENABLED @@ -82,8 +82,8 @@ Ref<Script> GDScriptLanguage::make_template(const String &p_template, const Stri processed_template = processed_template.replace("_BASE_", p_base_class_name) .replace("_CLASS_", p_class_name) .replace("_TS_", _get_indentation()); - script->set_source_code(processed_template); - return script; + scr->set_source_code(processed_template); + return scr; } Vector<ScriptLanguage::ScriptTemplate> GDScriptLanguage::get_built_in_templates(StringName p_object) { @@ -318,10 +318,10 @@ void GDScriptLanguage::debug_get_stack_level_members(int p_level, List<String> * return; } - Ref<GDScript> script = instance->get_script(); - ERR_FAIL_COND(script.is_null()); + Ref<GDScript> scr = instance->get_script(); + ERR_FAIL_COND(scr.is_null()); - const HashMap<StringName, GDScript::MemberInfo> &mi = script->debug_get_member_indices(); + const HashMap<StringName, GDScript::MemberInfo> &mi = scr->debug_get_member_indices(); for (const KeyValue<StringName, GDScript::MemberInfo> &E : mi) { p_members->push_back(E.key); @@ -344,7 +344,7 @@ ScriptInstance *GDScriptLanguage::debug_get_stack_level_instance(int p_level) { void GDScriptLanguage::debug_get_globals(List<String> *p_globals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) { const HashMap<StringName, int> &name_idx = GDScriptLanguage::get_singleton()->get_global_map(); - const Variant *globals = GDScriptLanguage::get_singleton()->get_global_array(); + const Variant *gl_array = GDScriptLanguage::get_singleton()->get_global_array(); List<Pair<String, Variant>> cinfo; get_public_constants(&cinfo); @@ -365,7 +365,7 @@ void GDScriptLanguage::debug_get_globals(List<String> *p_globals, List<Variant> continue; } - const Variant &var = globals[E.value]; + const Variant &var = gl_array[E.value]; if (Object *obj = var) { if (Object::cast_to<GDScriptNativeClass>(obj)) { continue; @@ -766,7 +766,7 @@ static void _find_annotation_arguments(const GDScriptParser::AnnotationNode *p_a ScriptLanguage::CodeCompletionOption slider2("or_less", ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT); slider2.insert_text = slider2.display.quote(p_quote_style); r_result.insert(slider2.display, slider2); - ScriptLanguage::CodeCompletionOption slider3("no_slider", ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT); + ScriptLanguage::CodeCompletionOption slider3("hide_slider", ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT); slider3.insert_text = slider3.display.quote(p_quote_style); r_result.insert(slider3.display, slider3); } @@ -1205,8 +1205,8 @@ static void _find_identifiers(const GDScriptParser::CompletionContext &p_context _find_built_in_variants(r_result); static const char *_keywords[] = { - "false", "PI", "TAU", "INF", "NAN", "self", "true", "breakpoint", "tool", "super", - "break", "continue", "pass", "return", + "true", "false", "PI", "TAU", "INF", "NAN", "null", "self", "super", + "break", "breakpoint", "continue", "pass", "return", nullptr }; @@ -1218,7 +1218,7 @@ static void _find_identifiers(const GDScriptParser::CompletionContext &p_context } static const char *_keywords_with_space[] = { - "and", "in", "not", "or", "as", "class", "extends", "is", "func", "signal", "await", + "and", "not", "or", "in", "as", "class", "class_name", "extends", "is", "func", "signal", "await", "const", "enum", "static", "var", "if", "elif", "else", "for", "match", "while", nullptr }; @@ -2513,7 +2513,7 @@ static void _find_call_arguments(GDScriptParser::CompletionContext &p_context, c static void _find_call_arguments(GDScriptParser::CompletionContext &p_context, const GDScriptParser::Node *p_call, int p_argidx, HashMap<String, ScriptLanguage::CodeCompletionOption> &r_result, bool &r_forced, String &r_arghint) { if (p_call->type == GDScriptParser::Node::PRELOAD) { - if (p_argidx == 0 && bool(EditorSettings::get_singleton()->get("text_editor/completion/complete_file_paths"))) { + if (p_argidx == 0 && bool(EDITOR_GET("text_editor/completion/complete_file_paths"))) { _get_directory_contents(EditorFileSystem::get_singleton()->get_filesystem(), r_result); } @@ -2874,7 +2874,7 @@ static void _find_call_arguments(GDScriptParser::CompletionContext &p_context, c r_forced = true; } break; case GDScriptParser::COMPLETION_RESOURCE_PATH: { - if (EditorSettings::get_singleton()->get("text_editor/completion/complete_file_paths")) { + if (EDITOR_GET("text_editor/completion/complete_file_paths")) { _get_directory_contents(EditorFileSystem::get_singleton()->get_filesystem(), options); r_forced = true; } @@ -3105,8 +3105,9 @@ static Error _lookup_symbol_from_base(const GDScriptParser::DataType &p_base, co r_result.type = ScriptLanguage::LOOKUP_RESULT_SCRIPT_LOCATION; r_result.location = base_type.class_type->get_member(p_symbol).get_line(); r_result.class_path = base_type.script_path; - r_result.script = GDScriptCache::get_shallow_script(r_result.class_path); - return OK; + Error err = OK; + r_result.script = GDScriptCache::get_shallow_script(r_result.class_path, err); + return err; } base_type = base_type.class_type->base_type; } @@ -3356,17 +3357,17 @@ static Error _lookup_symbol_from_base(const GDScriptParser::DataType &p_base, co if (ProjectSettings::get_singleton()->has_autoload(p_symbol)) { const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(p_symbol); if (autoload.is_singleton) { - String script = autoload.path; - if (!script.ends_with(".gd")) { + String scr_path = autoload.path; + if (!scr_path.ends_with(".gd")) { // Not a script, try find the script anyway, // may have some success. - script = script.get_basename() + ".gd"; + scr_path = scr_path.get_basename() + ".gd"; } - if (FileAccess::exists(script)) { + if (FileAccess::exists(scr_path)) { r_result.type = ScriptLanguage::LOOKUP_RESULT_SCRIPT_LOCATION; r_result.location = 0; - r_result.script = ResourceLoader::load(script); + r_result.script = ResourceLoader::load(scr_path); return OK; } } diff --git a/modules/gdscript/gdscript_function.cpp b/modules/gdscript/gdscript_function.cpp index cd3b7d69c5..98b3e40f1b 100644 --- a/modules/gdscript/gdscript_function.cpp +++ b/modules/gdscript/gdscript_function.cpp @@ -142,7 +142,7 @@ GDScriptFunction::GDScriptFunction() { name = "<anonymous>"; #ifdef DEBUG_ENABLED { - MutexLock lock(GDScriptLanguage::get_singleton()->lock); + MutexLock lock(GDScriptLanguage::get_singleton()->mutex); GDScriptLanguage::get_singleton()->function_list.add(&function_list); } #endif @@ -155,7 +155,7 @@ GDScriptFunction::~GDScriptFunction() { #ifdef DEBUG_ENABLED - MutexLock lock(GDScriptLanguage::get_singleton()->lock); + MutexLock lock(GDScriptLanguage::get_singleton()->mutex); GDScriptLanguage::get_singleton()->function_list.remove(&function_list); #endif @@ -201,7 +201,7 @@ bool GDScriptFunctionState::is_valid(bool p_extended_check) const { } if (p_extended_check) { - MutexLock lock(GDScriptLanguage::get_singleton()->lock); + MutexLock lock(GDScriptLanguage::get_singleton()->mutex); // Script gone? if (!scripts_list.in_list()) { @@ -219,7 +219,7 @@ bool GDScriptFunctionState::is_valid(bool p_extended_check) const { Variant GDScriptFunctionState::resume(const Variant &p_arg) { ERR_FAIL_COND_V(!function, Variant()); { - MutexLock lock(GDScriptLanguage::singleton->lock); + MutexLock lock(GDScriptLanguage::singleton->mutex); if (!scripts_list.in_list()) { #ifdef DEBUG_ENABLED @@ -304,7 +304,7 @@ GDScriptFunctionState::GDScriptFunctionState() : GDScriptFunctionState::~GDScriptFunctionState() { { - MutexLock lock(GDScriptLanguage::singleton->lock); + MutexLock lock(GDScriptLanguage::singleton->mutex); scripts_list.remove_from_list(); instances_list.remove_from_list(); } diff --git a/modules/gdscript/gdscript_parser.cpp b/modules/gdscript/gdscript_parser.cpp index 888cd782fb..71cedb4f38 100644 --- a/modules/gdscript/gdscript_parser.cpp +++ b/modules/gdscript/gdscript_parser.cpp @@ -534,6 +534,7 @@ void GDScriptParser::end_statement(const String &p_context) { void GDScriptParser::parse_program() { head = alloc_node<ClassNode>(); + head->fqcn = script_path; current_class = head; // If we happen to parse an annotation before extends or class_name keywords, track it. @@ -646,6 +647,9 @@ GDScriptParser::ClassNode *GDScriptParser::parse_class() { if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier for the class name after "class".)")) { n_class->identifier = parse_identifier(); + if (n_class->outer) { + n_class->fqcn = n_class->outer->fqcn + "::" + n_class->identifier->name; + } } if (match(GDScriptTokenizer::Token::EXTENDS)) { @@ -684,6 +688,7 @@ GDScriptParser::ClassNode *GDScriptParser::parse_class() { void GDScriptParser::parse_class_name() { if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier for the global class name after "class_name".)")) { current_class->identifier = parse_identifier(); + current_class->fqcn = String(current_class->identifier->name); } if (match(GDScriptTokenizer::Token::EXTENDS)) { @@ -2932,11 +2937,16 @@ GDScriptParser::ExpressionNode *GDScriptParser::parse_call(ExpressionNode *p_pre // Allow for trailing comma. break; } + bool use_identifier_completion = current.cursor_place == GDScriptTokenizer::CURSOR_END || current.cursor_place == GDScriptTokenizer::CURSOR_MIDDLE; ExpressionNode *argument = parse_expression(false); if (argument == nullptr) { push_error(R"(Expected expression as the function argument.)"); } else { call->arguments.push_back(argument); + + if (argument->type == Node::IDENTIFIER && use_identifier_completion) { + completion_context.type = COMPLETION_IDENTIFIER; + } } ct = COMPLETION_CALL_ARGUMENTS; } while (match(GDScriptTokenizer::Token::COMMA)); @@ -3758,13 +3768,46 @@ bool GDScriptParser::export_annotations(const AnnotationNode *p_annotation, Node return false; } break; + case GDScriptParser::DataType::CLASS: + // Can assume type is a global GDScript class. + if (ClassDB::is_parent_class(export_type.native_type, SNAME("Resource"))) { + variable->export_info.type = Variant::OBJECT; + variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE; + variable->export_info.hint_string = export_type.class_type->identifier->name; + } else if (ClassDB::is_parent_class(export_type.native_type, SNAME("Node"))) { + variable->export_info.type = Variant::OBJECT; + variable->export_info.hint = PROPERTY_HINT_NODE_TYPE; + variable->export_info.hint_string = export_type.class_type->identifier->name; + } else { + push_error(R"(Export type can only be built-in, a resource, a node or an enum.)", variable); + return false; + } + + break; + case GDScriptParser::DataType::SCRIPT: { + StringName class_name; + if (export_type.script_type != nullptr && export_type.script_type.is_valid()) { + class_name = export_type.script_type->get_language()->get_global_class_name(export_type.script_type->get_path()); + } + if (class_name == StringName()) { + Ref<Script> script = ResourceLoader::load(export_type.script_path, SNAME("Script")); + if (script.is_valid()) { + class_name = script->get_language()->get_global_class_name(export_type.script_path); + } + } + if (class_name != StringName() && ClassDB::is_parent_class(ScriptServer::get_global_class_native_base(class_name), SNAME("Resource"))) { + variable->export_info.type = Variant::OBJECT; + variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE; + variable->export_info.hint_string = class_name; + } + } break; case GDScriptParser::DataType::ENUM: { variable->export_info.type = Variant::INT; variable->export_info.hint = PROPERTY_HINT_ENUM; String enum_hint_string; bool first = true; - for (const KeyValue<StringName, int> &E : export_type.enum_values) { + for (const KeyValue<StringName, int64_t> &E : export_type.enum_values) { if (!first) { enum_hint_string += ","; } else { @@ -3921,28 +3964,22 @@ GDScriptParser::DataType GDScriptParser::SuiteNode::Local::get_datatype() const } String GDScriptParser::SuiteNode::Local::get_name() const { - String name; switch (type) { case SuiteNode::Local::PARAMETER: - name = "parameter"; - break; + return "parameter"; case SuiteNode::Local::CONSTANT: - name = "constant"; - break; + return "constant"; case SuiteNode::Local::VARIABLE: - name = "variable"; - break; + return "variable"; case SuiteNode::Local::FOR_VARIABLE: - name = "for loop iterator"; - break; + return "for loop iterator"; case SuiteNode::Local::PATTERN_BIND: - name = "pattern_bind"; - break; + return "pattern_bind"; case SuiteNode::Local::UNDEFINED: - name = "<undefined>"; - break; + return "<undefined>"; + default: + return String(); } - return name; } String GDScriptParser::DataType::to_string() const { @@ -3974,7 +4011,7 @@ String GDScriptParser::DataType::to_string() const { if (is_meta_type) { return script_type->get_class_name().operator String(); } - String name = script_type->get_name(); + String name = script_type != nullptr ? script_type->get_name() : ""; if (!name.is_empty()) { return name; } diff --git a/modules/gdscript/gdscript_parser.h b/modules/gdscript/gdscript_parser.h index d4efab173b..d8f5b866aa 100644 --- a/modules/gdscript/gdscript_parser.h +++ b/modules/gdscript/gdscript_parser.h @@ -131,7 +131,7 @@ public: ClassNode *class_type = nullptr; MethodInfo method_info; // For callable/signals. - HashMap<StringName, int> enum_values; // For enums. + HashMap<StringName, int64_t> enum_values; // For enums. _FORCE_INLINE_ bool is_set() const { return kind != UNRESOLVED; } _FORCE_INLINE_ bool has_no_type() const { return type_source == UNDETECTED; } @@ -469,7 +469,7 @@ public: EnumNode *parent_enum = nullptr; int index = -1; bool resolved = false; - int value = 0; + int64_t value = 0; int line = 0; int leftmost_column = 0; int rightmost_column = 0; @@ -578,19 +578,19 @@ public: return m_enum->get_datatype(); case ENUM_VALUE: { // Always integer. - DataType type; - type.type_source = DataType::ANNOTATED_EXPLICIT; - type.kind = DataType::BUILTIN; - type.builtin_type = Variant::INT; - return type; + DataType out_type; + out_type.type_source = DataType::ANNOTATED_EXPLICIT; + out_type.kind = DataType::BUILTIN; + out_type.builtin_type = Variant::INT; + return out_type; } case SIGNAL: { - DataType type; - type.type_source = DataType::ANNOTATED_EXPLICIT; - type.kind = DataType::BUILTIN; - type.builtin_type = Variant::SIGNAL; + DataType out_type; + out_type.type_source = DataType::ANNOTATED_EXPLICIT; + out_type.kind = DataType::BUILTIN; + out_type.builtin_type = Variant::SIGNAL; // TODO: Add parameter info. - return type; + return out_type; } case GROUP: { return DataType(); diff --git a/modules/gdscript/gdscript_tokenizer.cpp b/modules/gdscript/gdscript_tokenizer.cpp index 6c17afe939..9bbfd7aece 100644 --- a/modules/gdscript/gdscript_tokenizer.cpp +++ b/modules/gdscript/gdscript_tokenizer.cpp @@ -516,15 +516,15 @@ GDScriptTokenizer::Token GDScriptTokenizer::potential_identifier() { _advance(); } - int length = _current - _start; + int len = _current - _start; - if (length == 1 && _peek(-1) == '_') { + if (len == 1 && _peek(-1) == '_') { // Lone underscore. return make_token(Token::UNDERSCORE); } - String name(_start, length); - if (length < MIN_KEYWORD_LENGTH || length > MAX_KEYWORD_LENGTH) { + String name(_start, len); + if (len < MIN_KEYWORD_LENGTH || len > MAX_KEYWORD_LENGTH) { // Cannot be a keyword, as the length doesn't match any. return make_identifier(name); } @@ -538,7 +538,7 @@ GDScriptTokenizer::Token GDScriptTokenizer::potential_identifier() { const int keyword_length = sizeof(keyword) - 1; \ static_assert(keyword_length <= MAX_KEYWORD_LENGTH, "There's a keyword longer than the defined maximum length"); \ static_assert(keyword_length >= MIN_KEYWORD_LENGTH, "There's a keyword shorter than the defined minimum length"); \ - if (keyword_length == length && name == keyword) { \ + if (keyword_length == len && name == keyword) { \ return make_token(token_type); \ } \ } @@ -551,13 +551,13 @@ GDScriptTokenizer::Token GDScriptTokenizer::potential_identifier() { } // Check if it's a special literal - if (length == 4) { + if (len == 4) { if (name == "true") { return make_literal(true); } else if (name == "null") { return make_literal(Variant()); } - } else if (length == 5) { + } else if (len == 5) { if (name == "false") { return make_literal(false); } @@ -725,8 +725,8 @@ GDScriptTokenizer::Token GDScriptTokenizer::number() { } // Create a string with the whole number. - int length = _current - _start; - String number = String(_start, length).replace("_", ""); + int len = _current - _start; + String number = String(_start, len).replace("_", ""); // Convert to the appropriate literal type. if (base == 16) { diff --git a/modules/gdscript/gdscript_vm.cpp b/modules/gdscript/gdscript_vm.cpp index afebe3c149..c73ba798aa 100644 --- a/modules/gdscript/gdscript_vm.cpp +++ b/modules/gdscript/gdscript_vm.cpp @@ -2216,7 +2216,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a gdfs->state.line = line; gdfs->state.script = _script; { - MutexLock lock(GDScriptLanguage::get_singleton()->lock); + MutexLock lock(GDScriptLanguage::get_singleton()->mutex); _script->pending_func_states.add(&gdfs->scripts_list); if (p_instance) { gdfs->state.instance = p_instance; diff --git a/modules/gdscript/gdscript_warning.cpp b/modules/gdscript/gdscript_warning.cpp index 1cae7bdfac..a0c107aa53 100644 --- a/modules/gdscript/gdscript_warning.cpp +++ b/modules/gdscript/gdscript_warning.cpp @@ -155,6 +155,10 @@ String GDScriptWarning::get_message() const { case INT_ASSIGNED_TO_ENUM: { return "Integer used when an enum value is expected. If this is intended cast the integer to the enum type."; } + case STATIC_CALLED_ON_INSTANCE: { + CHECK_SYMBOLS(2); + return vformat(R"(The function '%s()' is a static function but was called from an instance. Instead, it should be directly called from the type: '%s.%s()'.)", symbols[0], symbols[1], symbols[0]); + } case WARNING_MAX: break; // Can't happen, but silences warning } @@ -215,6 +219,7 @@ String GDScriptWarning::get_name_from_code(Code p_code) { "EMPTY_FILE", "SHADOWED_GLOBAL_IDENTIFIER", "INT_ASSIGNED_TO_ENUM", + "STATIC_CALLED_ON_INSTANCE", }; static_assert((sizeof(names) / sizeof(*names)) == WARNING_MAX, "Amount of warning types don't match the amount of warning names."); diff --git a/modules/gdscript/gdscript_warning.h b/modules/gdscript/gdscript_warning.h index a639e7b44e..7e4e975510 100644 --- a/modules/gdscript/gdscript_warning.h +++ b/modules/gdscript/gdscript_warning.h @@ -78,6 +78,7 @@ public: EMPTY_FILE, // A script file is empty. SHADOWED_GLOBAL_IDENTIFIER, // A global class or function has the same name as variable. INT_ASSIGNED_TO_ENUM, // An integer value was assigned to an enum-typed variable without casting. + STATIC_CALLED_ON_INSTANCE, // A static method was called on an instance of a class instead of on the class itself. WARNING_MAX, }; diff --git a/modules/gdscript/language_server/gdscript_extend_parser.cpp b/modules/gdscript/language_server/gdscript_extend_parser.cpp index 46a9b33eb0..de3becbaf8 100644 --- a/modules/gdscript/language_server/gdscript_extend_parser.cpp +++ b/modules/gdscript/language_server/gdscript_extend_parser.cpp @@ -38,8 +38,8 @@ void ExtendGDScriptParser::update_diagnostics() { diagnostics.clear(); - const List<ParserError> &errors = get_errors(); - for (const ParserError &error : errors) { + const List<ParserError> &parser_errors = get_errors(); + for (const ParserError &error : parser_errors) { lsp::Diagnostic diagnostic; diagnostic.severity = lsp::DiagnosticSeverity::Error; diagnostic.message = error.message; @@ -47,9 +47,9 @@ void ExtendGDScriptParser::update_diagnostics() { diagnostic.code = -1; lsp::Range range; lsp::Position pos; - const PackedStringArray lines = get_lines(); - int line = CLAMP(LINE_NUMBER_TO_INDEX(error.line), 0, lines.size() - 1); - const String &line_text = lines[line]; + const PackedStringArray line_array = get_lines(); + int line = CLAMP(LINE_NUMBER_TO_INDEX(error.line), 0, line_array.size() - 1); + const String &line_text = line_array[line]; pos.line = line; pos.character = line_text.length() - line_text.strip_edges(true, false).length(); range.start = pos; @@ -59,8 +59,8 @@ void ExtendGDScriptParser::update_diagnostics() { diagnostics.push_back(diagnostic); } - const List<GDScriptWarning> &warnings = get_warnings(); - for (const GDScriptWarning &warning : warnings) { + const List<GDScriptWarning> &parser_warnings = get_warnings(); + for (const GDScriptWarning &warning : parser_warnings) { lsp::Diagnostic diagnostic; diagnostic.severity = lsp::DiagnosticSeverity::Warning; diagnostic.message = "(" + warning.get_name() + "): " + warning.get_message(); @@ -83,8 +83,7 @@ void ExtendGDScriptParser::update_diagnostics() { void ExtendGDScriptParser::update_symbols() { members.clear(); - const GDScriptParser::Node *head = get_tree(); - if (const GDScriptParser::ClassNode *gdclass = dynamic_cast<const GDScriptParser::ClassNode *>(head)) { + if (const GDScriptParser::ClassNode *gdclass = dynamic_cast<const GDScriptParser::ClassNode *>(get_tree())) { parse_class_symbol(gdclass, class_symbol); for (int i = 0; i < class_symbol.children.size(); i++) { @@ -107,26 +106,26 @@ void ExtendGDScriptParser::update_symbols() { void ExtendGDScriptParser::update_document_links(const String &p_code) { document_links.clear(); - GDScriptTokenizer tokenizer; + GDScriptTokenizer scr_tokenizer; Ref<FileAccess> fs = FileAccess::create(FileAccess::ACCESS_RESOURCES); - tokenizer.set_source_code(p_code); + scr_tokenizer.set_source_code(p_code); while (true) { - GDScriptTokenizer::Token token = tokenizer.scan(); + GDScriptTokenizer::Token token = scr_tokenizer.scan(); if (token.type == GDScriptTokenizer::Token::TK_EOF) { break; } else if (token.type == GDScriptTokenizer::Token::LITERAL) { const Variant &const_val = token.literal; if (const_val.get_type() == Variant::STRING) { - String path = const_val; - bool exists = fs->file_exists(path); + String scr_path = const_val; + bool exists = fs->file_exists(scr_path); if (!exists) { - path = get_path().get_base_dir() + "/" + path; - exists = fs->file_exists(path); + scr_path = get_path().get_base_dir() + "/" + scr_path; + exists = fs->file_exists(scr_path); } if (exists) { String value = const_val; lsp::DocumentLink link; - link.target = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_uri(path); + link.target = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_uri(scr_path); link.range.start.line = LINE_NUMBER_TO_INDEX(token.start_line); link.range.end.line = LINE_NUMBER_TO_INDEX(token.end_line); link.range.start.character = LINE_NUMBER_TO_INDEX(token.start_column); @@ -437,11 +436,11 @@ String ExtendGDScriptParser::parse_documentation(int p_line, bool p_docs_down) { if (!p_docs_down) { // inline comment String inline_comment = lines[p_line]; - int comment_start = inline_comment.find("#"); + int comment_start = inline_comment.find("##"); if (comment_start != -1) { inline_comment = inline_comment.substr(comment_start, inline_comment.length()).strip_edges(); if (inline_comment.length() > 1) { - doc_lines.push_back(inline_comment.substr(1, inline_comment.length())); + doc_lines.push_back(inline_comment.substr(2, inline_comment.length())); } } } @@ -454,8 +453,8 @@ String ExtendGDScriptParser::parse_documentation(int p_line, bool p_docs_down) { } String line_comment = lines[i].strip_edges(true, false); - if (line_comment.begins_with("#")) { - line_comment = line_comment.substr(1, line_comment.length()); + if (line_comment.begins_with("##")) { + line_comment = line_comment.substr(2, line_comment.length()); if (p_docs_down) { doc_lines.push_back(line_comment); } else { @@ -731,7 +730,7 @@ Dictionary ExtendGDScriptParser::dump_class_api(const GDScriptParser::ClassNode Array nested_classes; Array constants; - Array members; + Array class_members; Array signals; Array methods; Array static_functions; @@ -792,7 +791,7 @@ Dictionary ExtendGDScriptParser::dump_class_api(const GDScriptParser::ClassNode api["signature"] = symbol->detail; api["description"] = symbol->documentation; } - members.push_back(api); + class_members.push_back(api); } break; case ClassNode::Member::SIGNAL: { Dictionary api; @@ -824,7 +823,7 @@ Dictionary ExtendGDScriptParser::dump_class_api(const GDScriptParser::ClassNode class_api["sub_classes"] = nested_classes; class_api["constants"] = constants; - class_api["members"] = members; + class_api["members"] = class_members; class_api["signals"] = signals; class_api["methods"] = methods; class_api["static_functions"] = static_functions; @@ -834,8 +833,7 @@ Dictionary ExtendGDScriptParser::dump_class_api(const GDScriptParser::ClassNode Dictionary ExtendGDScriptParser::generate_api() const { Dictionary api; - const GDScriptParser::Node *head = get_tree(); - if (const GDScriptParser::ClassNode *gdclass = dynamic_cast<const GDScriptParser::ClassNode *>(head)) { + if (const GDScriptParser::ClassNode *gdclass = dynamic_cast<const GDScriptParser::ClassNode *>(get_tree())) { api = dump_class_api(gdclass); } return api; diff --git a/modules/gdscript/language_server/gdscript_language_server.cpp b/modules/gdscript/language_server/gdscript_language_server.cpp index ead4ef1987..38bea314a0 100644 --- a/modules/gdscript/language_server/gdscript_language_server.cpp +++ b/modules/gdscript/language_server/gdscript_language_server.cpp @@ -61,12 +61,12 @@ void GDScriptLanguageServer::_notification(int p_what) { } break; case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { - String host = String(_EDITOR_GET("network/language_server/remote_host")); - int port = (int)_EDITOR_GET("network/language_server/remote_port"); - bool use_thread = (bool)_EDITOR_GET("network/language_server/use_thread"); - if (host != this->host || port != this->port || use_thread != this->use_thread) { - this->stop(); - this->start(); + String remote_host = String(_EDITOR_GET("network/language_server/remote_host")); + int remote_port = (int)_EDITOR_GET("network/language_server/remote_port"); + bool remote_use_thread = (bool)_EDITOR_GET("network/language_server/use_thread"); + if (remote_host != host || remote_port != port || remote_use_thread != use_thread) { + stop(); + start(); } } break; } diff --git a/modules/gdscript/language_server/gdscript_text_document.cpp b/modules/gdscript/language_server/gdscript_text_document.cpp index 5ad9680ea0..3905e28bcb 100644 --- a/modules/gdscript/language_server/gdscript_text_document.cpp +++ b/modules/gdscript/language_server/gdscript_text_document.cpp @@ -42,6 +42,7 @@ void GDScriptTextDocument::_bind_methods() { ClassDB::bind_method(D_METHOD("didOpen"), &GDScriptTextDocument::didOpen); ClassDB::bind_method(D_METHOD("didClose"), &GDScriptTextDocument::didClose); ClassDB::bind_method(D_METHOD("didChange"), &GDScriptTextDocument::didChange); + ClassDB::bind_method(D_METHOD("willSaveWaitUntil"), &GDScriptTextDocument::willSaveWaitUntil); ClassDB::bind_method(D_METHOD("didSave"), &GDScriptTextDocument::didSave); ClassDB::bind_method(D_METHOD("nativeSymbol"), &GDScriptTextDocument::nativeSymbol); ClassDB::bind_method(D_METHOD("documentSymbol"), &GDScriptTextDocument::documentSymbol); @@ -81,6 +82,16 @@ void GDScriptTextDocument::didChange(const Variant &p_param) { sync_script_content(doc.uri, doc.text); } +void GDScriptTextDocument::willSaveWaitUntil(const Variant &p_param) { + lsp::TextDocumentItem doc = load_document_item(p_param); + + String path = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_path(doc.uri); + Ref<Script> scr = ResourceLoader::load(path); + if (scr.is_valid()) { + ScriptEditor::get_singleton()->clear_docs_from_script(scr); + } +} + void GDScriptTextDocument::didSave(const Variant &p_param) { lsp::TextDocumentItem doc = load_document_item(p_param); Dictionary dict = p_param; @@ -88,11 +99,16 @@ void GDScriptTextDocument::didSave(const Variant &p_param) { sync_script_content(doc.uri, text); - /*String path = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_path(doc.uri); - - Ref<GDScript> script = ResourceLoader::load(path); - script->load_source_code(path); - script->reload(true);*/ + String path = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_path(doc.uri); + Ref<GDScript> scr = ResourceLoader::load(path); + if (scr.is_valid() && (scr->load_source_code(path) == OK)) { + if (scr->is_tool()) { + scr->get_language()->reload_tool_script(scr, true); + } else { + scr->reload(true); + } + ScriptEditor::get_singleton()->update_docs_from_script(scr); + } } lsp::TextDocumentItem GDScriptTextDocument::load_document_item(const Variant &p_param) { @@ -213,8 +229,8 @@ Array GDScriptTextDocument::completion(const Dictionary &p_params) { arr = native_member_completions.duplicate(); for (KeyValue<String, ExtendGDScriptParser *> &E : GDScriptLanguageProtocol::get_singleton()->get_workspace()->scripts) { - ExtendGDScriptParser *script = E.value; - const Array &items = script->get_member_completions(); + ExtendGDScriptParser *scr = E.value; + const Array &items = scr->get_member_completions(); const int start_size = arr.size(); arr.resize(start_size + items.size()); @@ -417,13 +433,6 @@ void GDScriptTextDocument::sync_script_content(const String &p_path, const Strin GDScriptLanguageProtocol::get_singleton()->get_workspace()->parse_script(path, p_content); EditorFileSystem::get_singleton()->update_file(path); - Error error; - Ref<GDScript> script = ResourceLoader::load(path, "", ResourceFormatLoader::CACHE_MODE_REUSE, &error); - if (error == OK) { - if (script->load_source_code(path) == OK) { - script->reload(true); - } - } } void GDScriptTextDocument::show_native_symbol_in_editor(const String &p_symbol_id) { diff --git a/modules/gdscript/language_server/gdscript_text_document.h b/modules/gdscript/language_server/gdscript_text_document.h index 87bc08a34e..456c7d71fe 100644 --- a/modules/gdscript/language_server/gdscript_text_document.h +++ b/modules/gdscript/language_server/gdscript_text_document.h @@ -45,6 +45,7 @@ protected: void didOpen(const Variant &p_param); void didClose(const Variant &p_param); void didChange(const Variant &p_param); + void willSaveWaitUntil(const Variant &p_param); void didSave(const Variant &p_param); void sync_script_content(const String &p_path, const String &p_content); diff --git a/modules/gdscript/language_server/gdscript_workspace.cpp b/modules/gdscript/language_server/gdscript_workspace.cpp index 16461b0a6c..390460bed9 100644 --- a/modules/gdscript/language_server/gdscript_workspace.cpp +++ b/modules/gdscript/language_server/gdscript_workspace.cpp @@ -55,14 +55,14 @@ void GDScriptWorkspace::_bind_methods() { } void GDScriptWorkspace::apply_new_signal(Object *obj, String function, PackedStringArray args) { - Ref<Script> script = obj->get_script(); + Ref<Script> scr = obj->get_script(); - if (script->get_language()->get_name() != "GDScript") { + if (scr->get_language()->get_name() != "GDScript") { return; } String function_signature = "func " + function; - String source = script->get_source_code(); + String source = scr->get_source_code(); if (source.contains(function_signature)) { return; @@ -98,7 +98,7 @@ void GDScriptWorkspace::apply_new_signal(Object *obj, String function, PackedStr text_edit.newText = function_body; - String uri = get_file_uri(script->get_path()); + String uri = get_file_uri(scr->get_path()); lsp::ApplyWorkspaceEditParams params; params.edit.add_edit(uri, text_edit); @@ -118,12 +118,12 @@ void GDScriptWorkspace::did_delete_files(const Dictionary &p_params) { void GDScriptWorkspace::remove_cache_parser(const String &p_path) { HashMap<String, ExtendGDScriptParser *>::Iterator parser = parse_results.find(p_path); - HashMap<String, ExtendGDScriptParser *>::Iterator script = scripts.find(p_path); - if (parser && script) { - if (script->value && script->value == parser->value) { - memdelete(script->value); + HashMap<String, ExtendGDScriptParser *>::Iterator scr = scripts.find(p_path); + if (parser && scr) { + if (scr->value && scr->value == parser->value) { + memdelete(scr->value); } else { - memdelete(script->value); + memdelete(scr->value); memdelete(parser->value); } parse_results.erase(p_path); @@ -131,8 +131,8 @@ void GDScriptWorkspace::remove_cache_parser(const String &p_path) { } else if (parser) { memdelete(parser->value); parse_results.erase(p_path); - } else if (script) { - memdelete(script->value); + } else if (scr) { + memdelete(scr->value); scripts.erase(p_path); } } @@ -587,8 +587,8 @@ void GDScriptWorkspace::completion(const lsp::CompletionParams &p_params, List<S while (!stack.is_empty()) { current = Object::cast_to<Node>(stack.pop_back()); - Ref<GDScript> script = current->get_script(); - if (script.is_valid() && script->get_path() == path) { + Ref<GDScript> scr = current->get_script(); + if (scr.is_valid() && scr->get_path() == path) { break; } for (int i = 0; i < current->get_child_count(); ++i) { @@ -596,8 +596,8 @@ void GDScriptWorkspace::completion(const lsp::CompletionParams &p_params, List<S } } - Ref<GDScript> script = current->get_script(); - if (!script.is_valid() || script->get_path() != path) { + Ref<GDScript> scr = current->get_script(); + if (!scr.is_valid() || scr->get_path() != path) { current = owner_scene_node; } } @@ -691,13 +691,13 @@ void GDScriptWorkspace::resolve_related_symbols(const lsp::TextDocumentPositionP } for (const KeyValue<String, ExtendGDScriptParser *> &E : scripts) { - const ExtendGDScriptParser *script = E.value; - const ClassMembers &members = script->get_members(); + const ExtendGDScriptParser *scr = E.value; + const ClassMembers &members = scr->get_members(); if (const lsp::DocumentSymbol *const *symbol = members.getptr(symbol_identifier)) { r_list.push_back(*symbol); } - for (const KeyValue<String, ClassMembers> &F : script->get_inner_classes()) { + for (const KeyValue<String, ClassMembers> &F : scr->get_inner_classes()) { const ClassMembers *inner_class = &F.value; if (const lsp::DocumentSymbol *const *symbol = inner_class->getptr(symbol_identifier)) { r_list.push_back(*symbol); diff --git a/modules/gdscript/language_server/godot_lsp.h b/modules/gdscript/language_server/godot_lsp.h index fbd40796c4..024da1cab7 100644 --- a/modules/gdscript/language_server/godot_lsp.h +++ b/modules/gdscript/language_server/godot_lsp.h @@ -546,7 +546,7 @@ struct TextDocumentSyncOptions { * If present will save wait until requests are sent to the server. If omitted the request should not be * sent. */ - bool willSaveWaitUntil = false; + bool willSaveWaitUntil = true; /** * If present save notifications are sent to the server. If omitted the notification should not be diff --git a/modules/gdscript/tests/gdscript_test_runner.cpp b/modules/gdscript/tests/gdscript_test_runner.cpp index 6c346acb7e..1ccbf9d150 100644 --- a/modules/gdscript/tests/gdscript_test_runner.cpp +++ b/modules/gdscript/tests/gdscript_test_runner.cpp @@ -461,7 +461,6 @@ GDScriptTest::TestResult GDScriptTest::execute_test_code(bool p_is_generating) { Ref<GDScript> script; script.instantiate(); script->set_path(source_file); - script->set_script_path(source_file); err = script->load_source_code(source_file); if (err != OK) { enable_stdout(); @@ -479,9 +478,9 @@ GDScriptTest::TestResult GDScriptTest::execute_test_code(bool p_is_generating) { result.output = get_text_for_status(result.status) + "\n"; const List<GDScriptParser::ParserError> &errors = parser.get_errors(); - for (const GDScriptParser::ParserError &E : errors) { - result.output += E.message + "\n"; // TODO: line, column? - break; // Only the first error since the following might be cascading. + if (!errors.is_empty()) { + // Only the first error since the following might be cascading. + result.output += errors[0].message + "\n"; // TODO: line, column? } if (!p_is_generating) { result.passed = check_output(result.output); @@ -498,9 +497,9 @@ GDScriptTest::TestResult GDScriptTest::execute_test_code(bool p_is_generating) { result.output = get_text_for_status(result.status) + "\n"; const List<GDScriptParser::ParserError> &errors = parser.get_errors(); - for (const GDScriptParser::ParserError &E : errors) { - result.output += E.message + "\n"; // TODO: line, column? - break; // Only the first error since the following might be cascading. + if (!errors.is_empty()) { + // Only the first error since the following might be cascading. + result.output += errors[0].message + "\n"; // TODO: line, column? } if (!p_is_generating) { result.passed = check_output(result.output); diff --git a/modules/gdscript/tests/scripts/analyzer/features/external_inner_base.gd b/modules/gdscript/tests/scripts/analyzer/features/external_inner_base.gd new file mode 100644 index 0000000000..3f9bfe189c --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/external_inner_base.gd @@ -0,0 +1,4 @@ +extends "inner_base.gd".InnerA.InnerAB + +func test(): + super.test() diff --git a/modules/gdscript/tests/scripts/analyzer/features/external_inner_base.out b/modules/gdscript/tests/scripts/analyzer/features/external_inner_base.out new file mode 100644 index 0000000000..62f1383392 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/external_inner_base.out @@ -0,0 +1,3 @@ +GDTEST_OK +InnerA.InnerAB.test +InnerB.test diff --git a/modules/gdscript/tests/scripts/analyzer/features/inner_base.gd b/modules/gdscript/tests/scripts/analyzer/features/inner_base.gd new file mode 100644 index 0000000000..a825b59255 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/inner_base.gd @@ -0,0 +1,18 @@ +extends InnerA + +func test(): + super.test() + +class InnerA extends InnerAB: + func test(): + print("InnerA.test") + super.test() + + class InnerAB extends InnerB: + func test(): + print("InnerA.InnerAB.test") + super.test() + +class InnerB: + func test(): + print("InnerB.test") diff --git a/modules/gdscript/tests/scripts/analyzer/features/inner_base.out b/modules/gdscript/tests/scripts/analyzer/features/inner_base.out new file mode 100644 index 0000000000..ddd5ffcfd3 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/inner_base.out @@ -0,0 +1,4 @@ +GDTEST_OK +InnerA.test +InnerA.InnerAB.test +InnerB.test diff --git a/modules/gdscript/tests/scripts/parser/features/class.gd b/modules/gdscript/tests/scripts/parser/features/class.gd index 6652f85ad9..af24b32322 100644 --- a/modules/gdscript/tests/scripts/parser/features/class.gd +++ b/modules/gdscript/tests/scripts/parser/features/class.gd @@ -21,5 +21,5 @@ func test(): assert(test_sub.number == 25) # From Test. assert(test_sub.other_string == "bye") # From TestSub. - TestConstructor.new() - TestConstructor.new(500) + var _test_constructor = TestConstructor.new() + _test_constructor = TestConstructor.new(500) diff --git a/modules/gdscript/tests/scripts/parser/features/dictionary.out b/modules/gdscript/tests/scripts/parser/features/dictionary.out index 5f999f573a..e1eeb46f78 100644 --- a/modules/gdscript/tests/scripts/parser/features/dictionary.out +++ b/modules/gdscript/tests/scripts/parser/features/dictionary.out @@ -7,8 +7,8 @@ null false empty array zero Vector2i -{22:{4:["nesting", "arrays"]}} -{4:["nesting", "arrays"]} +{ 22: { 4: ["nesting", "arrays"] } } +{ 4: ["nesting", "arrays"] } ["nesting", "arrays"] nesting arrays diff --git a/modules/gdscript/tests/scripts/parser/features/dictionary_lua_style.out b/modules/gdscript/tests/scripts/parser/features/dictionary_lua_style.out index 5143d040a9..553d40d953 100644 --- a/modules/gdscript/tests/scripts/parser/features/dictionary_lua_style.out +++ b/modules/gdscript/tests/scripts/parser/features/dictionary_lua_style.out @@ -1,2 +1,2 @@ GDTEST_OK -{"a":1, "b":2, "with spaces":3, "2":4} +{ "a": 1, "b": 2, "with spaces": 3, "2": 4 } diff --git a/modules/gdscript/tests/scripts/parser/features/dictionary_mixed_syntax.out b/modules/gdscript/tests/scripts/parser/features/dictionary_mixed_syntax.out index dd28609850..cf79845f53 100644 --- a/modules/gdscript/tests/scripts/parser/features/dictionary_mixed_syntax.out +++ b/modules/gdscript/tests/scripts/parser/features/dictionary_mixed_syntax.out @@ -1,2 +1,2 @@ GDTEST_OK -{"hello":{"world":{"is":"beautiful"}}} +{ "hello": { "world": { "is": "beautiful" } } } diff --git a/modules/gdscript/tests/scripts/parser/features/nested_dictionary.out b/modules/gdscript/tests/scripts/parser/features/nested_dictionary.out index 8b8c33202f..508f0ff217 100644 --- a/modules/gdscript/tests/scripts/parser/features/nested_dictionary.out +++ b/modules/gdscript/tests/scripts/parser/features/nested_dictionary.out @@ -1,5 +1,5 @@ GDTEST_OK -{8:{"key":"value"}} -{"key":"value"} +{ 8: { "key": "value" } } +{ "key": "value" } value value diff --git a/modules/gdscript/tests/scripts/parser/warnings/return_value_discarded.out b/modules/gdscript/tests/scripts/parser/warnings/return_value_discarded.out index d73c5eb7cd..13f759dd46 100644 --- a/modules/gdscript/tests/scripts/parser/warnings/return_value_discarded.out +++ b/modules/gdscript/tests/scripts/parser/warnings/return_value_discarded.out @@ -1 +1,5 @@ GDTEST_OK +>> WARNING +>> Line: 6 +>> RETURN_VALUE_DISCARDED +>> The function 'i_return_int()' returns a value, but this value is never used. diff --git a/modules/gdscript/tests/scripts/parser/warnings/static_called_on_instance.gd b/modules/gdscript/tests/scripts/parser/warnings/static_called_on_instance.gd new file mode 100644 index 0000000000..29d8501b78 --- /dev/null +++ b/modules/gdscript/tests/scripts/parser/warnings/static_called_on_instance.gd @@ -0,0 +1,11 @@ +class Player: + var x = 3 + +func test(): + # These should not emit a warning. + var _player = Player.new() + print(String.num_uint64(8589934592)) # 2 ^ 33 + + # This should emit a warning. + var some_string = String() + print(some_string.num_uint64(8589934592)) # 2 ^ 33 diff --git a/modules/gdscript/tests/scripts/parser/warnings/static_called_on_instance.out b/modules/gdscript/tests/scripts/parser/warnings/static_called_on_instance.out new file mode 100644 index 0000000000..3933a35178 --- /dev/null +++ b/modules/gdscript/tests/scripts/parser/warnings/static_called_on_instance.out @@ -0,0 +1,7 @@ +GDTEST_OK +>> WARNING +>> Line: 11 +>> STATIC_CALLED_ON_INSTANCE +>> The function 'num_uint64()' is a static function but was called from an instance. Instead, it should be directly called from the type: 'String.num_uint64()'. +8589934592 +8589934592 diff --git a/modules/gdscript/tests/scripts/runtime/features/chain_assignment_works.out b/modules/gdscript/tests/scripts/runtime/features/chain_assignment_works.out index 5e7ccf534a..22929bf636 100644 --- a/modules/gdscript/tests/scripts/runtime/features/chain_assignment_works.out +++ b/modules/gdscript/tests/scripts/runtime/features/chain_assignment_works.out @@ -1,6 +1,6 @@ GDTEST_OK -{1:(2, 0)} -{3:(4, 0)} +{ 1: (2, 0) } +{ 3: (4, 0) } [[(5, 0)]] [[(6, 0)]] [[(7, 0)]] diff --git a/modules/gdscript/tests/scripts/runtime/features/compare-builtin-equals-null.gd b/modules/gdscript/tests/scripts/runtime/features/compare-builtin-equals-null.gd index c6645c2c34..809d0d28a9 100644 --- a/modules/gdscript/tests/scripts/runtime/features/compare-builtin-equals-null.gd +++ b/modules/gdscript/tests/scripts/runtime/features/compare-builtin-equals-null.gd @@ -69,6 +69,10 @@ func test(): value = Transform3D() print(value == null) + # Projection + value = Projection() + print(value == null) + # Color value = Color() print(value == null) diff --git a/modules/gdscript/tests/scripts/runtime/features/compare-builtin-equals-null.out b/modules/gdscript/tests/scripts/runtime/features/compare-builtin-equals-null.out index 639f6027b9..27423ab8e7 100644 --- a/modules/gdscript/tests/scripts/runtime/features/compare-builtin-equals-null.out +++ b/modules/gdscript/tests/scripts/runtime/features/compare-builtin-equals-null.out @@ -33,3 +33,4 @@ false false false false +false diff --git a/modules/gdscript/tests/scripts/runtime/features/compare-builtin-not-equals-null.gd b/modules/gdscript/tests/scripts/runtime/features/compare-builtin-not-equals-null.gd index ee622bf22f..f46afb0f18 100644 --- a/modules/gdscript/tests/scripts/runtime/features/compare-builtin-not-equals-null.gd +++ b/modules/gdscript/tests/scripts/runtime/features/compare-builtin-not-equals-null.gd @@ -69,6 +69,10 @@ func test(): value = Transform3D() print(value != null) + # Projection + value = Projection() + print(value != null) + # Color value = Color() print(value != null) diff --git a/modules/gdscript/tests/scripts/runtime/features/compare-builtin-not-equals-null.out b/modules/gdscript/tests/scripts/runtime/features/compare-builtin-not-equals-null.out index d1e332afba..a11c47854a 100644 --- a/modules/gdscript/tests/scripts/runtime/features/compare-builtin-not-equals-null.out +++ b/modules/gdscript/tests/scripts/runtime/features/compare-builtin-not-equals-null.out @@ -33,3 +33,4 @@ true true true true +true diff --git a/modules/gdscript/tests/scripts/runtime/features/range_optimized_in_for_has_int_iterator.gd b/modules/gdscript/tests/scripts/runtime/features/range_optimized_in_for_has_int_iterator.gd new file mode 100644 index 0000000000..e24137a20d --- /dev/null +++ b/modules/gdscript/tests/scripts/runtime/features/range_optimized_in_for_has_int_iterator.gd @@ -0,0 +1,60 @@ +func test(): + # All combinations of 1/2/3 arguments, each being int/float. + + for number in range(5): + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + for number in range(5.2): + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + + for number in range(1, 5): + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + for number in range(1, 5.2): + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + for number in range(1.2, 5): + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + for number in range(1.2, 5.2): + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + + for number in range(1, 5, 2): + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + for number in range(1, 5, 2.2): + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + for number in range(1, 5.2, 2): + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + for number in range(1, 5.2, 2.2): + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + for number in range(1.2, 5, 2): + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + for number in range(1.2, 5.2, 2): + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + for number in range(1.2, 5, 2.2): + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + for number in range(1.2, 5.2, 2.2): + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") diff --git a/modules/gdscript/tests/scripts/runtime/features/range_optimized_in_for_has_int_iterator.out b/modules/gdscript/tests/scripts/runtime/features/range_optimized_in_for_has_int_iterator.out new file mode 100644 index 0000000000..d73c5eb7cd --- /dev/null +++ b/modules/gdscript/tests/scripts/runtime/features/range_optimized_in_for_has_int_iterator.out @@ -0,0 +1 @@ +GDTEST_OK diff --git a/modules/gdscript/tests/scripts/runtime/features/range_returns_ints.gd b/modules/gdscript/tests/scripts/runtime/features/range_returns_ints.gd new file mode 100644 index 0000000000..63c3b84305 --- /dev/null +++ b/modules/gdscript/tests/scripts/runtime/features/range_returns_ints.gd @@ -0,0 +1,77 @@ +func test(): + # All combinations of 1/2/3 arguments, each being int/float. + # Store result in variable to ensure actual array is created (avoid `for` + `range` optimization). + + var result + + result = range(5) + for number in result: + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + result = range(5.2) + for number in result: + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + + result = range(1, 5) + for number in result: + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + result = range(1, 5.2) + for number in result: + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + result = range(1.2, 5) + for number in result: + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + result = range(1.2, 5.2) + for number in result: + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + + result = range(1, 5, 2) + for number in result: + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + result = range(1, 5, 2.2) + for number in result: + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + result = range(1, 5.2, 2) + for number in result: + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + result = range(1, 5.2, 2.2) + for number in result: + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + result = range(1.2, 5, 2) + for number in result: + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + result = range(1.2, 5.2, 2) + for number in result: + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + result = range(1.2, 5, 2.2) + for number in result: + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") + + result = range(1.2, 5.2, 2.2) + for number in result: + if typeof(number) != TYPE_INT: + print("Number returned from `range` was not an int!") diff --git a/modules/gdscript/tests/scripts/runtime/features/range_returns_ints.out b/modules/gdscript/tests/scripts/runtime/features/range_returns_ints.out new file mode 100644 index 0000000000..d73c5eb7cd --- /dev/null +++ b/modules/gdscript/tests/scripts/runtime/features/range_returns_ints.out @@ -0,0 +1 @@ +GDTEST_OK diff --git a/modules/gdscript/tests/scripts/runtime/features/stringify.out b/modules/gdscript/tests/scripts/runtime/features/stringify.out index d4468737a5..1f33de00cc 100644 --- a/modules/gdscript/tests/scripts/runtime/features/stringify.out +++ b/modules/gdscript/tests/scripts/runtime/features/stringify.out @@ -21,7 +21,7 @@ hello/world RID(0) Node::get_name Node::[signal]property_list_changed -{"hello":123} +{ "hello": 123 } ["hello", 123] [255, 0, 1] [-1, 0, 1] diff --git a/modules/glslang/glslang_resource_limits.h b/modules/glslang/glslang_resource_limits.h index 02d3daff07..0847f2d720 100644 --- a/modules/glslang/glslang_resource_limits.h +++ b/modules/glslang/glslang_resource_limits.h @@ -129,6 +129,15 @@ const TBuiltInResource DefaultTBuiltInResource = { /* .maxTaskWorkGroupSizeY_NV = */ 1, /* .maxTaskWorkGroupSizeZ_NV = */ 1, /* .maxMeshViewCountNV = */ 4, + /* .maxMeshOutputVerticesEXT = */ 256, + /* .maxMeshOutputPrimitivesEXT = */ 256, + /* .maxMeshWorkGroupSizeX_EXT = */ 128, + /* .maxMeshWorkGroupSizeY_EXT = */ 128, + /* .maxMeshWorkGroupSizeZ_EXT = */ 128, + /* .maxTaskWorkGroupSizeX_EXT = */ 128, + /* .maxTaskWorkGroupSizeY_EXT = */ 128, + /* .maxTaskWorkGroupSizeZ_EXT = */ 128, + /* .maxMeshViewCountEXT = */ 4, /* .maxDualSourceDrawBuffersEXT = */ 1, /* .limits = */ { diff --git a/modules/glslang/register_types.cpp b/modules/glslang/register_types.cpp index b1c2140039..53ec0fde34 100644 --- a/modules/glslang/register_types.cpp +++ b/modules/glslang/register_types.cpp @@ -53,7 +53,6 @@ static Vector<uint8_t> _compile_shader_glsl(RenderingDevice::ShaderStage p_stage }; int ClientInputSemanticsVersion = 100; // maps to, say, #define VULKAN 100 - bool check_subgroup_support = true; // assume we support subgroups glslang::EShTargetClientVersion ClientVersion = glslang::EShTargetVulkan_1_2; glslang::EShTargetLanguageVersion TargetVersion = glslang::EShTargetSpv_1_5; @@ -63,7 +62,6 @@ static Vector<uint8_t> _compile_shader_glsl(RenderingDevice::ShaderStage p_stage if (capabilities->version_major == 1 && capabilities->version_minor == 0) { ClientVersion = glslang::EShTargetVulkan_1_0; TargetVersion = glslang::EShTargetSpv_1_0; - check_subgroup_support = false; // subgroups are not supported in Vulkan 1.0 } else if (capabilities->version_major == 1 && capabilities->version_minor == 1) { ClientVersion = glslang::EShTargetVulkan_1_1; TargetVersion = glslang::EShTargetSpv_1_3; @@ -88,7 +86,7 @@ static Vector<uint8_t> _compile_shader_glsl(RenderingDevice::ShaderStage p_stage shader.setEnvClient(glslang::EShClientVulkan, ClientVersion); shader.setEnvTarget(glslang::EShTargetSpv, TargetVersion); - if (check_subgroup_support) { + { uint32_t stage_bit = 1 << p_stage; uint32_t subgroup_in_shaders = uint32_t(p_render_device->limit_get(RD::LIMIT_SUBGROUP_IN_SHADERS)); diff --git a/modules/gltf/SCsub b/modules/gltf/SCsub index 71f3ba58d9..d1f337715f 100644 --- a/modules/gltf/SCsub +++ b/modules/gltf/SCsub @@ -7,7 +7,7 @@ env_gltf = env_modules.Clone() # Godot source files env_gltf.add_source_files(env.modules_sources, "*.cpp") -env_gltf.add_source_files(env.modules_sources, "extensions/*.cpp") env_gltf.add_source_files(env.modules_sources, "structures/*.cpp") -if env["tools"]: +SConscript("extensions/SCsub") +if env.editor_build: env_gltf.add_source_files(env.modules_sources, "editor/*.cpp") diff --git a/modules/gltf/config.py b/modules/gltf/config.py index 189b5a831a..130c06d264 100644 --- a/modules/gltf/config.py +++ b/modules/gltf/config.py @@ -26,6 +26,7 @@ def get_doc_classes(): "GLTFSpecGloss", "GLTFState", "GLTFTexture", + "GLTFTextureSampler", ] diff --git a/modules/gltf/doc_classes/GLTFDocumentExtension.xml b/modules/gltf/doc_classes/GLTFDocumentExtension.xml index d2a9022445..936794976d 100644 --- a/modules/gltf/doc_classes/GLTFDocumentExtension.xml +++ b/modules/gltf/doc_classes/GLTFDocumentExtension.xml @@ -1,8 +1,10 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="GLTFDocumentExtension" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> + [GLTFDocument] extension class. </brief_description> <description> + Extends the functionality of the [GLTFDocument] class by allowing you to run arbitrary code at various stages of GLTF import or export. </description> <tutorials> </tutorials> @@ -28,6 +30,12 @@ <description> </description> </method> + <method name="_get_supported_extensions" qualifiers="virtual"> + <return type="PackedStringArray" /> + <description> + Returns an array of the GLTF extensions supported by this GLTFDocumentExtension class. This is used to validate if a GLTF file with required extensions can be loaded. + </description> + </method> <method name="_import_node" qualifiers="virtual"> <return type="int" /> <param index="0" name="state" type="GLTFState" /> diff --git a/modules/gltf/doc_classes/GLTFNode.xml b/modules/gltf/doc_classes/GLTFNode.xml index e933e6046a..8e48066623 100644 --- a/modules/gltf/doc_classes/GLTFNode.xml +++ b/modules/gltf/doc_classes/GLTFNode.xml @@ -1,11 +1,33 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="GLTFNode" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> + GLTF node class. </brief_description> <description> + Represents a GLTF node. GLTF nodes may have names, transforms, children (other GLTF nodes), and more specialized properties (represented by their own classes). </description> <tutorials> + <link title="GLTF scene and node spec">https://github.com/KhronosGroup/glTF-Tutorials/blob/master/gltfTutorial/gltfTutorial_004_ScenesNodes.md"</link> </tutorials> + <methods> + <method name="get_additional_data"> + <return type="Variant" /> + <param index="0" name="extension_name" type="StringName" /> + <description> + Gets additional arbitrary data in this [GLTFNode] instance. This can be used to keep per-node state data in [GLTFDocumentExtension] classes, which is important because they are stateless. + The argument should be the [GLTFDocumentExtension] name (does not have to match the extension name in the GLTF file), and the return value can be anything you set. If nothing was set, the return value is null. + </description> + </method> + <method name="set_additional_data"> + <return type="void" /> + <param index="0" name="extension_name" type="StringName" /> + <param index="1" name="additional_data" type="Variant" /> + <description> + Sets additional arbitrary data in this [GLTFNode] instance. This can be used to keep per-node state data in [GLTFDocumentExtension] classes, which is important because they are stateless. + The first argument should be the [GLTFDocumentExtension] name (does not have to match the extension name in the GLTF file), and the second argument can be anything you want. + </description> + </method> + </methods> <members> <member name="camera" type="int" setter="set_camera" getter="get_camera" default="-1"> </member> diff --git a/modules/gltf/doc_classes/GLTFState.xml b/modules/gltf/doc_classes/GLTFState.xml index 1dbd89aed8..d0740cf7ca 100644 --- a/modules/gltf/doc_classes/GLTFState.xml +++ b/modules/gltf/doc_classes/GLTFState.xml @@ -7,11 +7,27 @@ <tutorials> </tutorials> <methods> + <method name="add_used_extension"> + <return type="void" /> + <param index="0" name="extension_name" type="String" /> + <param index="1" name="required" type="bool" /> + <description> + Appends an extension to the list of extensions used by this GLTF file during serialization. If [param required] is true, the extension will also be added to the list of required extensions. Do not run this in [method GLTFDocumentExtension._export_post], as that stage is too late to add extensions. The final list is sorted alphabetically. + </description> + </method> <method name="get_accessors"> <return type="GLTFAccessor[]" /> <description> </description> </method> + <method name="get_additional_data"> + <return type="Variant" /> + <param index="0" name="extension_name" type="StringName" /> + <description> + Gets additional arbitrary data in this [GLTFState] instance. This can be used to keep per-file state data in [GLTFDocumentExtension] classes, which is important because they are stateless. + The argument should be the [GLTFDocumentExtension] name (does not have to match the extension name in the GLTF file), and the return value can be anything you set. If nothing was set, the return value is null. + </description> + </method> <method name="get_animation_player"> <return type="AnimationPlayer" /> <param index="0" name="idx" type="int" /> @@ -85,6 +101,12 @@ <description> </description> </method> + <method name="get_texture_samplers"> + <return type="GLTFTextureSampler[]" /> + <description> + Retrieves the array of texture samplers that are used by the textures contained in the GLTF. + </description> + </method> <method name="get_textures"> <return type="GLTFTexture[]" /> <description> @@ -106,6 +128,15 @@ <description> </description> </method> + <method name="set_additional_data"> + <return type="void" /> + <param index="0" name="extension_name" type="StringName" /> + <param index="1" name="additional_data" type="Variant" /> + <description> + Sets additional arbitrary data in this [GLTFState] instance. This can be used to keep per-file state data in [GLTFDocumentExtension] classes, which is important because they are stateless. + The first argument should be the [GLTFDocumentExtension] name (does not have to match the extension name in the GLTF file), and the second argument can be anything you want. + </description> + </method> <method name="set_animations"> <return type="void" /> <param index="0" name="animations" type="GLTFAnimation[]" /> @@ -172,6 +203,13 @@ <description> </description> </method> + <method name="set_texture_samplers"> + <return type="void" /> + <param index="0" name="texture_samplers" type="GLTFTextureSampler[]" /> + <description> + Sets the array of texture samplers that are used by the textures contained in the GLTF. + </description> + </method> <method name="set_textures"> <return type="void" /> <param index="0" name="textures" type="GLTFTexture[]" /> diff --git a/modules/gltf/doc_classes/GLTFTexture.xml b/modules/gltf/doc_classes/GLTFTexture.xml index c0bc424168..f4486fd504 100644 --- a/modules/gltf/doc_classes/GLTFTexture.xml +++ b/modules/gltf/doc_classes/GLTFTexture.xml @@ -7,6 +7,9 @@ <tutorials> </tutorials> <members> + <member name="sampler" type="int" setter="set_sampler" getter="get_sampler" default="-1"> + ID of the texture sampler to use when sampling the image. If -1, then the default texture sampler is used (linear filtering, and repeat wrapping in both axes). + </member> <member name="src_image" type="int" setter="set_src_image" getter="get_src_image" default="0"> </member> </members> diff --git a/modules/gltf/doc_classes/GLTFTextureSampler.xml b/modules/gltf/doc_classes/GLTFTextureSampler.xml new file mode 100644 index 0000000000..1cc69bfe73 --- /dev/null +++ b/modules/gltf/doc_classes/GLTFTextureSampler.xml @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="GLTFTextureSampler" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> + <brief_description> + Represents a GLTF texture sampler + </brief_description> + <description> + Represents a texture sampler as defined by the base GLTF spec. Texture samplers in GLTF specify how to sample data from the texture's base image, when rendering the texture on an object. + </description> + <tutorials> + </tutorials> + <members> + <member name="mag_filter" type="int" setter="set_mag_filter" getter="get_mag_filter" default="9729"> + Texture's magnification filter, used when texture appears larger on screen than the source image. + </member> + <member name="min_filter" type="int" setter="set_min_filter" getter="get_min_filter" default="9987"> + Texture's minification filter, used when the texture appears smaller on screen than the source image. + </member> + <member name="wrap_s" type="int" setter="set_wrap_s" getter="get_wrap_s" default="10497"> + Wrapping mode to use for S-axis (horizontal) texture coordinates. + </member> + <member name="wrap_t" type="int" setter="set_wrap_t" getter="get_wrap_t" default="10497"> + Wrapping mode to use for T-axis (vertical) texture coordinates. + </member> + </members> +</class> diff --git a/modules/gltf/editor/editor_scene_exporter_gltf_plugin.h b/modules/gltf/editor/editor_scene_exporter_gltf_plugin.h index 5af46bc752..66fd27b449 100644 --- a/modules/gltf/editor/editor_scene_exporter_gltf_plugin.h +++ b/modules/gltf/editor/editor_scene_exporter_gltf_plugin.h @@ -36,6 +36,8 @@ #include "editor/editor_plugin.h" #include "editor_scene_importer_gltf.h" +class EditorFileDialog; + class SceneExporterGLTFPlugin : public EditorPlugin { GDCLASS(SceneExporterGLTFPlugin, EditorPlugin); diff --git a/modules/gltf/editor/editor_scene_importer_blend.cpp b/modules/gltf/editor/editor_scene_importer_blend.cpp index ab52761e17..20c9508474 100644 --- a/modules/gltf/editor/editor_scene_importer_blend.cpp +++ b/modules/gltf/editor/editor_scene_importer_blend.cpp @@ -77,20 +77,19 @@ Node *EditorSceneFormatImporterBlend::import_scene(const String &p_path, uint32_ } else { parameters_arg += "export_extras=False,"; } - if (p_options.has(SNAME("blender/meshes/skins")) && p_options[SNAME("blender/meshes/skins")]) { + if (p_options.has(SNAME("blender/meshes/skins"))) { int32_t skins = p_options["blender/meshes/skins"]; if (skins == BLEND_BONE_INFLUENCES_NONE) { - parameters_arg += "export_all_influences=False,"; + parameters_arg += "export_skins=False,"; } else if (skins == BLEND_BONE_INFLUENCES_COMPATIBLE) { - parameters_arg += "export_all_influences=False,"; + parameters_arg += "export_all_influences=False,export_skins=True,"; } else if (skins == BLEND_BONE_INFLUENCES_ALL) { - parameters_arg += "export_all_influences=True,"; + parameters_arg += "export_all_influences=True,export_skins=True,"; } - parameters_arg += "export_skins=True,"; } else { parameters_arg += "export_skins=False,"; } - if (p_options.has(SNAME("blender/materials/export_materials")) && p_options[SNAME("blender/materials/export_materials")]) { + if (p_options.has(SNAME("blender/materials/export_materials"))) { int32_t exports = p_options["blender/materials/export_materials"]; if (exports == BLEND_MATERIAL_EXPORT_PLACEHOLDER) { parameters_arg += "export_materials='PLACEHOLDER',"; @@ -115,7 +114,7 @@ Node *EditorSceneFormatImporterBlend::import_scene(const String &p_path, uint32_ } else { parameters_arg += "export_colors=False,"; } - if (p_options.has(SNAME("blender/nodes/visible")) && p_options[SNAME("blender/nodes/visible")]) { + if (p_options.has(SNAME("blender/nodes/visible"))) { int32_t visible = p_options["blender/nodes/visible"]; if (visible == BLEND_VISIBLE_VISIBLE_ONLY) { parameters_arg += "use_visible=True,"; @@ -180,13 +179,13 @@ Node *EditorSceneFormatImporterBlend::import_scene(const String &p_path, uint32_ "export_format='GLTF_SEPARATE'," "export_yup=True," + parameters_arg; - String script = + String export_script = String("import bpy, sys;") + "print('Blender 3.0 or higher is required.', file=sys.stderr) if bpy.app.version < (3, 0, 0) else None;" + vformat("bpy.ops.wm.open_mainfile(filepath='%s');", source_global) + unpack_all + vformat("bpy.ops.export_scene.gltf(export_keep_originals=True,%s);", common_args); - print_verbose(script); + print_verbose(export_script); // Run script with configured Blender binary. @@ -201,7 +200,7 @@ Node *EditorSceneFormatImporterBlend::import_scene(const String &p_path, uint32_ List<String> args; args.push_back("--background"); args.push_back("--python-expr"); - args.push_back(script); + args.push_back(export_script); String standard_out; int ret; @@ -261,7 +260,7 @@ void EditorSceneFormatImporterBlend::get_import_options(const String &p_path, Li #define ADD_OPTION_ENUM(PATH, ENUM_HINT, VALUE) \ r_options->push_back(ResourceImporter::ImportOption(PropertyInfo(Variant::INT, SNAME(PATH), PROPERTY_HINT_ENUM, ENUM_HINT), VALUE)); - ADD_OPTION_ENUM("blender/nodes/visible", "Visible Only,Renderable,All", BLEND_VISIBLE_ALL); + ADD_OPTION_ENUM("blender/nodes/visible", "All,Visible Only,Renderable", BLEND_VISIBLE_ALL); ADD_OPTION_BOOL("blender/nodes/punctual_lights", true); ADD_OPTION_BOOL("blender/nodes/cameras", true); ADD_OPTION_BOOL("blender/nodes/custom_properties", true); @@ -350,9 +349,7 @@ static bool _test_blender_path(const String &p_path, String *r_err = nullptr) { bool EditorFileSystemImportFormatSupportQueryBlend::is_active() const { bool blend_enabled = GLOBAL_GET("filesystem/import/blender/enabled"); - String blender_path = EDITOR_GET("filesystem/import/blender/blender3_path"); - - if (blend_enabled && !_test_blender_path(blender_path)) { + if (blend_enabled && !_test_blender_path(EDITOR_GET("filesystem/import/blender/blender3_path").operator String())) { // Intending to import Blender, but blend not configured. return true; } diff --git a/modules/gltf/editor/editor_scene_importer_blend.h b/modules/gltf/editor/editor_scene_importer_blend.h index dd1c1b9889..a1485ff82e 100644 --- a/modules/gltf/editor/editor_scene_importer_blend.h +++ b/modules/gltf/editor/editor_scene_importer_blend.h @@ -45,9 +45,9 @@ class EditorSceneFormatImporterBlend : public EditorSceneFormatImporter { public: enum { + BLEND_VISIBLE_ALL, BLEND_VISIBLE_VISIBLE_ONLY, - BLEND_VISIBLE_RENDERABLE, - BLEND_VISIBLE_ALL + BLEND_VISIBLE_RENDERABLE }; enum { BLEND_BONE_INFLUENCES_NONE, diff --git a/modules/gltf/extensions/SCsub b/modules/gltf/extensions/SCsub new file mode 100644 index 0000000000..ad214bb79c --- /dev/null +++ b/modules/gltf/extensions/SCsub @@ -0,0 +1,9 @@ +#!/usr/bin/env python + +Import("env") +Import("env_modules") + +env_gltf = env_modules.Clone() + +# Godot source files +env_gltf.add_source_files(env.modules_sources, "*.cpp") diff --git a/modules/gltf/extensions/gltf_light.cpp b/modules/gltf/extensions/gltf_light.cpp index 6923c765cb..d00bead61c 100644 --- a/modules/gltf/extensions/gltf_light.cpp +++ b/modules/gltf/extensions/gltf_light.cpp @@ -142,18 +142,17 @@ Light3D *GLTFLight::to_node() const { light->set_color(color); return light; } - const float range = CLAMP(this->range, 0, 4096); if (light_type == "point") { OmniLight3D *light = memnew(OmniLight3D); light->set_param(OmniLight3D::PARAM_ENERGY, intensity); - light->set_param(OmniLight3D::PARAM_RANGE, range); + light->set_param(OmniLight3D::PARAM_RANGE, CLAMP(range, 0, 4096)); light->set_color(color); return light; } if (light_type == "spot") { SpotLight3D *light = memnew(SpotLight3D); light->set_param(SpotLight3D::PARAM_ENERGY, intensity); - light->set_param(SpotLight3D::PARAM_RANGE, range); + light->set_param(SpotLight3D::PARAM_RANGE, CLAMP(range, 0, 4096)); light->set_param(SpotLight3D::PARAM_SPOT_ANGLE, Math::rad_to_deg(outer_cone_angle)); light->set_color(color); // Line of best fit derived from guessing, see https://www.desmos.com/calculator/biiflubp8b diff --git a/modules/gltf/gltf_defines.h b/modules/gltf/gltf_defines.h index c20c87f798..23bf33869e 100644 --- a/modules/gltf/gltf_defines.h +++ b/modules/gltf/gltf_defines.h @@ -58,6 +58,7 @@ class GLTFSkin; class GLTFSpecGloss; class GLTFState; class GLTFTexture; +class GLTFTextureSampler; // GLTF index aliases. using GLTFAccessorIndex = int; @@ -66,13 +67,14 @@ using GLTFBufferIndex = int; using GLTFBufferViewIndex = int; using GLTFCameraIndex = int; using GLTFImageIndex = int; +using GLTFLightIndex = int; using GLTFMaterialIndex = int; using GLTFMeshIndex = int; -using GLTFLightIndex = int; using GLTFNodeIndex = int; using GLTFSkeletonIndex = int; using GLTFSkinIndex = int; using GLTFTextureIndex = int; +using GLTFTextureSamplerIndex = int; enum GLTFType { TYPE_SCALAR, diff --git a/modules/gltf/gltf_document.cpp b/modules/gltf/gltf_document.cpp index 6cb398b5f8..99803ed05d 100644 --- a/modules/gltf/gltf_document.cpp +++ b/modules/gltf/gltf_document.cpp @@ -145,6 +145,12 @@ Error GLTFDocument::_serialize(Ref<GLTFState> state, const String &p_path) { return Error::FAILED; } + /* STEP SERIALIZE TEXTURE SAMPLERS */ + err = _serialize_texture_samplers(state); + if (err != OK) { + return Error::FAILED; + } + /* STEP SERIALIZE ANIMATIONS */ err = _serialize_animations(state); if (err != OK) { @@ -191,14 +197,14 @@ Error GLTFDocument::_serialize(Ref<GLTFState> state, const String &p_path) { return Error::FAILED; } - /* STEP SERIALIZE SCENE */ + /* STEP SERIALIZE LIGHTS */ err = _serialize_lights(state); if (err != OK) { return Error::FAILED; } /* STEP SERIALIZE EXTENSIONS */ - err = _serialize_extensions(state); + err = _serialize_gltf_extensions(state); if (err != OK) { return Error::FAILED; } @@ -219,9 +225,9 @@ Error GLTFDocument::_serialize(Ref<GLTFState> state, const String &p_path) { return OK; } -Error GLTFDocument::_serialize_extensions(Ref<GLTFState> state) const { - Array extensions_used; - Array extensions_required; +Error GLTFDocument::_serialize_gltf_extensions(Ref<GLTFState> state) const { + Vector<String> extensions_used = state->extensions_used; + Vector<String> extensions_required = state->extensions_required; if (!state->lights.is_empty()) { extensions_used.push_back("KHR_lights_punctual"); } @@ -230,9 +236,11 @@ Error GLTFDocument::_serialize_extensions(Ref<GLTFState> state) const { extensions_required.push_back("KHR_texture_transform"); } if (!extensions_used.is_empty()) { + extensions_used.sort(); state->json["extensionsUsed"] = extensions_used; } if (!extensions_required.is_empty()) { + extensions_required.sort(); state->json["extensionsRequired"] = extensions_required; } return OK; @@ -401,47 +409,47 @@ Error GLTFDocument::_serialize_nodes(Ref<GLTFState> state) { Array nodes; for (int i = 0; i < state->nodes.size(); i++) { Dictionary node; - Ref<GLTFNode> n = state->nodes[i]; + Ref<GLTFNode> gltf_node = state->nodes[i]; Dictionary extensions; node["extensions"] = extensions; - if (!n->get_name().is_empty()) { - node["name"] = n->get_name(); + if (!gltf_node->get_name().is_empty()) { + node["name"] = gltf_node->get_name(); } - if (n->camera != -1) { - node["camera"] = n->camera; + if (gltf_node->camera != -1) { + node["camera"] = gltf_node->camera; } - if (n->light != -1) { + if (gltf_node->light != -1) { Dictionary lights_punctual; extensions["KHR_lights_punctual"] = lights_punctual; - lights_punctual["light"] = n->light; + lights_punctual["light"] = gltf_node->light; } - if (n->mesh != -1) { - node["mesh"] = n->mesh; + if (gltf_node->mesh != -1) { + node["mesh"] = gltf_node->mesh; } - if (n->skin != -1) { - node["skin"] = n->skin; + if (gltf_node->skin != -1) { + node["skin"] = gltf_node->skin; } - if (n->skeleton != -1 && n->skin < 0) { + if (gltf_node->skeleton != -1 && gltf_node->skin < 0) { } - if (n->xform != Transform3D()) { - node["matrix"] = _xform_to_array(n->xform); + if (gltf_node->xform != Transform3D()) { + node["matrix"] = _xform_to_array(gltf_node->xform); } - if (!n->rotation.is_equal_approx(Quaternion())) { - node["rotation"] = _quaternion_to_array(n->rotation); + if (!gltf_node->rotation.is_equal_approx(Quaternion())) { + node["rotation"] = _quaternion_to_array(gltf_node->rotation); } - if (!n->scale.is_equal_approx(Vector3(1.0f, 1.0f, 1.0f))) { - node["scale"] = _vec3_to_arr(n->scale); + if (!gltf_node->scale.is_equal_approx(Vector3(1.0f, 1.0f, 1.0f))) { + node["scale"] = _vec3_to_arr(gltf_node->scale); } - if (!n->position.is_zero_approx()) { - node["translation"] = _vec3_to_arr(n->position); + if (!gltf_node->position.is_zero_approx()) { + node["translation"] = _vec3_to_arr(gltf_node->position); } - if (n->children.size()) { + if (gltf_node->children.size()) { Array children; - for (int j = 0; j < n->children.size(); j++) { - children.push_back(n->children[j]); + for (int j = 0; j < gltf_node->children.size(); j++) { + children.push_back(gltf_node->children[j]); } node["children"] = children; } @@ -450,7 +458,7 @@ Error GLTFDocument::_serialize_nodes(Ref<GLTFState> state) { Ref<GLTFDocumentExtension> ext = document_extensions[ext_i]; ERR_CONTINUE(ext.is_null()); ERR_CONTINUE(!state->scene_nodes.find(i)); - Error err = ext->export_node(state, n, state->json, state->scene_nodes[i]); + Error err = ext->export_node(state, gltf_node, node, state->scene_nodes[i]); ERR_CONTINUE(err != OK); } @@ -463,23 +471,23 @@ Error GLTFDocument::_serialize_nodes(Ref<GLTFState> state) { String GLTFDocument::_gen_unique_name(Ref<GLTFState> state, const String &p_name) { const String s_name = p_name.validate_node_name(); - String name; + String u_name; int index = 1; while (true) { - name = s_name; + u_name = s_name; if (index > 1) { - name += itos(index); + u_name += itos(index); } - if (!state->unique_names.has(name)) { + if (!state->unique_names.has(u_name)) { break; } index++; } - state->unique_names.insert(name); + state->unique_names.insert(u_name); - return name; + return u_name; } String GLTFDocument::_sanitize_animation_name(const String &p_name) { @@ -487,39 +495,39 @@ String GLTFDocument::_sanitize_animation_name(const String &p_name) { // (See animation/animation_player.cpp::add_animation) // TODO: Consider adding invalid_characters or a validate_animation_name to animation_player to mirror Node. - String name = p_name.validate_node_name(); - name = name.replace(",", ""); - name = name.replace("[", ""); - return name; + String anim_name = p_name.validate_node_name(); + anim_name = anim_name.replace(",", ""); + anim_name = anim_name.replace("[", ""); + return anim_name; } String GLTFDocument::_gen_unique_animation_name(Ref<GLTFState> state, const String &p_name) { const String s_name = _sanitize_animation_name(p_name); - String name; + String u_name; int index = 1; while (true) { - name = s_name; + u_name = s_name; if (index > 1) { - name += itos(index); + u_name += itos(index); } - if (!state->unique_animation_names.has(name)) { + if (!state->unique_animation_names.has(u_name)) { break; } index++; } - state->unique_animation_names.insert(name); + state->unique_animation_names.insert(u_name); - return name; + return u_name; } String GLTFDocument::_sanitize_bone_name(const String &p_name) { - String name = p_name; - name = name.replace(":", "_"); - name = name.replace("/", "_"); - return name; + String bone_name = p_name; + bone_name = bone_name.replace(":", "_"); + bone_name = bone_name.replace("/", "_"); + return bone_name; } String GLTFDocument::_gen_unique_bone_name(Ref<GLTFState> state, const GLTFSkeletonIndex skel_i, const String &p_name) { @@ -527,23 +535,23 @@ String GLTFDocument::_gen_unique_bone_name(Ref<GLTFState> state, const GLTFSkele if (s_name.is_empty()) { s_name = "bone"; } - String name; + String u_name; int index = 1; while (true) { - name = s_name; + u_name = s_name; if (index > 1) { - name += "_" + itos(index); + u_name += "_" + itos(index); } - if (!state->skeletons[skel_i]->unique_names.has(name)) { + if (!state->skeletons[skel_i]->unique_names.has(u_name)) { break; } index++; } - state->skeletons.write[skel_i]->unique_names.insert(name); + state->skeletons.write[skel_i]->unique_names.insert(u_name); - return name; + return u_name; } Error GLTFDocument::_parse_scenes(Ref<GLTFState> state) { @@ -2582,10 +2590,7 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) { Mesh::PRIMITIVE_TRIANGLES, // 4 TRIANGLES Mesh::PRIMITIVE_TRIANGLE_STRIP, // 5 TRIANGLE_STRIP Mesh::PRIMITIVE_TRIANGLES, // 6 TRIANGLE_FAN fan not supported, should be converted -#ifndef _MSC_VER -#warning line loop and triangle fan are not supported and need to be converted to lines and triangles -#endif - + // TODO: Line loop and triangle fan are not supported and need to be converted to lines and triangles. }; primitive = primitives2[mode]; @@ -2673,7 +2678,7 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) { } else if (a.has("JOINTS_0") && a.has("JOINTS_1")) { PackedInt32Array joints_0 = _decode_accessor_as_ints(state, a["JOINTS_0"], true); PackedInt32Array joints_1 = _decode_accessor_as_ints(state, a["JOINTS_1"], true); - ERR_FAIL_COND_V(joints_0.size() != joints_0.size(), ERR_INVALID_DATA); + ERR_FAIL_COND_V(joints_0.size() != joints_1.size(), ERR_INVALID_DATA); int32_t weight_8_count = JOINT_GROUP_SIZE * 2; Vector<int> joints; joints.resize(vertex_num * weight_8_count); @@ -2816,8 +2821,7 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) { if (j == 0) { const Array &target_names = extras.has("targetNames") ? (Array)extras["targetNames"] : Array(); for (int k = 0; k < targets.size(); k++) { - const String name = k < target_names.size() ? (String)target_names[k] : String("morph_") + itos(k); - import_mesh->add_blend_shape(name); + import_mesh->add_blend_shape(k < target_names.size() ? (String)target_names[k] : String("morph_") + itos(k)); } } @@ -3026,12 +3030,12 @@ Error GLTFDocument::_serialize_images(Ref<GLTFState> state, const String &p_path d["mimeType"] = "image/png"; } else { ERR_FAIL_COND_V(p_path.is_empty(), ERR_INVALID_PARAMETER); - String name = state->images[i]->get_name(); - if (name.is_empty()) { - name = itos(i); + String img_name = state->images[i]->get_name(); + if (img_name.is_empty()) { + img_name = itos(i); } - name = _gen_unique_name(state, name); - name = name.pad_zeros(3) + ".png"; + img_name = _gen_unique_name(state, img_name); + img_name = img_name.pad_zeros(3) + ".png"; String texture_dir = "textures"; String path = p_path.get_base_dir(); String new_texture_dir = path + "/" + texture_dir; @@ -3039,8 +3043,8 @@ Error GLTFDocument::_serialize_images(Ref<GLTFState> state, const String &p_path if (!da->dir_exists(new_texture_dir)) { da->make_dir(new_texture_dir); } - image->save_png(new_texture_dir.path_join(name)); - d["uri"] = texture_dir.path_join(name).uri_encode(); + image->save_png(new_texture_dir.path_join(img_name)); + d["uri"] = texture_dir.path_join(img_name).uri_encode(); } images.push_back(d); } @@ -3217,6 +3221,11 @@ Error GLTFDocument::_serialize_textures(Ref<GLTFState> state) { Ref<GLTFTexture> t = state->textures[i]; ERR_CONTINUE(t->get_src_image() == -1); d["source"] = t->get_src_image(); + + GLTFTextureSamplerIndex sampler_index = t->get_sampler(); + if (sampler_index != -1) { + d["sampler"] = sampler_index; + } textures.push_back(d); } state->json["textures"] = textures; @@ -3238,13 +3247,18 @@ Error GLTFDocument::_parse_textures(Ref<GLTFState> state) { Ref<GLTFTexture> t; t.instantiate(); t->set_src_image(d["source"]); + if (d.has("sampler")) { + t->set_sampler(d["sampler"]); + } else { + t->set_sampler(-1); + } state->textures.push_back(t); } return OK; } -GLTFTextureIndex GLTFDocument::_set_texture(Ref<GLTFState> state, Ref<Texture2D> p_texture) { +GLTFTextureIndex GLTFDocument::_set_texture(Ref<GLTFState> state, Ref<Texture2D> p_texture, StandardMaterial3D::TextureFilter p_filter_mode, bool p_repeats) { ERR_FAIL_COND_V(p_texture.is_null(), -1); Ref<GLTFTexture> gltf_texture; gltf_texture.instantiate(); @@ -3252,6 +3266,7 @@ GLTFTextureIndex GLTFDocument::_set_texture(Ref<GLTFState> state, Ref<Texture2D> GLTFImageIndex gltf_src_image_i = state->images.size(); state->images.push_back(p_texture); gltf_texture->set_src_image(gltf_src_image_i); + gltf_texture->set_sampler(_set_sampler_for_mode(state, p_filter_mode, p_repeats)); GLTFTextureIndex gltf_texture_i = state->textures.size(); state->textures.push_back(gltf_texture); return gltf_texture_i; @@ -3266,6 +3281,102 @@ Ref<Texture2D> GLTFDocument::_get_texture(Ref<GLTFState> state, const GLTFTextur return state->images[image]; } +GLTFTextureSamplerIndex GLTFDocument::_set_sampler_for_mode(Ref<GLTFState> state, StandardMaterial3D::TextureFilter p_filter_mode, bool p_repeats) { + for (int i = 0; i < state->texture_samplers.size(); ++i) { + if (state->texture_samplers[i]->get_filter_mode() == p_filter_mode) { + return i; + } + } + + GLTFTextureSamplerIndex gltf_sampler_i = state->texture_samplers.size(); + Ref<GLTFTextureSampler> gltf_sampler; + gltf_sampler.instantiate(); + gltf_sampler->set_filter_mode(p_filter_mode); + gltf_sampler->set_wrap_mode(p_repeats); + state->texture_samplers.push_back(gltf_sampler); + return gltf_sampler_i; +} + +Ref<GLTFTextureSampler> GLTFDocument::_get_sampler_for_texture(Ref<GLTFState> state, const GLTFTextureIndex p_texture) { + ERR_FAIL_INDEX_V(p_texture, state->textures.size(), Ref<Texture2D>()); + const GLTFTextureSamplerIndex sampler = state->textures[p_texture]->get_sampler(); + + if (sampler == -1) { + return state->default_texture_sampler; + } else { + ERR_FAIL_INDEX_V(sampler, state->texture_samplers.size(), Ref<GLTFTextureSampler>()); + + return state->texture_samplers[sampler]; + } +} + +Error GLTFDocument::_serialize_texture_samplers(Ref<GLTFState> state) { + if (!state->texture_samplers.size()) { + return OK; + } + + Array samplers; + for (int32_t i = 0; i < state->texture_samplers.size(); ++i) { + Dictionary d; + Ref<GLTFTextureSampler> s = state->texture_samplers[i]; + d["magFilter"] = s->get_mag_filter(); + d["minFilter"] = s->get_min_filter(); + d["wrapS"] = s->get_wrap_s(); + d["wrapT"] = s->get_wrap_t(); + samplers.push_back(d); + } + state->json["samplers"] = samplers; + + return OK; +} + +Error GLTFDocument::_parse_texture_samplers(Ref<GLTFState> state) { + state->default_texture_sampler.instantiate(); + state->default_texture_sampler->set_min_filter(GLTFTextureSampler::FilterMode::LINEAR_MIPMAP_LINEAR); + state->default_texture_sampler->set_mag_filter(GLTFTextureSampler::FilterMode::LINEAR); + state->default_texture_sampler->set_wrap_s(GLTFTextureSampler::WrapMode::REPEAT); + state->default_texture_sampler->set_wrap_t(GLTFTextureSampler::WrapMode::REPEAT); + + if (!state->json.has("samplers")) { + return OK; + } + + const Array &samplers = state->json["samplers"]; + for (int i = 0; i < samplers.size(); ++i) { + const Dictionary &d = samplers[i]; + + Ref<GLTFTextureSampler> sampler; + sampler.instantiate(); + + if (d.has("minFilter")) { + sampler->set_min_filter(d["minFilter"]); + } else { + sampler->set_min_filter(GLTFTextureSampler::FilterMode::LINEAR_MIPMAP_LINEAR); + } + if (d.has("magFilter")) { + sampler->set_mag_filter(d["magFilter"]); + } else { + sampler->set_mag_filter(GLTFTextureSampler::FilterMode::LINEAR); + } + + if (d.has("wrapS")) { + sampler->set_wrap_s(d["wrapS"]); + } else { + sampler->set_wrap_s(GLTFTextureSampler::WrapMode::DEFAULT); + } + + if (d.has("wrapT")) { + sampler->set_wrap_t(d["wrapT"]); + } else { + sampler->set_wrap_t(GLTFTextureSampler::WrapMode::DEFAULT); + } + + state->texture_samplers.push_back(sampler); + } + + return OK; +} + Error GLTFDocument::_serialize_materials(Ref<GLTFState> state) { Array materials; for (int32_t i = 0; i < state->materials.size(); i++) { @@ -3297,7 +3408,7 @@ Error GLTFDocument::_serialize_materials(Ref<GLTFState> state) { if (albedo_texture.is_valid() && albedo_texture->get_image().is_valid()) { albedo_texture->set_name(material->get_name() + "_albedo"); - gltf_texture_index = _set_texture(state, albedo_texture); + gltf_texture_index = _set_texture(state, albedo_texture, material->get_texture_filter(), material->get_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT)); } if (gltf_texture_index != -1) { bct["index"] = gltf_texture_index; @@ -3373,7 +3484,7 @@ Error GLTFDocument::_serialize_materials(Ref<GLTFState> state) { height = albedo_texture->get_height(); width = albedo_texture->get_width(); } - orm_image->create(width, height, false, Image::FORMAT_RGBA8); + orm_image->initialize_data(width, height, false, Image::FORMAT_RGBA8); if (ao_image.is_valid() && ao_image->get_size() != Vector2(width, height)) { ao_image->resize(width, height, Image::INTERPOLATE_LANCZOS); } @@ -3427,7 +3538,7 @@ Error GLTFDocument::_serialize_materials(Ref<GLTFState> state) { GLTFTextureIndex orm_texture_index = -1; if (has_ao || has_roughness || has_metalness) { orm_texture->set_name(material->get_name() + "_orm"); - orm_texture_index = _set_texture(state, orm_texture); + orm_texture_index = _set_texture(state, orm_texture, material->get_texture_filter(), material->get_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT)); } if (has_ao) { Dictionary occt; @@ -3482,7 +3593,7 @@ Error GLTFDocument::_serialize_materials(Ref<GLTFState> state) { GLTFTextureIndex gltf_texture_index = -1; if (tex.is_valid() && tex->get_image().is_valid()) { tex->set_name(material->get_name() + "_normal"); - gltf_texture_index = _set_texture(state, tex); + gltf_texture_index = _set_texture(state, tex, material->get_texture_filter(), material->get_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT)); } nt["scale"] = material->get_normal_scale(); if (gltf_texture_index != -1) { @@ -3505,7 +3616,7 @@ Error GLTFDocument::_serialize_materials(Ref<GLTFState> state) { GLTFTextureIndex gltf_texture_index = -1; if (emission_texture.is_valid() && emission_texture->get_image().is_valid()) { emission_texture->set_name(material->get_name() + "_emission"); - gltf_texture_index = _set_texture(state, emission_texture); + gltf_texture_index = _set_texture(state, emission_texture, material->get_texture_filter(), material->get_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT)); } if (gltf_texture_index != -1) { @@ -3564,6 +3675,11 @@ Error GLTFDocument::_parse_materials(Ref<GLTFState> state) { if (sgm.has("diffuseTexture")) { const Dictionary &diffuse_texture_dict = sgm["diffuseTexture"]; if (diffuse_texture_dict.has("index")) { + Ref<GLTFTextureSampler> diffuse_sampler = _get_sampler_for_texture(state, diffuse_texture_dict["index"]); + if (diffuse_sampler.is_valid()) { + material->set_texture_filter(diffuse_sampler->get_filter_mode()); + material->set_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT, diffuse_sampler->get_wrap_mode()); + } Ref<Texture2D> diffuse_texture = _get_texture(state, diffuse_texture_dict["index"]); if (diffuse_texture.is_valid()) { spec_gloss->diffuse_img = diffuse_texture->get_image(); @@ -3612,6 +3728,9 @@ Error GLTFDocument::_parse_materials(Ref<GLTFState> state) { if (mr.has("baseColorTexture")) { const Dictionary &bct = mr["baseColorTexture"]; if (bct.has("index")) { + Ref<GLTFTextureSampler> bct_sampler = _get_sampler_for_texture(state, bct["index"]); + material->set_texture_filter(bct_sampler->get_filter_mode()); + material->set_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT, bct_sampler->get_wrap_mode()); material->set_texture(BaseMaterial3D::TEXTURE_ALBEDO, _get_texture(state, bct["index"])); } if (!mr.has("baseColorFactor")) { @@ -3741,13 +3860,11 @@ void GLTFDocument::spec_gloss_to_rough_metal(Ref<GLTFSpecGloss> r_spec_gloss, Re if (r_spec_gloss->diffuse_img.is_null()) { return; } - Ref<Image> rm_img; - rm_img.instantiate(); bool has_roughness = false; bool has_metal = false; p_material->set_roughness(1.0f); p_material->set_metallic(1.0f); - rm_img->create(r_spec_gloss->spec_gloss_img->get_width(), r_spec_gloss->spec_gloss_img->get_height(), false, Image::FORMAT_RGBA8); + Ref<Image> rm_img = Image::create_empty(r_spec_gloss->spec_gloss_img->get_width(), r_spec_gloss->spec_gloss_img->get_height(), false, Image::FORMAT_RGBA8); r_spec_gloss->spec_gloss_img->decompress(); if (r_spec_gloss->diffuse_img.is_valid()) { r_spec_gloss->diffuse_img->decompress(); @@ -4299,14 +4416,14 @@ Error GLTFDocument::_determine_skeleton_roots(Ref<GLTFState> state, const GLTFSk Ref<GLTFSkeleton> skeleton = state->skeletons.write[skel_i]; - Vector<GLTFNodeIndex> owners; - disjoint_set.get_representatives(owners); + Vector<GLTFNodeIndex> representatives; + disjoint_set.get_representatives(representatives); Vector<GLTFNodeIndex> roots; - for (int i = 0; i < owners.size(); ++i) { + for (int i = 0; i < representatives.size(); ++i) { Vector<GLTFNodeIndex> set; - disjoint_set.get_members(set, owners[i]); + disjoint_set.get_members(set, representatives[i]); const GLTFNodeIndex root = _find_highest_node(state, set); ERR_FAIL_COND_V(root < 0, FAILED); roots.push_back(root); @@ -4837,12 +4954,12 @@ Error GLTFDocument::_parse_animations(Ref<GLTFState> state) { Array samplers = d["samplers"]; if (d.has("name")) { - const String name = d["name"]; - const String name_lower = name.to_lower(); - if (name_lower.begins_with("loop") || name_lower.ends_with("loop") || name_lower.begins_with("cycle") || name_lower.ends_with("cycle")) { + const String anim_name = d["name"]; + const String anim_name_lower = anim_name.to_lower(); + if (anim_name_lower.begins_with("loop") || anim_name_lower.ends_with("loop") || anim_name_lower.begins_with("cycle") || anim_name_lower.ends_with("cycle")) { animation->set_loop(true); } - animation->set_name(_gen_unique_animation_name(state, name)); + animation->set_name(_gen_unique_animation_name(state, anim_name)); } for (int j = 0; j < channels.size(); j++) { @@ -5046,7 +5163,7 @@ ImporterMeshInstance3D *GLTFDocument::_generate_mesh_instance(Ref<GLTFState> sta return mi; } -Node3D *GLTFDocument::_generate_light(Ref<GLTFState> state, const GLTFNodeIndex node_index) { +Light3D *GLTFDocument::_generate_light(Ref<GLTFState> state, const GLTFNodeIndex node_index) { Ref<GLTFNode> gltf_node = state->nodes[node_index]; ERR_FAIL_INDEX_V(gltf_node->light, state->lights.size(), nullptr); @@ -5102,6 +5219,7 @@ Node3D *GLTFDocument::_generate_spatial(Ref<GLTFState> state, const GLTFNodeInde return spatial; } + void GLTFDocument::_convert_scene_node(Ref<GLTFState> state, Node *p_current, const GLTFNodeIndex p_gltf_parent, const GLTFNodeIndex p_gltf_root) { bool retflag = true; _check_visibility(p_current, retflag); @@ -5704,15 +5822,15 @@ T GLTFDocument::_interpolate_track(const Vector<real_t> &p_times, const Vector<T void GLTFDocument::_import_animation(Ref<GLTFState> state, AnimationPlayer *ap, const GLTFAnimationIndex index, const int bake_fps) { Ref<GLTFAnimation> anim = state->animations[index]; - String name = anim->get_name(); - if (name.is_empty()) { + String anim_name = anim->get_name(); + if (anim_name.is_empty()) { // No node represent these, and they are not in the hierarchy, so just make a unique name - name = _gen_unique_name(state, "Animation"); + anim_name = _gen_unique_name(state, "Animation"); } Ref<Animation> animation; animation.instantiate(); - animation->set_name(name); + animation->set_name(anim_name); if (anim->get_loop()) { animation->set_loop_mode(Animation::LOOP_LINEAR); @@ -5935,7 +6053,7 @@ void GLTFDocument::_import_animation(Ref<GLTFState> state, AnimationPlayer *ap, } else { library = ap->get_animation_library(""); } - library->add_animation(name, animation); + library->add_animation(anim_name, animation); } void GLTFDocument::_convert_mesh_instances(Ref<GLTFState> state) { @@ -6171,7 +6289,7 @@ GLTFAnimation::Track GLTFDocument::_convert_animation_track(Ref<GLTFState> state for (int32_t key_i = 0; key_i < key_count; key_i++) { Vector3 rotation_radian = p_animation->track_get_key_value(p_track_i, key_i); - p_track.rotation_track.values.write[key_i] = Quaternion(rotation_radian); + p_track.rotation_track.values.write[key_i] = Quaternion::from_euler(rotation_radian); } } else if (path.contains(":scale")) { p_track.scale_track.times = times; @@ -6474,8 +6592,10 @@ Error GLTFDocument::_parse(Ref<GLTFState> state, String p_path, Ref<FileAccess> err = ext->import_preflight(state); ERR_FAIL_COND_V(err != OK, err); } + err = _parse_gltf_state(state, p_path, p_bake_fps); ERR_FAIL_COND_V(err != OK, err); + return OK; } @@ -6831,6 +6951,11 @@ Error GLTFDocument::_parse_gltf_state(Ref<GLTFState> state, const String &p_sear ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR); + /* PARSE TEXTURE SAMPLERS */ + err = _parse_texture_samplers(state); + + ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR); + /* PARSE TEXTURES */ err = _parse_textures(state); @@ -6916,12 +7041,32 @@ Error GLTFDocument::append_from_file(String p_path, Ref<GLTFState> r_state, uint Error GLTFDocument::_parse_gltf_extensions(Ref<GLTFState> state) { ERR_FAIL_NULL_V(state, ERR_PARSE_ERROR); - if (state->json.has("extensionsRequired") && state->json["extensionsRequired"].get_type() == Variant::ARRAY) { - Array extensions_required = state->json["extensionsRequired"]; - if (extensions_required.find("KHR_draco_mesh_compression") != -1) { - ERR_PRINT("glTF2 extension KHR_draco_mesh_compression is not supported."); - return ERR_UNAVAILABLE; + if (state->json.has("extensionsUsed")) { + Vector<String> ext_array = state->json["extensionsUsed"]; + state->extensions_used = ext_array; + } + if (state->json.has("extensionsRequired")) { + Vector<String> ext_array = state->json["extensionsRequired"]; + state->extensions_required = ext_array; + } + HashSet<String> supported_extensions; + supported_extensions.insert("KHR_lights_punctual"); + supported_extensions.insert("KHR_materials_pbrSpecularGlossiness"); + supported_extensions.insert("KHR_texture_transform"); + for (int ext_i = 0; ext_i < document_extensions.size(); ext_i++) { + Ref<GLTFDocumentExtension> ext = document_extensions[ext_i]; + ERR_CONTINUE(ext.is_null()); + Vector<String> ext_supported_extensions = ext->get_supported_extensions(); + for (int i = 0; i < ext_supported_extensions.size(); ++i) { + supported_extensions.insert(ext_supported_extensions[i]); } } - return OK; + Error ret = Error::OK; + for (int i = 0; i < state->extensions_required.size(); i++) { + if (!supported_extensions.has(state->extensions_required[i])) { + ERR_PRINT("GLTF: Can't import file '" + state->filename + "', required extension '" + String(state->extensions_required[i]) + "' is not supported. Are you missing a GLTFDocumentExtension plugin?"); + ret = ERR_UNAVAILABLE; + } + } + return ret; } diff --git a/modules/gltf/gltf_document.h b/modules/gltf/gltf_document.h index 36a2f94a4e..62b6e29fe0 100644 --- a/modules/gltf/gltf_document.h +++ b/modules/gltf/gltf_document.h @@ -95,9 +95,14 @@ private: String _gen_unique_bone_name(Ref<GLTFState> state, const GLTFSkeletonIndex skel_i, const String &p_name); - GLTFTextureIndex _set_texture(Ref<GLTFState> state, Ref<Texture2D> p_texture); + GLTFTextureIndex _set_texture(Ref<GLTFState> state, Ref<Texture2D> p_texture, + StandardMaterial3D::TextureFilter p_filter_mode, bool p_repeats); Ref<Texture2D> _get_texture(Ref<GLTFState> state, const GLTFTextureIndex p_texture); + GLTFTextureSamplerIndex _set_sampler_for_mode(Ref<GLTFState> state, + StandardMaterial3D::TextureFilter p_filter_mode, bool p_repeats); + Ref<GLTFTextureSampler> _get_sampler_for_texture(Ref<GLTFState> state, + const GLTFTextureIndex p_texture); Error _parse_json(const String &p_path, Ref<GLTFState> state); Error _parse_glb(Ref<FileAccess> f, Ref<GLTFState> state); void _compute_node_heights(Ref<GLTFState> state); @@ -145,10 +150,12 @@ private: const bool p_for_vertex); Error _parse_meshes(Ref<GLTFState> state); Error _serialize_textures(Ref<GLTFState> state); + Error _serialize_texture_samplers(Ref<GLTFState> state); Error _serialize_images(Ref<GLTFState> state, const String &p_path); Error _serialize_lights(Ref<GLTFState> state); Error _parse_images(Ref<GLTFState> state, const String &p_base_path); Error _parse_textures(Ref<GLTFState> state); + Error _parse_texture_samplers(Ref<GLTFState> state); Error _parse_materials(Ref<GLTFState> state); void _set_texture_transform_uv1(const Dictionary &d, Ref<BaseMaterial3D> material); void spec_gloss_to_rough_metal(Ref<GLTFSpecGloss> r_spec_gloss, @@ -188,7 +195,7 @@ private: const GLTFNodeIndex bone_index); ImporterMeshInstance3D *_generate_mesh_instance(Ref<GLTFState> state, const GLTFNodeIndex node_index); Camera3D *_generate_camera(Ref<GLTFState> state, const GLTFNodeIndex node_index); - Node3D *_generate_light(Ref<GLTFState> state, const GLTFNodeIndex node_index); + Light3D *_generate_light(Ref<GLTFState> state, const GLTFNodeIndex node_index); Node3D *_generate_spatial(Ref<GLTFState> state, const GLTFNodeIndex node_index); void _assign_scene_names(Ref<GLTFState> state); template <class T> @@ -265,7 +272,7 @@ private: Dictionary _serialize_texture_transform_uv2(Ref<BaseMaterial3D> p_material); Error _serialize_version(Ref<GLTFState> state); Error _serialize_file(Ref<GLTFState> state, const String p_path); - Error _serialize_extensions(Ref<GLTFState> state) const; + Error _serialize_gltf_extensions(Ref<GLTFState> state) const; public: // https://www.itu.int/rec/R-REC-BT.601 diff --git a/modules/gltf/gltf_document_extension.cpp b/modules/gltf/gltf_document_extension.cpp index d0bd7651e0..713779712c 100644 --- a/modules/gltf/gltf_document_extension.cpp +++ b/modules/gltf/gltf_document_extension.cpp @@ -31,6 +31,7 @@ #include "gltf_document_extension.h" void GLTFDocumentExtension::_bind_methods() { + GDVIRTUAL_BIND(_get_supported_extensions); GDVIRTUAL_BIND(_import_preflight, "state"); GDVIRTUAL_BIND(_import_post_parse, "state"); GDVIRTUAL_BIND(_import_node, "state", "gltf_node", "json", "node"); @@ -40,49 +41,45 @@ void GLTFDocumentExtension::_bind_methods() { GDVIRTUAL_BIND(_export_post, "state"); } +Vector<String> GLTFDocumentExtension::get_supported_extensions() { + Vector<String> ret; + GDVIRTUAL_CALL(_get_supported_extensions, ret); + return ret; +} + Error GLTFDocumentExtension::import_post(Ref<GLTFState> p_state, Node *p_root) { ERR_FAIL_NULL_V(p_root, ERR_INVALID_PARAMETER); ERR_FAIL_NULL_V(p_state, ERR_INVALID_PARAMETER); int err = OK; - if (GDVIRTUAL_CALL(_import_post, p_state, p_root, err)) { - return Error(err); - } - return OK; + GDVIRTUAL_CALL(_import_post, p_state, p_root, err); + return Error(err); } Error GLTFDocumentExtension::import_preflight(Ref<GLTFState> p_state) { ERR_FAIL_NULL_V(p_state, ERR_INVALID_PARAMETER); int err = OK; - if (GDVIRTUAL_CALL(_import_preflight, p_state, err)) { - return Error(err); - } - return OK; + GDVIRTUAL_CALL(_import_preflight, p_state, err); + return Error(err); } Error GLTFDocumentExtension::import_post_parse(Ref<GLTFState> p_state) { ERR_FAIL_NULL_V(p_state, ERR_INVALID_PARAMETER); int err = OK; - if (GDVIRTUAL_CALL(_import_post_parse, p_state, err)) { - return Error(err); - } - return OK; + GDVIRTUAL_CALL(_import_post_parse, p_state, err); + return Error(err); } Error GLTFDocumentExtension::export_post(Ref<GLTFState> p_state) { ERR_FAIL_NULL_V(p_state, ERR_INVALID_PARAMETER); int err = OK; - if (GDVIRTUAL_CALL(_export_post, p_state, err)) { - return Error(err); - } - return OK; + GDVIRTUAL_CALL(_export_post, p_state, err); + return Error(err); } Error GLTFDocumentExtension::export_preflight(Node *p_root) { ERR_FAIL_NULL_V(p_root, ERR_INVALID_PARAMETER); int err = OK; - if (GDVIRTUAL_CALL(_export_preflight, p_root, err)) { - return Error(err); - } - return OK; + GDVIRTUAL_CALL(_export_preflight, p_root, err); + return Error(err); } Error GLTFDocumentExtension::import_node(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Dictionary &r_dict, Node *p_node) { @@ -90,10 +87,8 @@ Error GLTFDocumentExtension::import_node(Ref<GLTFState> p_state, Ref<GLTFNode> p ERR_FAIL_NULL_V(p_gltf_node, ERR_INVALID_PARAMETER); ERR_FAIL_NULL_V(p_node, ERR_INVALID_PARAMETER); int err = OK; - if (GDVIRTUAL_CALL(_import_node, p_state, p_gltf_node, r_dict, p_node, err)) { - return Error(err); - } - return OK; + GDVIRTUAL_CALL(_import_node, p_state, p_gltf_node, r_dict, p_node, err); + return Error(err); } Error GLTFDocumentExtension::export_node(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Dictionary &r_dict, Node *p_node) { @@ -101,8 +96,6 @@ Error GLTFDocumentExtension::export_node(Ref<GLTFState> p_state, Ref<GLTFNode> p ERR_FAIL_NULL_V(p_gltf_node, ERR_INVALID_PARAMETER); ERR_FAIL_NULL_V(p_node, ERR_INVALID_PARAMETER); int err = OK; - if (GDVIRTUAL_CALL(_export_node, p_state, p_gltf_node, r_dict, p_node, err)) { - return Error(err); - } - return OK; + GDVIRTUAL_CALL(_export_node, p_state, p_gltf_node, r_dict, p_node, err); + return Error(err); } diff --git a/modules/gltf/gltf_document_extension.h b/modules/gltf/gltf_document_extension.h index 0ef9109584..d4bb3993dc 100644 --- a/modules/gltf/gltf_document_extension.h +++ b/modules/gltf/gltf_document_extension.h @@ -41,6 +41,7 @@ protected: static void _bind_methods(); public: + virtual Vector<String> get_supported_extensions(); virtual Error import_preflight(Ref<GLTFState> p_state); virtual Error import_post_parse(Ref<GLTFState> p_state); virtual Error export_post(Ref<GLTFState> p_state); @@ -48,6 +49,7 @@ public: virtual Error export_preflight(Node *p_state); virtual Error import_node(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Dictionary &r_json, Node *p_node); virtual Error export_node(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Dictionary &r_json, Node *p_node); + GDVIRTUAL0R(Vector<String>, _get_supported_extensions); GDVIRTUAL1R(int, _import_preflight, Ref<GLTFState>); GDVIRTUAL1R(int, _import_post_parse, Ref<GLTFState>); GDVIRTUAL4R(int, _import_node, Ref<GLTFState>, Ref<GLTFNode>, Dictionary, Node *); diff --git a/modules/gltf/gltf_state.cpp b/modules/gltf/gltf_state.cpp index 85bac446cc..ac5665e396 100644 --- a/modules/gltf/gltf_state.cpp +++ b/modules/gltf/gltf_state.cpp @@ -31,6 +31,7 @@ #include "gltf_state.h" void GLTFState::_bind_methods() { + ClassDB::bind_method(D_METHOD("add_used_extension", "extension_name", "required"), &GLTFState::add_used_extension); ClassDB::bind_method(D_METHOD("get_json"), &GLTFState::get_json); ClassDB::bind_method(D_METHOD("set_json", "json"), &GLTFState::set_json); ClassDB::bind_method(D_METHOD("get_major_version"), &GLTFState::get_major_version); @@ -63,6 +64,8 @@ void GLTFState::_bind_methods() { ClassDB::bind_method(D_METHOD("set_root_nodes", "root_nodes"), &GLTFState::set_root_nodes); ClassDB::bind_method(D_METHOD("get_textures"), &GLTFState::get_textures); ClassDB::bind_method(D_METHOD("set_textures", "textures"), &GLTFState::set_textures); + ClassDB::bind_method(D_METHOD("get_texture_samplers"), &GLTFState::get_texture_samplers); + ClassDB::bind_method(D_METHOD("set_texture_samplers", "texture_samplers"), &GLTFState::set_texture_samplers); ClassDB::bind_method(D_METHOD("get_images"), &GLTFState::get_images); ClassDB::bind_method(D_METHOD("set_images", "images"), &GLTFState::set_images); ClassDB::bind_method(D_METHOD("get_skins"), &GLTFState::get_skins); @@ -84,6 +87,8 @@ void GLTFState::_bind_methods() { ClassDB::bind_method(D_METHOD("get_animations"), &GLTFState::get_animations); ClassDB::bind_method(D_METHOD("set_animations", "animations"), &GLTFState::set_animations); ClassDB::bind_method(D_METHOD("get_scene_node", "idx"), &GLTFState::get_scene_node); + ClassDB::bind_method(D_METHOD("get_additional_data", "extension_name"), &GLTFState::get_additional_data); + ClassDB::bind_method(D_METHOD("set_additional_data", "extension_name", "additional_data"), &GLTFState::set_additional_data); ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "json"), "set_json", "get_json"); // Dictionary ADD_PROPERTY(PropertyInfo(Variant::INT, "major_version"), "set_major_version", "get_major_version"); // int @@ -100,6 +105,7 @@ void GLTFState::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::STRING, "base_path"), "set_base_path", "get_base_path"); // String ADD_PROPERTY(PropertyInfo(Variant::PACKED_INT32_ARRAY, "root_nodes"), "set_root_nodes", "get_root_nodes"); // Vector<int> ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "textures", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_textures", "get_textures"); // Vector<Ref<GLTFTexture>> + ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "texture_samplers", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_texture_samplers", "get_texture_samplers"); //Vector<Ref<GLTFTextureSampler>> ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "images", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_images", "get_images"); // Vector<Ref<Texture> ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "skins", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_skins", "get_skins"); // Vector<Ref<GLTFSkin>> ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "cameras", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_cameras", "get_cameras"); // Vector<Ref<GLTFCamera>> @@ -112,6 +118,17 @@ void GLTFState::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "animations", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_animations", "get_animations"); // Vector<Ref<GLTFAnimation>> } +void GLTFState::add_used_extension(const String &p_extension_name, bool p_required) { + if (!extensions_used.has(p_extension_name)) { + extensions_used.push_back(p_extension_name); + } + if (p_required) { + if (!extensions_required.has(p_extension_name)) { + extensions_required.push_back(p_extension_name); + } + } +} + Dictionary GLTFState::get_json() { return json; } @@ -224,6 +241,14 @@ void GLTFState::set_textures(TypedArray<GLTFTexture> p_textures) { GLTFTemplateConvert::set_from_array(textures, p_textures); } +TypedArray<GLTFTextureSampler> GLTFState::get_texture_samplers() { + return GLTFTemplateConvert::to_array(texture_samplers); +} + +void GLTFState::set_texture_samplers(TypedArray<GLTFTextureSampler> p_texture_samplers) { + GLTFTemplateConvert::set_from_array(texture_samplers, p_texture_samplers); +} + TypedArray<Texture2D> GLTFState::get_images() { return GLTFTemplateConvert::to_array(images); } @@ -335,3 +360,11 @@ String GLTFState::get_base_path() { void GLTFState::set_base_path(String p_base_path) { base_path = p_base_path; } + +Variant GLTFState::get_additional_data(const StringName &p_extension_name) { + return additional_data[p_extension_name]; +} + +void GLTFState::set_additional_data(const StringName &p_extension_name, Variant p_additional_data) { + additional_data[p_extension_name] = p_additional_data; +} diff --git a/modules/gltf/gltf_state.h b/modules/gltf/gltf_state.h index 6b2d1ca228..e24017b0fd 100644 --- a/modules/gltf/gltf_state.h +++ b/modules/gltf/gltf_state.h @@ -42,6 +42,7 @@ #include "structures/gltf_skeleton.h" #include "structures/gltf_skin.h" #include "structures/gltf_texture.h" +#include "structures/gltf_texture_sampler.h" #include "core/templates/rb_map.h" #include "scene/animation/animation_player.h" @@ -77,7 +78,11 @@ class GLTFState : public Resource { String scene_name; Vector<int> root_nodes; Vector<Ref<GLTFTexture>> textures; + Vector<Ref<GLTFTextureSampler>> texture_samplers; + Ref<GLTFTextureSampler> default_texture_sampler; Vector<Ref<Texture2D>> images; + Vector<String> extensions_used; + Vector<String> extensions_required; Vector<Ref<GLTFSkin>> skins; Vector<Ref<GLTFCamera>> cameras; @@ -92,11 +97,14 @@ class GLTFState : public Resource { HashMap<ObjectID, GLTFSkeletonIndex> skeleton3d_to_gltf_skeleton; HashMap<ObjectID, HashMap<ObjectID, GLTFSkinIndex>> skin_and_skeleton3d_to_gltf_skin; + Dictionary additional_data; protected: static void _bind_methods(); public: + void add_used_extension(const String &p_extension, bool p_required = false); + Dictionary get_json(); void set_json(Dictionary p_json); @@ -145,6 +153,9 @@ public: TypedArray<GLTFTexture> get_textures(); void set_textures(TypedArray<GLTFTexture> p_textures); + TypedArray<GLTFTextureSampler> get_texture_samplers(); + void set_texture_samplers(TypedArray<GLTFTextureSampler> p_texture_samplers); + TypedArray<Texture2D> get_images(); void set_images(TypedArray<Texture2D> p_images); @@ -181,6 +192,9 @@ public: AnimationPlayer *get_animation_player(int idx); + Variant get_additional_data(const StringName &p_extension_name); + void set_additional_data(const StringName &p_extension_name, Variant p_additional_data); + //void set_scene_nodes(RBMap<GLTFNodeIndex, Node *> p_scene_nodes) { // this->scene_nodes = p_scene_nodes; //} diff --git a/modules/gltf/register_types.cpp b/modules/gltf/register_types.cpp index dbbccc9bcc..b9027f6e3d 100644 --- a/modules/gltf/register_types.cpp +++ b/modules/gltf/register_types.cpp @@ -47,6 +47,7 @@ #include "structures/gltf_skeleton.h" #include "structures/gltf_skin.h" #include "structures/gltf_texture.h" +#include "structures/gltf_texture_sampler.h" #ifdef TOOLS_ENABLED #include "core/config/project_settings.h" @@ -126,6 +127,7 @@ void initialize_gltf_module(ModuleInitializationLevel p_level) { GDREGISTER_CLASS(GLTFSpecGloss); GDREGISTER_CLASS(GLTFState); GDREGISTER_CLASS(GLTFTexture); + GDREGISTER_CLASS(GLTFTextureSampler); } #ifdef TOOLS_ENABLED @@ -142,6 +144,11 @@ void initialize_gltf_module(ModuleInitializationLevel p_level) { GLOBAL_DEF_RST("filesystem/import/fbx/enabled", true); GDREGISTER_CLASS(EditorSceneFormatImporterBlend); GDREGISTER_CLASS(EditorSceneFormatImporterFBX); + // Can't (a priori) run external app on these platforms. + GLOBAL_DEF_RST("filesystem/import/blender/enabled.android", false); + GLOBAL_DEF_RST("filesystem/import/blender/enabled.web", false); + GLOBAL_DEF_RST("filesystem/import/fbx/enabled.android", false); + GLOBAL_DEF_RST("filesystem/import/fbx/enabled.web", false); ClassDB::set_current_api(prev_api); EditorNode::add_init_callback(_editor_init); diff --git a/modules/gltf/register_types.h b/modules/gltf/register_types.h index 90b9a83c88..bf2730d2ef 100644 --- a/modules/gltf/register_types.h +++ b/modules/gltf/register_types.h @@ -28,7 +28,12 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ +#ifndef GLTF_REGISTER_TYPES_H +#define GLTF_REGISTER_TYPES_H + #include "modules/register_module_types.h" void initialize_gltf_module(ModuleInitializationLevel p_level); void uninitialize_gltf_module(ModuleInitializationLevel p_level); + +#endif // GLTF_REGISTER_TYPES_H diff --git a/modules/gltf/structures/gltf_node.cpp b/modules/gltf/structures/gltf_node.cpp index 86280603fa..6fd36f93b7 100644 --- a/modules/gltf/structures/gltf_node.cpp +++ b/modules/gltf/structures/gltf_node.cpp @@ -57,6 +57,8 @@ void GLTFNode::_bind_methods() { ClassDB::bind_method(D_METHOD("set_children", "children"), &GLTFNode::set_children); ClassDB::bind_method(D_METHOD("get_light"), &GLTFNode::get_light); ClassDB::bind_method(D_METHOD("set_light", "light"), &GLTFNode::set_light); + ClassDB::bind_method(D_METHOD("get_additional_data", "extension_name"), &GLTFNode::get_additional_data); + ClassDB::bind_method(D_METHOD("set_additional_data", "extension_name", "additional_data"), &GLTFNode::set_additional_data); ADD_PROPERTY(PropertyInfo(Variant::INT, "parent"), "set_parent", "get_parent"); // GLTFNodeIndex ADD_PROPERTY(PropertyInfo(Variant::INT, "height"), "set_height", "get_height"); // int @@ -176,3 +178,11 @@ GLTFLightIndex GLTFNode::get_light() { void GLTFNode::set_light(GLTFLightIndex p_light) { light = p_light; } + +Variant GLTFNode::get_additional_data(const StringName &p_extension_name) { + return additional_data[p_extension_name]; +} + +void GLTFNode::set_additional_data(const StringName &p_extension_name, Variant p_additional_data) { + additional_data[p_extension_name] = p_additional_data; +} diff --git a/modules/gltf/structures/gltf_node.h b/modules/gltf/structures/gltf_node.h index 1a57ea32e2..90a4fa99ed 100644 --- a/modules/gltf/structures/gltf_node.h +++ b/modules/gltf/structures/gltf_node.h @@ -53,6 +53,7 @@ private: Vector3 scale = Vector3(1, 1, 1); Vector<int> children; GLTFLightIndex light = -1; + Dictionary additional_data; protected: static void _bind_methods(); @@ -96,6 +97,9 @@ public: GLTFLightIndex get_light(); void set_light(GLTFLightIndex p_light); + + Variant get_additional_data(const StringName &p_extension_name); + void set_additional_data(const StringName &p_extension_name, Variant p_additional_data); }; #endif // GLTF_NODE_H diff --git a/modules/gltf/structures/gltf_texture.cpp b/modules/gltf/structures/gltf_texture.cpp index 2a21cb3df8..5cc96e3221 100644 --- a/modules/gltf/structures/gltf_texture.cpp +++ b/modules/gltf/structures/gltf_texture.cpp @@ -33,8 +33,11 @@ void GLTFTexture::_bind_methods() { ClassDB::bind_method(D_METHOD("get_src_image"), &GLTFTexture::get_src_image); ClassDB::bind_method(D_METHOD("set_src_image", "src_image"), &GLTFTexture::set_src_image); + ClassDB::bind_method(D_METHOD("get_sampler"), &GLTFTexture::get_sampler); + ClassDB::bind_method(D_METHOD("set_sampler", "sampler"), &GLTFTexture::set_sampler); ADD_PROPERTY(PropertyInfo(Variant::INT, "src_image"), "set_src_image", "get_src_image"); // int + ADD_PROPERTY(PropertyInfo(Variant::INT, "sampler"), "set_sampler", "get_sampler"); // int } GLTFImageIndex GLTFTexture::get_src_image() const { @@ -44,3 +47,11 @@ GLTFImageIndex GLTFTexture::get_src_image() const { void GLTFTexture::set_src_image(GLTFImageIndex val) { src_image = val; } + +GLTFTextureSamplerIndex GLTFTexture::get_sampler() const { + return sampler; +} + +void GLTFTexture::set_sampler(GLTFTextureSamplerIndex val) { + sampler = val; +} diff --git a/modules/gltf/structures/gltf_texture.h b/modules/gltf/structures/gltf_texture.h index b1d12dddfa..b26c8a7b07 100644 --- a/modules/gltf/structures/gltf_texture.h +++ b/modules/gltf/structures/gltf_texture.h @@ -39,6 +39,7 @@ class GLTFTexture : public Resource { private: GLTFImageIndex src_image = 0; + GLTFTextureSamplerIndex sampler = -1; protected: static void _bind_methods(); @@ -46,6 +47,8 @@ protected: public: GLTFImageIndex get_src_image() const; void set_src_image(GLTFImageIndex val); + GLTFTextureSamplerIndex get_sampler() const; + void set_sampler(GLTFTextureSamplerIndex val); }; #endif // GLTF_TEXTURE_H diff --git a/modules/gltf/structures/gltf_texture_sampler.cpp b/modules/gltf/structures/gltf_texture_sampler.cpp new file mode 100644 index 0000000000..6cf615b6cc --- /dev/null +++ b/modules/gltf/structures/gltf_texture_sampler.cpp @@ -0,0 +1,47 @@ +/*************************************************************************/ +/* gltf_texture_sampler.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 "gltf_texture_sampler.h" + +void GLTFTextureSampler::_bind_methods() { + ClassDB::bind_method(D_METHOD("get_mag_filter"), &GLTFTextureSampler::get_mag_filter); + ClassDB::bind_method(D_METHOD("set_mag_filter", "filter_mode"), &GLTFTextureSampler::set_mag_filter); + ClassDB::bind_method(D_METHOD("get_min_filter"), &GLTFTextureSampler::get_min_filter); + ClassDB::bind_method(D_METHOD("set_min_filter", "filter_mode"), &GLTFTextureSampler::set_min_filter); + ClassDB::bind_method(D_METHOD("get_wrap_s"), &GLTFTextureSampler::get_wrap_s); + ClassDB::bind_method(D_METHOD("set_wrap_s", "wrap_mode"), &GLTFTextureSampler::set_wrap_s); + ClassDB::bind_method(D_METHOD("get_wrap_t"), &GLTFTextureSampler::get_wrap_t); + ClassDB::bind_method(D_METHOD("set_wrap_t", "wrap_mode"), &GLTFTextureSampler::set_wrap_t); + + ADD_PROPERTY(PropertyInfo(Variant::INT, "mag_filter"), "set_mag_filter", "get_mag_filter"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "min_filter"), "set_min_filter", "get_min_filter"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "wrap_s"), "set_wrap_s", "get_wrap_s"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "wrap_t"), "set_wrap_t", "get_wrap_t"); +} diff --git a/modules/gltf/structures/gltf_texture_sampler.h b/modules/gltf/structures/gltf_texture_sampler.h new file mode 100644 index 0000000000..3fad31bbee --- /dev/null +++ b/modules/gltf/structures/gltf_texture_sampler.h @@ -0,0 +1,163 @@ +/*************************************************************************/ +/* gltf_texture_sampler.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 GLTF_TEXTURE_SAMPLER_H +#define GLTF_TEXTURE_SAMPLER_H + +#include "core/io/resource.h" +#include "scene/resources/material.h" + +class GLTFTextureSampler : public Resource { + GDCLASS(GLTFTextureSampler, Resource); + +public: + enum FilterMode { + NEAREST = 9728, + LINEAR = 9729, + NEAREST_MIPMAP_NEAREST = 9984, + LINEAR_MIPMAP_NEAREST = 9985, + NEAREST_MIPMAP_LINEAR = 9986, + LINEAR_MIPMAP_LINEAR = 9987 + }; + + enum WrapMode { + CLAMP_TO_EDGE = 33071, + MIRRORED_REPEAT = 33648, + REPEAT = 10497, + DEFAULT = REPEAT + }; + + int get_mag_filter() const { + return mag_filter; + } + + void set_mag_filter(const int filter_mode) { + mag_filter = (FilterMode)filter_mode; + } + + int get_min_filter() const { + return min_filter; + } + + void set_min_filter(const int filter_mode) { + min_filter = (FilterMode)filter_mode; + } + + int get_wrap_s() const { + return wrap_s; + } + + void set_wrap_s(const int wrap_mode) { + wrap_s = (WrapMode)wrap_mode; + } + + int get_wrap_t() const { + return wrap_t; + } + + void set_wrap_t(const int wrap_mode) { + wrap_s = (WrapMode)wrap_mode; + } + + StandardMaterial3D::TextureFilter get_filter_mode() const { + using TextureFilter = StandardMaterial3D::TextureFilter; + + switch (min_filter) { + case NEAREST: + return TextureFilter::TEXTURE_FILTER_NEAREST; + case LINEAR: + return TextureFilter::TEXTURE_FILTER_LINEAR; + case NEAREST_MIPMAP_NEAREST: + case NEAREST_MIPMAP_LINEAR: + return TextureFilter::TEXTURE_FILTER_NEAREST_WITH_MIPMAPS; + case LINEAR_MIPMAP_NEAREST: + case LINEAR_MIPMAP_LINEAR: + default: + return TextureFilter::TEXTURE_FILTER_LINEAR_WITH_MIPMAPS; + } + } + + void set_filter_mode(StandardMaterial3D::TextureFilter mode) { + using TextureFilter = StandardMaterial3D::TextureFilter; + + switch (mode) { + case TextureFilter::TEXTURE_FILTER_NEAREST: + min_filter = FilterMode::NEAREST; + mag_filter = FilterMode::NEAREST; + break; + case TextureFilter::TEXTURE_FILTER_LINEAR: + min_filter = FilterMode::LINEAR; + mag_filter = FilterMode::LINEAR; + break; + case TextureFilter::TEXTURE_FILTER_NEAREST_WITH_MIPMAPS: + case TextureFilter::TEXTURE_FILTER_NEAREST_WITH_MIPMAPS_ANISOTROPIC: + min_filter = FilterMode::NEAREST_MIPMAP_LINEAR; + mag_filter = FilterMode::NEAREST; + break; + case TextureFilter::TEXTURE_FILTER_LINEAR_WITH_MIPMAPS: + case TextureFilter::TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC: + default: + min_filter = FilterMode::LINEAR_MIPMAP_LINEAR; + mag_filter = FilterMode::LINEAR; + break; + } + } + + bool get_wrap_mode() const { + // BaseMaterial3D presents wrapping as a boolean property. Either the texture is repeated + // in both dimensions, non-mirrored, or it isn't repeated at all. This will cause oddities + // when people import models having other wrapping mode combinations. + return (wrap_s == WrapMode::REPEAT) && (wrap_t == WrapMode::REPEAT); + } + + void set_wrap_mode(bool mat_repeats) { + if (mat_repeats) { + wrap_s = WrapMode::REPEAT; + wrap_t = WrapMode::REPEAT; + } else { + wrap_s = WrapMode::CLAMP_TO_EDGE; + wrap_t = WrapMode::CLAMP_TO_EDGE; + } + } + +protected: + static void _bind_methods(); + +private: + FilterMode mag_filter = FilterMode::LINEAR; + FilterMode min_filter = FilterMode::LINEAR_MIPMAP_LINEAR; + WrapMode wrap_s = WrapMode::REPEAT; + WrapMode wrap_t = WrapMode::REPEAT; +}; + +VARIANT_ENUM_CAST(GLTFTextureSampler::FilterMode); +VARIANT_ENUM_CAST(GLTFTextureSampler::WrapMode); + +#endif // GLTF_TEXTURE_SAMPLER_H diff --git a/modules/gridmap/SCsub b/modules/gridmap/SCsub index da3f7d4dd9..282d772592 100644 --- a/modules/gridmap/SCsub +++ b/modules/gridmap/SCsub @@ -7,5 +7,5 @@ env_gridmap = env_modules.Clone() # Godot source files env_gridmap.add_source_files(env.modules_sources, "*.cpp") -if env["tools"]: +if env.editor_build: env_gridmap.add_source_files(env.modules_sources, "editor/*.cpp") diff --git a/modules/gridmap/doc_classes/GridMap.xml b/modules/gridmap/doc_classes/GridMap.xml index ed6cb8656a..0f3662c3cf 100644 --- a/modules/gridmap/doc_classes/GridMap.xml +++ b/modules/gridmap/doc_classes/GridMap.xml @@ -57,7 +57,7 @@ <return type="Basis" /> <param index="0" name="position" type="Vector3i" /> <description> - Returns the basis that gives the specificed cell its orientation. + Returns the basis that gives the specified cell its orientation. </description> </method> <method name="get_cell_item_orientation" qualifiers="const"> diff --git a/modules/gridmap/editor/grid_map_editor_plugin.cpp b/modules/gridmap/editor/grid_map_editor_plugin.cpp index b5afd8507d..9c6cbebf0e 100644 --- a/modules/gridmap/editor/grid_map_editor_plugin.cpp +++ b/modules/gridmap/editor/grid_map_editor_plugin.cpp @@ -617,7 +617,7 @@ EditorPlugin::AfterGUIInput GridMapEditor::forward_spatial_input_event(Camera3D } if (mb->is_pressed()) { - Node3DEditorViewport::NavigationScheme nav_scheme = (Node3DEditorViewport::NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int(); + Node3DEditorViewport::NavigationScheme nav_scheme = (Node3DEditorViewport::NavigationScheme)EDITOR_GET("editors/3d/navigation/navigation_scheme").operator int(); if ((nav_scheme == Node3DEditorViewport::NAVIGATION_MAYA || nav_scheme == Node3DEditorViewport::NAVIGATION_MODO) && mb->is_alt_pressed()) { input_action = INPUT_NONE; } else if (mb->get_button_index() == MouseButton::LEFT) { @@ -1434,7 +1434,7 @@ GridMapEditor::~GridMapEditor() { void GridMapEditorPlugin::_notification(int p_what) { switch (p_what) { case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { - switch ((int)EditorSettings::get_singleton()->get("editors/grid_map/editor_side")) { + switch ((int)EDITOR_GET("editors/grid_map/editor_side")) { case 0: { // Left. Node3DEditor::get_singleton()->move_control_to_left_panel(grid_map_editor); } break; @@ -1472,7 +1472,7 @@ GridMapEditorPlugin::GridMapEditorPlugin() { EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT, "editors/grid_map/editor_side", PROPERTY_HINT_ENUM, "Left,Right")); grid_map_editor = memnew(GridMapEditor); - switch ((int)EditorSettings::get_singleton()->get("editors/grid_map/editor_side")) { + switch ((int)EDITOR_GET("editors/grid_map/editor_side")) { case 0: { // Left. Node3DEditor::get_singleton()->add_control_to_left_panel(grid_map_editor); } break; diff --git a/modules/gridmap/editor/grid_map_editor_plugin.h b/modules/gridmap/editor/grid_map_editor_plugin.h index a64dc4a80b..91f14690ca 100644 --- a/modules/gridmap/editor/grid_map_editor_plugin.h +++ b/modules/gridmap/editor/grid_map_editor_plugin.h @@ -35,11 +35,14 @@ #include "../grid_map.h" #include "editor/editor_plugin.h" +#include "scene/gui/box_container.h" #include "scene/gui/item_list.h" #include "scene/gui/slider.h" #include "scene/gui/spin_box.h" +class ConfirmationDialog; class EditorUndoRedoManager; +class MenuButton; class Node3DEditorPlugin; class GridMapEditor : public VBoxContainer { @@ -241,7 +244,7 @@ protected: void _notification(int p_what); public: - virtual EditorPlugin::AfterGUIInput forward_spatial_gui_input(Camera3D *p_camera, const Ref<InputEvent> &p_event) override { return grid_map_editor->forward_spatial_input_event(p_camera, p_event); } + virtual EditorPlugin::AfterGUIInput forward_3d_gui_input(Camera3D *p_camera, const Ref<InputEvent> &p_event) override { return grid_map_editor->forward_spatial_input_event(p_camera, p_event); } virtual String get_name() const override { return "GridMap"; } bool has_main_screen() const override { return false; } virtual void edit(Object *p_object) override; diff --git a/modules/gridmap/grid_map.cpp b/modules/gridmap/grid_map.cpp index 466a2efd21..de50e9ea1e 100644 --- a/modules/gridmap/grid_map.cpp +++ b/modules/gridmap/grid_map.cpp @@ -157,13 +157,13 @@ uint32_t GridMap::get_collision_mask() const { void GridMap::set_collision_layer_value(int p_layer_number, bool p_value) { ERR_FAIL_COND_MSG(p_layer_number < 1, "Collision layer number must be between 1 and 32 inclusive."); ERR_FAIL_COND_MSG(p_layer_number > 32, "Collision layer number must be between 1 and 32 inclusive."); - uint32_t collision_layer = get_collision_layer(); + uint32_t collision_layer_new = get_collision_layer(); if (p_value) { - collision_layer |= 1 << (p_layer_number - 1); + collision_layer_new |= 1 << (p_layer_number - 1); } else { - collision_layer &= ~(1 << (p_layer_number - 1)); + collision_layer_new &= ~(1 << (p_layer_number - 1)); } - set_collision_layer(collision_layer); + set_collision_layer(collision_layer_new); } bool GridMap::get_collision_layer_value(int p_layer_number) const { @@ -1149,7 +1149,7 @@ TypedArray<Vector3i> GridMap::get_used_cells() const { TypedArray<Vector3i> GridMap::get_used_cells_by_item(int p_item) const { TypedArray<Vector3i> a; for (const KeyValue<IndexKey, Cell> &E : cell_map) { - if (E.value.item == p_item) { + if ((int)E.value.item == p_item) { Vector3i p(E.key.x, E.key.y, E.key.z); a.push_back(p); } diff --git a/modules/hdr/image_loader_hdr.cpp b/modules/hdr/image_loader_hdr.cpp index e7c6fe592d..457b263e16 100644 --- a/modules/hdr/image_loader_hdr.cpp +++ b/modules/hdr/image_loader_hdr.cpp @@ -33,7 +33,7 @@ #include "core/os/os.h" #include "core/string/print_string.h" -Error ImageLoaderHDR::load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale) { +Error ImageLoaderHDR::load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale) { String header = f->get_token(); ERR_FAIL_COND_V_MSG(header != "#?RADIANCE" && header != "#?RGBE", ERR_FILE_UNRECOGNIZED, "Unsupported header information in HDR: " + header + "."); @@ -140,7 +140,7 @@ Error ImageLoaderHDR::load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t } } - p_image->create(width, height, false, Image::FORMAT_RGBE9995, imgdata); + p_image->set_data(width, height, false, Image::FORMAT_RGBE9995, imgdata); return OK; } diff --git a/modules/hdr/image_loader_hdr.h b/modules/hdr/image_loader_hdr.h index 1bff05129b..5f817f0ba8 100644 --- a/modules/hdr/image_loader_hdr.h +++ b/modules/hdr/image_loader_hdr.h @@ -35,7 +35,7 @@ class ImageLoaderHDR : public ImageFormatLoader { public: - virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale); + virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale); virtual void get_recognized_extensions(List<String> *p_extensions) const; ImageLoaderHDR(); }; diff --git a/modules/hdr/register_types.cpp b/modules/hdr/register_types.cpp index b988bf4587..18b1a73f1c 100644 --- a/modules/hdr/register_types.cpp +++ b/modules/hdr/register_types.cpp @@ -32,14 +32,14 @@ #include "image_loader_hdr.h" -static ImageLoaderHDR *image_loader_hdr = nullptr; +static Ref<ImageLoaderHDR> image_loader_hdr; void initialize_hdr_module(ModuleInitializationLevel p_level) { if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) { return; } - image_loader_hdr = memnew(ImageLoaderHDR); + image_loader_hdr.instantiate(); ImageLoader::add_image_format_loader(image_loader_hdr); } @@ -48,5 +48,6 @@ void uninitialize_hdr_module(ModuleInitializationLevel p_level) { return; } - memdelete(image_loader_hdr); + ImageLoader::remove_image_format_loader(image_loader_hdr); + image_loader_hdr.unref(); } diff --git a/modules/jpg/image_loader_jpegd.cpp b/modules/jpg/image_loader_jpegd.cpp index 3e138bf633..9bbe467352 100644 --- a/modules/jpg/image_loader_jpegd.cpp +++ b/modules/jpg/image_loader_jpegd.cpp @@ -33,8 +33,8 @@ #include "core/os/os.h" #include "core/string/print_string.h" -#include "thirdparty/jpeg-compressor/jpgd.h" -#include "thirdparty/jpeg-compressor/jpge.h" +#include <jpgd.h> +#include <jpge.h> #include <string.h> Error jpeg_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p_buffer_len) { @@ -99,12 +99,12 @@ Error jpeg_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p fmt = Image::FORMAT_RGB8; } - p_image->create(image_width, image_height, false, fmt, data); + p_image->set_data(image_width, image_height, false, fmt, data); return OK; } -Error ImageLoaderJPG::load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale) { +Error ImageLoaderJPG::load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale) { Vector<uint8_t> src_image; uint64_t src_image_len = f->get_length(); ERR_FAIL_COND_V(src_image_len == 0, ERR_FILE_CORRUPT); @@ -132,10 +132,6 @@ static Ref<Image> _jpegd_mem_loader_func(const uint8_t *p_png, int p_size) { return img; } -static Error _jpgd_save_func(const String &p_path, const Ref<Image> &p_img, float p_quality) { - return OK; -} - class ImageLoaderJPGOSFile : public jpge::output_stream { public: Ref<FileAccess> f; @@ -157,21 +153,18 @@ public: } }; -static Vector<uint8_t> _jpgd_buffer_save_func(const Ref<Image> &p_img, float p_quality) { - ERR_FAIL_COND_V(p_img.is_null() || p_img->is_empty(), Vector<uint8_t>()); +static Error _jpgd_save_to_output_stream(jpge::output_stream *p_output_stream, const Ref<Image> &p_img, float p_quality) { + ERR_FAIL_COND_V(p_img.is_null() || p_img->is_empty(), ERR_INVALID_PARAMETER); Ref<Image> image = p_img; if (image->get_format() != Image::FORMAT_RGB8) { - image->convert(Image::FORMAT_ETC2_RGB8); + image->convert(Image::FORMAT_RGB8); } jpge::params p; p.m_quality = CLAMP(p_quality * 100, 1, 100); - Vector<uint8_t> output; - ImageLoaderJPGOSBuffer ob; - ob.buffer = &output; jpge::jpeg_encoder enc; - enc.init(&ob, image->get_width(), image->get_height(), 3, p); + enc.init(p_output_stream, image->get_width(), image->get_height(), 3, p); const uint8_t *src_data = image->get_data().ptr(); for (int i = 0; i < image->get_height(); i++) { @@ -180,9 +173,28 @@ static Vector<uint8_t> _jpgd_buffer_save_func(const Ref<Image> &p_img, float p_q enc.process_scanline(nullptr); + return OK; +} + +static Vector<uint8_t> _jpgd_buffer_save_func(const Ref<Image> &p_img, float p_quality) { + Vector<uint8_t> output; + ImageLoaderJPGOSBuffer ob; + ob.buffer = &output; + if (_jpgd_save_to_output_stream(&ob, p_img, p_quality) != OK) { + return Vector<uint8_t>(); + } return output; } +static Error _jpgd_save_func(const String &p_path, const Ref<Image> &p_img, float p_quality) { + Error err; + Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err); + ERR_FAIL_COND_V_MSG(err, err, vformat("Can't save JPG at path: '%s'.", p_path)); + ImageLoaderJPGOSFile ob; + ob.f = file; + return _jpgd_save_to_output_stream(&ob, p_img, p_quality); +} + ImageLoaderJPG::ImageLoaderJPG() { Image::_jpg_mem_loader_func = _jpegd_mem_loader_func; Image::save_jpg_func = _jpgd_save_func; diff --git a/modules/jpg/image_loader_jpegd.h b/modules/jpg/image_loader_jpegd.h index caa0461d05..f63db51521 100644 --- a/modules/jpg/image_loader_jpegd.h +++ b/modules/jpg/image_loader_jpegd.h @@ -35,7 +35,7 @@ class ImageLoaderJPG : public ImageFormatLoader { public: - virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale); + virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale); virtual void get_recognized_extensions(List<String> *p_extensions) const; ImageLoaderJPG(); }; diff --git a/modules/jpg/register_types.cpp b/modules/jpg/register_types.cpp index b8b48a550f..7da216bbe2 100644 --- a/modules/jpg/register_types.cpp +++ b/modules/jpg/register_types.cpp @@ -32,14 +32,14 @@ #include "image_loader_jpegd.h" -static ImageLoaderJPG *image_loader_jpg = nullptr; +static Ref<ImageLoaderJPG> image_loader_jpg; void initialize_jpg_module(ModuleInitializationLevel p_level) { if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) { return; } - image_loader_jpg = memnew(ImageLoaderJPG); + image_loader_jpg.instantiate(); ImageLoader::add_image_format_loader(image_loader_jpg); } @@ -48,5 +48,6 @@ void uninitialize_jpg_module(ModuleInitializationLevel p_level) { return; } - memdelete(image_loader_jpg); + ImageLoader::remove_image_format_loader(image_loader_jpg); + image_loader_jpg.unref(); } diff --git a/modules/lightmapper_rd/lightmapper_rd.cpp b/modules/lightmapper_rd/lightmapper_rd.cpp index 5b039e65c0..9111827c1b 100644 --- a/modules/lightmapper_rd/lightmapper_rd.cpp +++ b/modules/lightmapper_rd/lightmapper_rd.cpp @@ -251,15 +251,11 @@ Lightmapper::BakeError LightmapperRD::_blit_meshes_into_atlas(int p_max_texture_ } for (int i = 0; i < atlas_slices; i++) { - Ref<Image> albedo; - albedo.instantiate(); - albedo->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBA8); + Ref<Image> albedo = Image::create_empty(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBA8); albedo->set_as_black(); albedo_images.write[i] = albedo; - Ref<Image> emission; - emission.instantiate(); - emission->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH); + Ref<Image> emission = Image::create_empty(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH); emission->set_as_black(); emission_images.write[i] = emission; } @@ -278,7 +274,7 @@ Lightmapper::BakeError LightmapperRD::_blit_meshes_into_atlas(int p_max_texture_ return BAKE_OK; } -void LightmapperRD::_create_acceleration_structures(RenderingDevice *rd, Size2i atlas_size, int atlas_slices, AABB &bounds, int grid_size, Vector<Probe> &probe_positions, GenerateProbes p_generate_probes, Vector<int> &slice_triangle_count, Vector<int> &slice_seam_count, RID &vertex_buffer, RID &triangle_buffer, RID &lights_buffer, RID &triangle_cell_indices_buffer, RID &probe_positions_buffer, RID &grid_texture, RID &seams_buffer, BakeStepFunc p_step_function, void *p_bake_userdata) { +void LightmapperRD::_create_acceleration_structures(RenderingDevice *rd, Size2i atlas_size, int atlas_slices, AABB &bounds, int grid_size, Vector<Probe> &p_probe_positions, GenerateProbes p_generate_probes, Vector<int> &slice_triangle_count, Vector<int> &slice_seam_count, RID &vertex_buffer, RID &triangle_buffer, RID &lights_buffer, RID &triangle_cell_indices_buffer, RID &probe_positions_buffer, RID &grid_texture, RID &seams_buffer, BakeStepFunc p_step_function, void *p_bake_userdata) { HashMap<Vertex, uint32_t, VertexHash> vertex_map; //fill triangles array and vertex array @@ -403,8 +399,8 @@ void LightmapperRD::_create_acceleration_structures(RenderingDevice *rd, Size2i } //also consider probe positions for bounds - for (int i = 0; i < probe_positions.size(); i++) { - Vector3 pp(probe_positions[i].position[0], probe_positions[i].position[1], probe_positions[i].position[2]); + for (int i = 0; i < p_probe_positions.size(); i++) { + Vector3 pp(p_probe_positions[i].position[0], p_probe_positions[i].position[1], p_probe_positions[i].position[2]); bounds.expand_to(pp); } bounds.grow_by(0.1); //grow a bit to avoid numerical error @@ -478,9 +474,7 @@ void LightmapperRD::_create_acceleration_structures(RenderingDevice *rd, Size2i grid_usage.write[j] = count > 0 ? 255 : 0; } - Ref<Image> img; - img.instantiate(); - img->create(grid_size, grid_size, false, Image::FORMAT_L8, grid_usage); + Ref<Image> img = Image::create_from_data(grid_size, grid_size, false, Image::FORMAT_L8, grid_usage); img->save_png("res://grid_layer_" + itos(1000 + i).substr(1, 3) + ".png"); } #endif @@ -520,7 +514,7 @@ void LightmapperRD::_create_acceleration_structures(RenderingDevice *rd, Size2i } seams_buffer = rd->storage_buffer_create(sb.size(), sb); - Vector<uint8_t> pb = probe_positions.to_byte_array(); + Vector<uint8_t> pb = p_probe_positions.to_byte_array(); if (pb.size() == 0) { pb.resize(sizeof(Probe)); } @@ -660,9 +654,7 @@ LightmapperRD::BakeError LightmapperRD::_dilate(RenderingDevice *rd, Ref<RDShade #ifdef DEBUG_TEXTURES for (int i = 0; i < atlas_slices; i++) { Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i); - Ref<Image> img; - img.instantiate(); - img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); + Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); img->convert(Image::FORMAT_RGBA8); img->save_png("res://5_dilated_" + itos(i) + ".png"); } @@ -778,7 +770,7 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d panorama_tex->convert(Image::FORMAT_RGBAF); } else { panorama_tex.instantiate(); - panorama_tex->create(8, 8, false, Image::FORMAT_RGBAF); + panorama_tex->initialize_data(8, 8, false, Image::FORMAT_RGBAF); panorama_tex->fill(Color(0, 0, 0, 1)); } @@ -953,13 +945,11 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d for (int i = 0; i < atlas_slices; i++) { Vector<uint8_t> s = rd->texture_get_data(position_tex, i); - Ref<Image> img; - img.instantiate(); - img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAF, s); + Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAF, s); img->save_exr("res://1_position_" + itos(i) + ".exr", false); s = rd->texture_get_data(normal_tex, i); - img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); + img->set_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); img->save_exr("res://1_normal_" + itos(i) + ".exr", false); } #endif @@ -1182,9 +1172,7 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d for (int i = 0; i < atlas_slices; i++) { Vector<uint8_t> s = rd->texture_get_data(light_source_tex, i); - Ref<Image> img; - img.instantiate(); - img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); + Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); img->save_exr("res://2_light_primary_" + itos(i) + ".exr", false); } #endif @@ -1415,14 +1403,10 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d #if 0 for (int i = 0; i < probe_positions.size(); i++) { - Ref<Image> img; - img.instantiate(); - img->create(6, 4, false, Image::FORMAT_RGB8); + Ref<Image> img = Image::create_empty(6, 4, false, Image::FORMAT_RGB8); for (int j = 0; j < 6; j++) { Vector<uint8_t> s = rd->texture_get_data(lightprobe_tex, i * 6 + j); - Ref<Image> img2; - img2.instantiate(); - img2->create(2, 2, false, Image::FORMAT_RGBAF, s); + Ref<Image> img2 = Image::create_from_data(2, 2, false, Image::FORMAT_RGBAF, s); img2->convert(Image::FORMAT_RGB8); img->blit_rect(img2, Rect2i(0, 0, 2, 2), Point2i((j % 3) * 2, (j / 3) * 2)); } @@ -1449,9 +1433,7 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d if (denoiser.is_valid()) { for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) { Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i); - Ref<Image> img; - img.instantiate(); - img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); + Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); Ref<Image> denoised = denoiser->denoise_image(img); if (denoised != img) { @@ -1484,9 +1466,7 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) { Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i); - Ref<Image> img; - img.instantiate(); - img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); + Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); img->save_exr("res://4_light_secondary_" + itos(i) + ".exr", false); } #endif @@ -1640,9 +1620,7 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) { Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i); - Ref<Image> img; - img.instantiate(); - img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); + Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); img->save_exr("res://5_blendseams" + itos(i) + ".exr", false); } #endif @@ -1652,9 +1630,7 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) { Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i); - Ref<Image> img; - img.instantiate(); - img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); + Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); img->convert(Image::FORMAT_RGBH); //remove alpha bake_textures.push_back(img); } @@ -1667,9 +1643,7 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d #ifdef DEBUG_TEXTURES { - Ref<Image> img2; - img2.instantiate(); - img2->create(probe_values.size(), 1, false, Image::FORMAT_RGBAF, probe_data); + Ref<Image> img2 = Image::create_from_data(probe_values.size(), 1, false, Image::FORMAT_RGBAF, probe_data); img2->save_exr("res://6_lightprobes.exr", false); } #endif diff --git a/modules/lightmapper_rd/register_types.cpp b/modules/lightmapper_rd/register_types.cpp index 0e0330c1a1..ed223e1faa 100644 --- a/modules/lightmapper_rd/register_types.cpp +++ b/modules/lightmapper_rd/register_types.cpp @@ -57,6 +57,7 @@ void initialize_lightmapper_rd_module(ModuleInitializationLevel p_level) { GLOBAL_DEF("rendering/lightmapping/bake_quality/high_quality_probe_ray_count", 512); GLOBAL_DEF("rendering/lightmapping/bake_quality/ultra_quality_probe_ray_count", 2048); GLOBAL_DEF("rendering/lightmapping/bake_performance/max_rays_per_probe_pass", 64); + GLOBAL_DEF("rendering/lightmapping/primitive_meshes/texel_size", 0.2); #ifndef _3D_DISABLED GDREGISTER_CLASS(LightmapperRD); Lightmapper::create_gpu = create_lightmapper_rd; diff --git a/modules/mbedtls/stream_peer_mbedtls.cpp b/modules/mbedtls/stream_peer_mbedtls.cpp index a97c6bd916..26cd3bc3f9 100644 --- a/modules/mbedtls/stream_peer_mbedtls.cpp +++ b/modules/mbedtls/stream_peer_mbedtls.cpp @@ -242,7 +242,7 @@ void StreamPeerMbedTLS::poll() { return; } - // We could pass nullptr as second parameter, but some behaviour sanitizers don't seem to like that. + // We could pass nullptr as second parameter, but some behavior sanitizers don't seem to like that. // Passing a 1 byte buffer to workaround it. uint8_t byte; int ret = mbedtls_ssl_read(tls_ctx->get_context(), &byte, 0); diff --git a/modules/minimp3/audio_stream_mp3.cpp b/modules/minimp3/audio_stream_mp3.cpp index 98bcdea8f4..acb92b25e1 100644 --- a/modules/minimp3/audio_stream_mp3.cpp +++ b/modules/minimp3/audio_stream_mp3.cpp @@ -104,7 +104,7 @@ float AudioStreamPlaybackMP3::get_stream_sampling_rate() { return mp3_stream->sample_rate; } -void AudioStreamPlaybackMP3::start(float p_from_pos) { +void AudioStreamPlaybackMP3::start(double p_from_pos) { active = true; seek(p_from_pos); loops = 0; @@ -123,11 +123,11 @@ int AudioStreamPlaybackMP3::get_loop_count() const { return loops; } -float AudioStreamPlaybackMP3::get_playback_position() const { - return float(frames_mixed) / mp3_stream->sample_rate; +double AudioStreamPlaybackMP3::get_playback_position() const { + return double(frames_mixed) / mp3_stream->sample_rate; } -void AudioStreamPlaybackMP3::seek(float p_time) { +void AudioStreamPlaybackMP3::seek(double p_time) { if (!active) { return; } @@ -217,15 +217,15 @@ bool AudioStreamMP3::has_loop() const { return loop; } -void AudioStreamMP3::set_loop_offset(float p_seconds) { +void AudioStreamMP3::set_loop_offset(double p_seconds) { loop_offset = p_seconds; } -float AudioStreamMP3::get_loop_offset() const { +double AudioStreamMP3::get_loop_offset() const { return loop_offset; } -float AudioStreamMP3::get_length() const { +double AudioStreamMP3::get_length() const { return length; } diff --git a/modules/minimp3/audio_stream_mp3.h b/modules/minimp3/audio_stream_mp3.h index 428ac1240e..c34c1dc5fa 100644 --- a/modules/minimp3/audio_stream_mp3.h +++ b/modules/minimp3/audio_stream_mp3.h @@ -61,14 +61,14 @@ protected: virtual float get_stream_sampling_rate() override; public: - virtual void start(float p_from_pos = 0.0) override; + virtual void start(double p_from_pos = 0.0) override; virtual void stop() override; virtual bool is_playing() const override; virtual int get_loop_count() const override; //times it looped - virtual float get_playback_position() const override; - virtual void seek(float p_time) override; + virtual double get_playback_position() const override; + virtual void seek(double p_time) override; virtual void tag_used_streams() override; @@ -104,8 +104,8 @@ public: void set_loop(bool p_enable); virtual bool has_loop() const override; - void set_loop_offset(float p_seconds); - float get_loop_offset() const; + void set_loop_offset(double p_seconds); + double get_loop_offset() const; void set_bpm(double p_bpm); virtual double get_bpm() const override; @@ -122,7 +122,7 @@ public: void set_data(const Vector<uint8_t> &p_data); Vector<uint8_t> get_data() const; - virtual float get_length() const override; + virtual double get_length() const override; virtual bool is_monophonic() const override; diff --git a/modules/mobile_vr/doc_classes/MobileVRInterface.xml b/modules/mobile_vr/doc_classes/MobileVRInterface.xml index db186079b0..63592042c7 100644 --- a/modules/mobile_vr/doc_classes/MobileVRInterface.xml +++ b/modules/mobile_vr/doc_classes/MobileVRInterface.xml @@ -6,7 +6,7 @@ <description> This is a generic mobile VR implementation where you need to provide details about the phone and HMD used. It does not rely on any existing framework. This is the most basic interface we have. For the best effect, you need a mobile phone with a gyroscope and accelerometer. Note that even though there is no positional tracking, the camera will assume the headset is at a height of 1.85 meters. You can change this by setting [member eye_height]. - You can initialise this interface as follows: + You can initialize this interface as follows: [codeblock] var interface = XRServer.find_interface("Native mobile") if interface and interface.initialize(): diff --git a/modules/mobile_vr/mobile_vr_interface.cpp b/modules/mobile_vr/mobile_vr_interface.cpp index b14f5f469c..582be98d61 100644 --- a/modules/mobile_vr/mobile_vr_interface.cpp +++ b/modules/mobile_vr/mobile_vr_interface.cpp @@ -155,7 +155,7 @@ void MobileVRInterface::set_position_from_sensors() { last_magnetometer_data = magneto; if (grav.length() < 0.1) { - // not ideal but use our accelerometer, this will contain shaky user behaviour + // not ideal but use our accelerometer, this will contain shaky user behavior // maybe look into some math but I'm guessing that if this isn't available, it's because we lack the gyro sensor to actually work out // what a stable gravity vector is grav = acc; diff --git a/modules/mobile_vr/register_types.cpp b/modules/mobile_vr/register_types.cpp index 4df8af9009..dd35b3d164 100644 --- a/modules/mobile_vr/register_types.cpp +++ b/modules/mobile_vr/register_types.cpp @@ -53,7 +53,7 @@ void uninitialize_mobile_vr_module(ModuleInitializationLevel p_level) { } if (mobile_vr.is_valid()) { - // uninitialise our interface if it is initialised + // uninitialize our interface if it is initialized if (mobile_vr->is_initialized()) { mobile_vr->uninitialize(); } diff --git a/modules/mono/.gitignore b/modules/mono/.gitignore index fa6d00cbbb..2d62f9f88a 100644 --- a/modules/mono/.gitignore +++ b/modules/mono/.gitignore @@ -1,2 +1,5 @@ # Do not ignore solution files inside the mono module. Overrides Godot's global gitignore. !*.sln + +# Generated by build_assemblies.py. +SdkPackageVersions.props diff --git a/modules/mono/Directory.Build.targets b/modules/mono/Directory.Build.targets index 98410b93ae..e666b3ac9d 100644 --- a/modules/mono/Directory.Build.targets +++ b/modules/mono/Directory.Build.targets @@ -2,6 +2,8 @@ <PropertyGroup> <_HasNuGetPackage Condition=" '$(_HasNuGetPackage)' == '' And '$(PackageId)' != '' And '$(GeneratePackageOnBuild.ToLower())' == 'true' ">true</_HasNuGetPackage> <_HasNuGetPackage Condition=" '$(_HasNuGetPackage)' == '' ">false</_HasNuGetPackage> + <_HasSymbolsNuGetPackage Condition=" '$(_HasSymbolsNuGetPackage)' == '' And '$(PackageId)' != '' And '$(IncludeSymbols.ToLower())' == 'true' And '$(SymbolPackageFormat)' == 'snupkg' ">true</_HasSymbolsNuGetPackage> + <_HasSymbolsNuGetPackage Condition=" '$(_HasSymbolsNuGetPackage)' == '' ">false</_HasSymbolsNuGetPackage> </PropertyGroup> <Target Name="CopyNupkgToSConsOutputDir" AfterTargets="Pack" Condition=" '$(_HasNuGetPackage)' == 'true' "> @@ -10,13 +12,15 @@ <GodotOutputDataDir>$(GodotSourceRootPath)\bin\GodotSharp\</GodotOutputDataDir> </PropertyGroup> <Copy SourceFiles="$(PackageOutputPath)$(PackageId).$(PackageVersion).nupkg" DestinationFolder="$(GodotOutputDataDir)Tools\nupkgs\" /> + <Copy Condition=" '$(_HasSymbolsNuGetPackage)' == 'true' " SourceFiles="$(PackageOutputPath)$(PackageId).$(PackageVersion).snupkg" DestinationFolder="$(GodotOutputDataDir)Tools\nupkgs\" /> </Target> <Target Name="PushNuGetPackagesToLocalSource" BeforeTargets="Pack" Condition=" '$(_HasNuGetPackage)' == 'true' And '$(PushNuGetToLocalSource)' != '' "> <Copy SourceFiles="$(PackageOutputPath)$(PackageId).$(PackageVersion).nupkg" DestinationFolder="$(PushNuGetToLocalSource)\" /> + <Copy Condition=" '$(_HasSymbolsNuGetPackage)' == 'true' " SourceFiles="$(PackageOutputPath)$(PackageId).$(PackageVersion).snupkg" DestinationFolder="$(PushNuGetToLocalSource)\" /> </Target> <Target Name="ClearNuGetLocalPackageCache" BeforeTargets="Pack" Condition=" '$(_HasNuGetPackage)' == 'true' And '$(ClearNuGetLocalCache.ToLower())' == 'true' "> - <RemoveDir Directories="$(NugetPackageRoot)/$(PackageId.ToLower())/$(PackageVersion)"/> + <RemoveDir Directories="$(NugetPackageRoot)/$(PackageId.ToLower())/$(PackageVersion)" /> </Target> </Project> diff --git a/modules/mono/SCsub b/modules/mono/SCsub index 7764ba0b45..a4667f784d 100644 --- a/modules/mono/SCsub +++ b/modules/mono/SCsub @@ -26,6 +26,6 @@ if env["platform"] in ["macos", "ios"]: elif env["platform"] == "android": env_mono.add_source_files(env.modules_sources, "mono_gd/android_mono_config.gen.cpp") -if env["tools"]: +if env.editor_build: env_mono.add_source_files(env.modules_sources, "editor/*.cpp") SConscript("editor/script_templates/SCsub") diff --git a/modules/mono/SdkPackageVersions.props b/modules/mono/SdkPackageVersions.props deleted file mode 100644 index 65094aa34f..0000000000 --- a/modules/mono/SdkPackageVersions.props +++ /dev/null @@ -1,8 +0,0 @@ -<Project> - <PropertyGroup> - <PackageFloatingVersion_Godot>4.0.*-*</PackageFloatingVersion_Godot> - <PackageVersion_GodotSharp>4.0.0-dev</PackageVersion_GodotSharp> - <PackageVersion_Godot_NET_Sdk>4.0.0-dev8</PackageVersion_Godot_NET_Sdk> - <PackageVersion_Godot_SourceGenerators>4.0.0-dev8</PackageVersion_Godot_SourceGenerators> - </PropertyGroup> -</Project> diff --git a/modules/mono/build_scripts/build_assemblies.py b/modules/mono/build_scripts/build_assemblies.py index 6f66ce9efa..7343af0b39 100755 --- a/modules/mono/build_scripts/build_assemblies.py +++ b/modules/mono/build_scripts/build_assemblies.py @@ -5,6 +5,7 @@ import os.path import shlex import subprocess from dataclasses import dataclass +from typing import Optional, List def find_dotnet_cli(): @@ -150,10 +151,7 @@ def find_any_msbuild_tool(mono_prefix): return None -def run_msbuild(tools: ToolsLocation, sln: str, msbuild_args: [str] = None): - if msbuild_args is None: - msbuild_args = [] - +def run_msbuild(tools: ToolsLocation, sln: str, msbuild_args: Optional[List[str]] = None): using_msbuild_mono = False # Preference order: dotnet CLI > Standalone MSBuild > Mono's MSBuild @@ -169,7 +167,7 @@ def run_msbuild(tools: ToolsLocation, sln: str, msbuild_args: [str] = None): args += [sln] - if len(msbuild_args) > 0: + if msbuild_args: args += msbuild_args print("Running MSBuild: ", " ".join(shlex.quote(arg) for arg in args), flush=True) @@ -258,7 +256,57 @@ def build_godot_api(msbuild_tool, module_dir, output_dir, push_nupkgs_local, flo return 0 +def generate_sdk_package_versions(): + # I can't believe importing files in Python is so convoluted when not + # following the golden standard for packages/modules. + import os + import sys + from os.path import dirname + + # We want ../../../methods.py. + script_path = dirname(os.path.abspath(__file__)) + root_path = dirname(dirname(dirname(script_path))) + + sys.path.insert(0, root_path) + from methods import get_version_info + + version_info = get_version_info("") + sys.path.remove(root_path) + + version_str = "{major}.{minor}.{patch}".format(**version_info) + version_status = version_info["status"] + if version_status != "stable": # Pre-release + # If version was overridden to be e.g. "beta3", we insert a dot between + # "beta" and "3" to follow SemVer 2.0. + import re + + match = re.search(r"[\d]+$", version_status) + if match: + pos = match.start() + version_status = version_status[:pos] + "." + version_status[pos:] + version_str += "-" + version_status + + props = """<Project> + <PropertyGroup> + <PackageVersion_GodotSharp>{0}</PackageVersion_GodotSharp> + <PackageVersion_Godot_NET_Sdk>{0}</PackageVersion_Godot_NET_Sdk> + <PackageVersion_Godot_SourceGenerators>{0}</PackageVersion_Godot_SourceGenerators> + </PropertyGroup> +</Project> +""".format( + version_str + ) + + # We write in ../SdkPackageVersions.props. + with open(os.path.join(dirname(script_path), "SdkPackageVersions.props"), "w") as f: + f.write(props) + f.close() + + def build_all(msbuild_tool, module_dir, output_dir, godot_platform, dev_debug, push_nupkgs_local, float_size): + # Generate SdkPackageVersions.props + generate_sdk_package_versions() + # Godot API exit_code = build_godot_api(msbuild_tool, module_dir, output_dir, push_nupkgs_local, float_size) if exit_code != 0: @@ -315,6 +363,8 @@ def main(): output_dir = os.path.abspath(args.godot_output_dir) + push_nupkgs_local = os.path.abspath(args.push_nupkgs_local) if args.push_nupkgs_local else None + msbuild_tool = find_any_msbuild_tool(args.mono_prefix) if msbuild_tool is None: @@ -327,7 +377,7 @@ def main(): output_dir, args.godot_platform, args.dev_debug, - args.push_nupkgs_local, + push_nupkgs_local, args.float, ) sys.exit(exit_code) diff --git a/modules/mono/build_scripts/mono_configure.py b/modules/mono/build_scripts/mono_configure.py index 5d63773096..5cec8f41f5 100644 --- a/modules/mono/build_scripts/mono_configure.py +++ b/modules/mono/build_scripts/mono_configure.py @@ -20,10 +20,7 @@ def configure(env, env_mono): # is_ios = env["platform"] == "ios" # is_ios_sim = is_ios and env["arch"] in ["x86_32", "x86_64"] - tools_enabled = env["tools"] - - if tools_enabled and not module_supports_tools_on(env["platform"]): - raise RuntimeError("This module does not currently support building for this platform with tools enabled") - - if env["tools"]: + if env.editor_build: + if not module_supports_tools_on(env["platform"]): + raise RuntimeError("This module does not currently support building for this platform for editor builds.") env_mono.Append(CPPDEFINES=["GD_MONO_HOT_RELOAD"]) diff --git a/modules/mono/class_db_api_json.cpp b/modules/mono/class_db_api_json.cpp index c4547b4323..1f4b085bfb 100644 --- a/modules/mono/class_db_api_json.cpp +++ b/modules/mono/class_db_api_json.cpp @@ -227,8 +227,7 @@ void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api) { Ref<FileAccess> f = FileAccess::open(p_output_file, FileAccess::WRITE); ERR_FAIL_COND_MSG(f.is_null(), "Cannot open file '" + p_output_file + "'."); - JSON json; - f->store_string(json.stringify(classes_dict, "\t")); + f->store_string(JSON::stringify(classes_dict, "\t")); print_line(String() + "ClassDB API JSON written to: " + ProjectSettings::get_singleton()->globalize_path(p_output_file)); } diff --git a/modules/mono/config.py b/modules/mono/config.py index 15fe79ef8c..a36083b64b 100644 --- a/modules/mono/config.py +++ b/modules/mono/config.py @@ -7,7 +7,7 @@ def can_build(env, platform): if env["arch"].startswith("rv"): return False - if env["tools"]: + if env.editor_build: env.module_add_dependencies("mono", ["regex"]) return True diff --git a/modules/mono/csharp_script.cpp b/modules/mono/csharp_script.cpp index 8fd3626a20..345d2e4694 100644 --- a/modules/mono/csharp_script.cpp +++ b/modules/mono/csharp_script.cpp @@ -1299,7 +1299,7 @@ GDNativeBool CSharpLanguage::_instance_binding_reference_callback(void *p_token, MonoGCHandleData &gchandle = script_binding.gchandle; - int refcount = rc_owner->reference_get_count(); + int refcount = rc_owner->get_reference_count(); if (!script_binding.inited) { return refcount == 0; @@ -1818,7 +1818,7 @@ void CSharpInstance::refcount_incremented() { RefCounted *rc_owner = Object::cast_to<RefCounted>(owner); - if (rc_owner->reference_get_count() > 1 && gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0 + if (rc_owner->get_reference_count() > 1 && gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0 // The reference count was increased after the managed side was the only one referencing our owner. // This means the owner is being referenced again by the unmanaged side, // so the owner must hold the managed side alive again to avoid it from being GCed. @@ -1849,7 +1849,7 @@ bool CSharpInstance::refcount_decremented() { RefCounted *rc_owner = Object::cast_to<RefCounted>(owner); - int refcount = rc_owner->reference_get_count(); + int refcount = rc_owner->get_reference_count(); if (refcount == 1 && !gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0 // If owner owner is no longer referenced by the unmanaged side, @@ -1995,7 +1995,7 @@ CSharpInstance::~CSharpInstance() { #ifdef DEBUG_ENABLED // The "instance binding" holds a reference so the refcount should be at least 2 before `scope_keep_owner_alive` goes out of scope - CRASH_COND(rc_owner->reference_get_count() <= 1); + CRASH_COND(rc_owner->get_reference_count() <= 1); #endif } @@ -2398,9 +2398,9 @@ ScriptInstance *CSharpScript::instance_create(Object *p_this) { if (EngineDebugger::is_active()) { CSharpLanguage::get_singleton()->debug_break_parse(get_path(), 0, "Script inherits from native type '" + String(native_name) + - "', so it can't be instantiated in object of type: '" + p_this->get_class() + "'"); + "', so it can't be assigned to an object of type: '" + p_this->get_class() + "'"); } - ERR_FAIL_V_MSG(nullptr, "Script inherits from native type '" + String(native_name) + "', so it can't be instantiated in object of type: '" + p_this->get_class() + "'."); + ERR_FAIL_V_MSG(nullptr, "Script inherits from native type '" + String(native_name) + "', so it can't be assigned to an object of type: '" + p_this->get_class() + "'."); } Callable::CallError unchecked_error; diff --git a/modules/mono/csharp_script.h b/modules/mono/csharp_script.h index d469c28d4a..e5e53acb07 100644 --- a/modules/mono/csharp_script.h +++ b/modules/mono/csharp_script.h @@ -48,20 +48,10 @@ class CSharpScript; class CSharpInstance; class CSharpLanguage; -#ifdef NO_SAFE_CAST -template <typename TScriptInstance, typename TScriptLanguage> -TScriptInstance *cast_script_instance(ScriptInstance *p_inst) { - if (!p_inst) { - return nullptr; - } - return p_inst->get_language() == TScriptLanguage::get_singleton() ? static_cast<TScriptInstance *>(p_inst) : nullptr; -} -#else template <typename TScriptInstance, typename TScriptLanguage> TScriptInstance *cast_script_instance(ScriptInstance *p_inst) { return dynamic_cast<TScriptInstance *>(p_inst); } -#endif #define CAST_CSHARP_INSTANCE(m_inst) (cast_script_instance<CSharpInstance, CSharpLanguage>(m_inst)) diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.targets b/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.targets index bff9760b32..859ea52c93 100644 --- a/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.targets +++ b/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.targets @@ -17,7 +17,7 @@ <!-- C# source generators --> <ItemGroup Condition=" '$(DisableImplicitGodotGeneratorReferences)' != 'true' "> - <PackageReference Include="Godot.SourceGenerators" Version="$(PackageFloatingVersion_Godot)" /> + <PackageReference Include="Godot.SourceGenerators" Version="$(PackageVersion_Godot_SourceGenerators)" /> </ItemGroup> <!-- Godot API references --> diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/EventHandlerSuffixSuppressor.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/EventHandlerSuffixSuppressor.cs new file mode 100644 index 0000000000..ddde730fa2 --- /dev/null +++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/EventHandlerSuffixSuppressor.cs @@ -0,0 +1,53 @@ +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Diagnostics; + +namespace Godot.SourceGenerators +{ + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public class EventHandlerSuffixSuppressor : DiagnosticSuppressor + { + private static readonly SuppressionDescriptor _descriptor = new( + id: "GDSP0001", + suppressedDiagnosticId: "CA1711", + justification: "Signal delegates are used in events so the naming follows the guidelines."); + + public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions => + ImmutableArray.Create(_descriptor); + + public override void ReportSuppressions(SuppressionAnalysisContext context) + { + foreach (var diagnostic in context.ReportedDiagnostics) + { + AnalyzeDiagnostic(context, diagnostic, context.CancellationToken); + } + } + + private static void AnalyzeDiagnostic(SuppressionAnalysisContext context, Diagnostic diagnostic, CancellationToken cancellationToken = default) + { + var location = diagnostic.Location; + var root = location.SourceTree?.GetRoot(cancellationToken); + var dds = root? + .FindNode(location.SourceSpan) + .DescendantNodesAndSelf() + .OfType<DelegateDeclarationSyntax>() + .FirstOrDefault(); + + if (dds == null) + return; + + var semanticModel = context.GetSemanticModel(dds.SyntaxTree); + var delegateSymbol = semanticModel.GetDeclaredSymbol(dds, cancellationToken); + if (delegateSymbol == null) + return; + + if (delegateSymbol.GetAttributes().Any(a => a.AttributeClass?.IsGodotSignalAttribute() ?? false)) + { + context.ReportSuppression(Suppression.Create(_descriptor, diagnostic)); + } + } + } +} diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ExtensionMethods.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ExtensionMethods.cs index de3b6c862a..8de12de23b 100644 --- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ExtensionMethods.cs +++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ExtensionMethods.cs @@ -29,7 +29,7 @@ namespace Godot.SourceGenerators { while (symbol != null) { - if (symbol.ContainingAssembly.Name == assemblyName && + if (symbol.ContainingAssembly?.Name == assemblyName && symbol.ToString() == typeFullName) { return true; @@ -47,7 +47,7 @@ namespace Godot.SourceGenerators while (symbol != null) { - if (symbol.ContainingAssembly.Name == "GodotSharp") + if (symbol.ContainingAssembly?.Name == "GodotSharp") return symbol; symbol = symbol.BaseType; diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotPluginsInitializerGenerator.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotPluginsInitializerGenerator.cs index 7ec3f88e5d..19fdd51dab 100644 --- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotPluginsInitializerGenerator.cs +++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotPluginsInitializerGenerator.cs @@ -56,7 +56,7 @@ namespace GodotPlugins.Game } "; - context.AddSource("GodotPlugins.Game_Generated", + context.AddSource("GodotPlugins.Game.generated", SourceText.From(source, Encoding.UTF8)); } } diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MarshalUtils.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MarshalUtils.cs index efdd50098e..bd40675fd3 100644 --- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MarshalUtils.cs +++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MarshalUtils.cs @@ -124,8 +124,8 @@ namespace Godot.SourceGenerators if (typeKind == TypeKind.Struct) { - if (type.ContainingAssembly.Name == "GodotSharp" && - type.ContainingNamespace.Name == "Godot") + if (type.ContainingAssembly?.Name == "GodotSharp" && + type.ContainingNamespace?.Name == "Godot") { return type switch { @@ -156,6 +156,10 @@ namespace Godot.SourceGenerators else if (typeKind == TypeKind.Array) { var arrayType = (IArrayTypeSymbol)type; + + if (arrayType.Rank != 1) + return null; + var elementType = arrayType.ElementType; switch (elementType.SpecialType) @@ -177,8 +181,8 @@ namespace Godot.SourceGenerators if (elementType.SimpleDerivesFrom(typeCache.GodotObjectType)) return MarshalType.GodotObjectOrDerivedArray; - if (elementType.ContainingAssembly.Name == "GodotSharp" && - elementType.ContainingNamespace.Name == "Godot") + if (elementType.ContainingAssembly?.Name == "GodotSharp" && + elementType.ContainingNamespace?.Name == "Godot") { switch (elementType) { @@ -204,9 +208,9 @@ namespace Godot.SourceGenerators if (type.SimpleDerivesFrom(typeCache.GodotObjectType)) return MarshalType.GodotObjectOrDerived; - if (type.ContainingAssembly.Name == "GodotSharp") + if (type.ContainingAssembly?.Name == "GodotSharp") { - switch (type.ContainingNamespace.Name) + switch (type.ContainingNamespace?.Name) { case "Godot": return type switch @@ -216,7 +220,7 @@ namespace Godot.SourceGenerators _ => null }; case "Collections" - when type.ContainingNamespace.FullQualifiedName() == "Godot.Collections": + when type.ContainingNamespace?.FullQualifiedName() == "Godot.Collections": return type switch { { Name: "Dictionary" } => diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptMethodsGenerator.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptMethodsGenerator.cs index 1ee31eb1a9..d5d80df643 100644 --- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptMethodsGenerator.cs +++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptMethodsGenerator.cs @@ -87,7 +87,7 @@ namespace Godot.SourceGenerators bool isInnerClass = symbol.ContainingType != null; string uniqueHint = symbol.FullQualifiedName().SanitizeQualifiedNameForUniqueHint() - + "_ScriptMethods_Generated"; + + "_ScriptMethods.generated"; var source = new StringBuilder(); @@ -188,14 +188,14 @@ namespace Godot.SourceGenerators if (godotClassMethods.Length > 0) { source.Append(" protected override bool InvokeGodotClassMethod(in godot_string_name method, "); - source.Append("NativeVariantPtrArgs args, int argCount, out godot_variant ret)\n {\n"); + source.Append("NativeVariantPtrArgs args, out godot_variant ret)\n {\n"); foreach (var method in godotClassMethods) { GenerateMethodInvoker(method, source); } - source.Append(" return base.InvokeGodotClassMethod(method, args, argCount, out ret);\n"); + source.Append(" return base.InvokeGodotClassMethod(method, args, out ret);\n"); source.Append(" }\n"); } @@ -364,7 +364,7 @@ namespace Godot.SourceGenerators source.Append(" if (method == MethodName."); source.Append(methodName); - source.Append(" && argCount == "); + source.Append(" && args.Count == "); source.Append(method.ParamTypes.Length); source.Append(") {\n"); diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPathAttributeGenerator.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPathAttributeGenerator.cs index e8a9e28d0c..ccfb405d26 100644 --- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPathAttributeGenerator.cs +++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPathAttributeGenerator.cs @@ -96,8 +96,8 @@ namespace Godot.SourceGenerators string.Empty; bool hasNamespace = classNs.Length != 0; - var uniqueHint = symbol.FullQualifiedName().SanitizeQualifiedNameForUniqueHint() - + "_ScriptPath_Generated"; + string uniqueHint = symbol.FullQualifiedName().SanitizeQualifiedNameForUniqueHint() + + "_ScriptPath.generated"; var source = new StringBuilder(); @@ -126,7 +126,7 @@ namespace Godot.SourceGenerators source.Append("\n}\n"); } - context.AddSource(uniqueHint.ToString(), SourceText.From(source.ToString(), Encoding.UTF8)); + context.AddSource(uniqueHint, SourceText.From(source.ToString(), Encoding.UTF8)); } private static void AddScriptTypesAssemblyAttr(GeneratorExecutionContext context, @@ -157,7 +157,7 @@ namespace Godot.SourceGenerators sourceBuilder.Append("})]\n"); - context.AddSource("AssemblyScriptTypes_Generated", + context.AddSource("AssemblyScriptTypes.generated", SourceText.From(sourceBuilder.ToString(), Encoding.UTF8)); } diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertiesGenerator.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertiesGenerator.cs index b331e2e794..1198c633d9 100644 --- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertiesGenerator.cs +++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertiesGenerator.cs @@ -73,7 +73,7 @@ namespace Godot.SourceGenerators bool isInnerClass = symbol.ContainingType != null; string uniqueHint = symbol.FullQualifiedName().SanitizeQualifiedNameForUniqueHint() - + "_ScriptProperties_Generated"; + + "_ScriptProperties.generated"; var source = new StringBuilder(); diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertyDefValGenerator.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertyDefValGenerator.cs index 65dadcb801..98b9745c16 100644 --- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertyDefValGenerator.cs +++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertyDefValGenerator.cs @@ -73,7 +73,7 @@ namespace Godot.SourceGenerators bool isInnerClass = symbol.ContainingType != null; string uniqueHint = symbol.FullQualifiedName().SanitizeQualifiedNameForUniqueHint() - + "_ScriptPropertyDefVal_Generated"; + + "_ScriptPropertyDefVal.generated"; var source = new StringBuilder(); diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSerializationGenerator.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSerializationGenerator.cs index a40220565f..11e0a6fa21 100644 --- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSerializationGenerator.cs +++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSerializationGenerator.cs @@ -73,7 +73,7 @@ namespace Godot.SourceGenerators bool isInnerClass = symbol.ContainingType != null; string uniqueHint = symbol.FullQualifiedName().SanitizeQualifiedNameForUniqueHint() - + "_ScriptSerialization_Generated"; + + "_ScriptSerialization.generated"; var source = new StringBuilder(); diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSignalsGenerator.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSignalsGenerator.cs index 1df41a905b..50196b84f0 100644 --- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSignalsGenerator.cs +++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSignalsGenerator.cs @@ -7,7 +7,7 @@ using Microsoft.CodeAnalysis.Text; // TODO: // Determine a proper way to emit the signal. -// 'Emit(nameof(TheEvent))' creates a StringName everytime and has the overhead of string marshaling. +// 'Emit(nameof(TheEvent))' creates a StringName every time and has the overhead of string marshaling. // I haven't decided on the best option yet. Some possibilities: // - Expose the generated StringName fields to the user, for use with 'Emit(...)'. // - Generate a 'EmitSignalName' method for each event signal. @@ -82,7 +82,7 @@ namespace Godot.SourceGenerators bool isInnerClass = symbol.ContainingType != null; string uniqueHint = symbol.FullQualifiedName().SanitizeQualifiedNameForUniqueHint() - + "_ScriptSignals_Generated"; + + "_ScriptSignals.generated"; var source = new StringBuilder(); @@ -167,6 +167,7 @@ namespace Godot.SourceGenerators Common.ReportSignalDelegateSignatureMustReturnVoid(context, signalDelegateSymbol); } } + continue; } @@ -235,6 +236,8 @@ namespace Godot.SourceGenerators .Append(signalName) .Append(";\n"); + source.Append($" /// <inheritdoc cref=\"{signalDelegate.DelegateSymbol.FullQualifiedName()}\"/>\n"); + source.Append(" public event ") .Append(signalDelegate.DelegateSymbol.FullQualifiedName()) .Append(" ") @@ -255,14 +258,14 @@ namespace Godot.SourceGenerators { source.Append( " protected override void RaiseGodotClassSignalCallbacks(in godot_string_name signal, "); - source.Append("NativeVariantPtrArgs args, int argCount)\n {\n"); + source.Append("NativeVariantPtrArgs args)\n {\n"); foreach (var signal in godotSignalDelegates) { GenerateSignalEventInvoker(signal, source); } - source.Append(" base.RaiseGodotClassSignalCallbacks(signal, args, argCount);\n"); + source.Append(" base.RaiseGodotClassSignalCallbacks(signal, args);\n"); source.Append(" }\n"); } @@ -402,7 +405,7 @@ namespace Godot.SourceGenerators source.Append(" if (signal == SignalName."); source.Append(signalName); - source.Append(" && argCount == "); + source.Append(" && args.Count == "); source.Append(invokeMethodData.ParamTypes.Length); source.Append(") {\n"); source.Append(" backing_"); diff --git a/modules/mono/editor/GodotTools/GodotTools.Shared/GenerateGodotNupkgsVersions.targets b/modules/mono/editor/GodotTools/GodotTools.Shared/GenerateGodotNupkgsVersions.targets index 4baae77b34..37bd4a0be0 100644 --- a/modules/mono/editor/GodotTools/GodotTools.Shared/GenerateGodotNupkgsVersions.targets +++ b/modules/mono/editor/GodotTools/GodotTools.Shared/GenerateGodotNupkgsVersions.targets @@ -21,10 +21,13 @@ Outputs="$(GeneratedGodotNupkgsVersionsFile)"> <PropertyGroup> <GenerateGodotNupkgsVersionsCode><![CDATA[ -namespace $(RootNamespace) { - public class GeneratedGodotNupkgsVersions { +namespace $(RootNamespace) +{ + public class GeneratedGodotNupkgsVersions + { public const string GodotNETSdk = "$(PackageVersion_Godot_NET_Sdk)"%3b public const string GodotSourceGenerators = "$(PackageVersion_Godot_SourceGenerators)"%3b + public const string GodotSharp = "$(PackageVersion_GodotSharp)"%3b } } ]]></GenerateGodotNupkgsVersionsCode> diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs b/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs index ad4fce8daa..4d40724a83 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs @@ -69,51 +69,41 @@ namespace GodotTools.Build private void LoadIssuesFromFile(string csvFile) { - using (var file = new Godot.File()) + using var file = FileAccess.Open(csvFile, FileAccess.ModeFlags.Read); + + if (file == null) + return; + + while (!file.EofReached()) { - try - { - Error openError = file.Open(csvFile, Godot.File.ModeFlags.Read); + string[] csvColumns = file.GetCsvLine(); - if (openError != Error.Ok) - return; + if (csvColumns.Length == 1 && string.IsNullOrEmpty(csvColumns[0])) + return; - while (!file.EofReached()) - { - string[] csvColumns = file.GetCsvLine(); - - if (csvColumns.Length == 1 && string.IsNullOrEmpty(csvColumns[0])) - return; - - if (csvColumns.Length != 7) - { - GD.PushError($"Expected 7 columns, got {csvColumns.Length}"); - continue; - } - - var issue = new BuildIssue - { - Warning = csvColumns[0] == "warning", - File = csvColumns[1], - Line = int.Parse(csvColumns[2]), - Column = int.Parse(csvColumns[3]), - Code = csvColumns[4], - Message = csvColumns[5], - ProjectFile = csvColumns[6] - }; - - if (issue.Warning) - WarningCount += 1; - else - ErrorCount += 1; - - _issues.Add(issue); - } - } - finally + if (csvColumns.Length != 7) { - file.Close(); // Disposing it is not enough. We need to call Close() + GD.PushError($"Expected 7 columns, got {csvColumns.Length}"); + continue; } + + var issue = new BuildIssue + { + Warning = csvColumns[0] == "warning", + File = csvColumns[1], + Line = int.Parse(csvColumns[2]), + Column = int.Parse(csvColumns[3]), + Code = csvColumns[4], + Message = csvColumns[5], + ProjectFile = csvColumns[6] + }; + + if (issue.Warning) + WarningCount += 1; + else + ErrorCount += 1; + + _issues.Add(issue); } } diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/DotNetFinder.cs b/modules/mono/editor/GodotTools/GodotTools/Build/DotNetFinder.cs index 7bce53308c..b437c7e742 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Build/DotNetFinder.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Build/DotNetFinder.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; +using System.Runtime.InteropServices; using JetBrains.Annotations; using OS = GodotTools.Utils.OS; @@ -16,6 +17,23 @@ namespace GodotTools.Build // In the future, this method may do more than just search in PATH. We could look in // known locations or use Godot's linked nethost to search from the hostfxr location. + if (OS.IsMacOS) + { + if (RuntimeInformation.OSArchitecture == Architecture.X64) + { + string dotnet_x64 = "/usr/local/share/dotnet/x64/dotnet"; // Look for x64 version, when running under Rosetta 2. + if (File.Exists(dotnet_x64)) + { + return dotnet_x64; + } + } + string dotnet = "/usr/local/share/dotnet/dotnet"; // Look for native version. + if (File.Exists(dotnet)) + { + return dotnet; + } + } + return OS.PathWhich("dotnet"); } diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/NuGetUtils.cs b/modules/mono/editor/GodotTools/GodotTools/Build/NuGetUtils.cs index d2e0e128b5..fe309b8102 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Build/NuGetUtils.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Build/NuGetUtils.cs @@ -22,71 +22,13 @@ namespace GodotTools.Build public static string GodotFallbackFolderPath => Path.Combine(GodotSharpDirs.MonoUserDir, "GodotNuGetFallbackFolder"); - private static void AddFallbackFolderToNuGetConfig(string nuGetConfigPath, string name, string path) - { - var xmlDoc = new XmlDocument(); - xmlDoc.Load(nuGetConfigPath); - - const string nuGetConfigRootName = "configuration"; - - var rootNode = xmlDoc.DocumentElement; - - if (rootNode == null) - { - // No root node, create it - rootNode = xmlDoc.CreateElement(nuGetConfigRootName); - xmlDoc.AppendChild(rootNode); - - // Since this can be considered pretty much a new NuGet.Config, add the default nuget.org source as well - XmlElement nugetOrgSourceEntry = xmlDoc.CreateElement("add"); - nugetOrgSourceEntry.Attributes.Append(xmlDoc.CreateAttribute("key")).Value = "nuget.org"; - nugetOrgSourceEntry.Attributes.Append(xmlDoc.CreateAttribute("value")).Value = - "https://api.nuget.org/v3/index.json"; - nugetOrgSourceEntry.Attributes.Append(xmlDoc.CreateAttribute("protocolVersion")).Value = "3"; - rootNode.AppendChild(xmlDoc.CreateElement("packageSources")).AppendChild(nugetOrgSourceEntry); - } - else - { - // Check that the root node is the expected one - if (rootNode.Name != nuGetConfigRootName) - throw new FormatException("Invalid root Xml node for NuGet.Config. " + - $"Expected '{nuGetConfigRootName}' got '{rootNode.Name}'."); - } - - var fallbackFoldersNode = rootNode["fallbackPackageFolders"] ?? - rootNode.AppendChild(xmlDoc.CreateElement("fallbackPackageFolders")); - - // Check if it already has our fallback package folder - for (var xmlNode = fallbackFoldersNode.FirstChild; xmlNode != null; xmlNode = xmlNode.NextSibling) - { - if (xmlNode.NodeType != XmlNodeType.Element) - continue; - - var xmlElement = (XmlElement)xmlNode; - if (xmlElement.Name == "add" && - xmlElement.Attributes["key"]?.Value == name && - xmlElement.Attributes["value"]?.Value == path) - { - return; - } - } - - XmlElement newEntry = xmlDoc.CreateElement("add"); - newEntry.Attributes.Append(xmlDoc.CreateAttribute("key")).Value = name; - newEntry.Attributes.Append(xmlDoc.CreateAttribute("value")).Value = path; - - fallbackFoldersNode.AppendChild(newEntry); - - xmlDoc.Save(nuGetConfigPath); - } - /// <summary> - /// Returns all the paths where the user NuGet.Config files can be found. + /// Returns all the paths where the Godot.Offline.Config files can be found. /// Does not determine whether the returned files exist or not. /// </summary> - private static string[] GetAllUserNuGetConfigFilePaths() + private static string[] GetAllGodotNuGetConfigFilePaths() { - // Where to find 'NuGet/NuGet.Config': + // Where to find 'NuGet/config/Godot.Offline.Config': // // - Mono/.NETFramework (standalone NuGet): // Uses Environment.SpecialFolder.ApplicationData @@ -98,10 +40,12 @@ namespace GodotTools.Build string applicationData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); + const string configFileName = "Godot.Offline.Config"; + if (Utils.OS.IsWindows) { // %APPDATA% for both - return new[] { Path.Combine(applicationData, "NuGet", "NuGet.Config") }; + return new[] { Path.Combine(applicationData, "NuGet", "config", configFileName) }; } var paths = new string[2]; @@ -111,20 +55,20 @@ namespace GodotTools.Build string dotnetCliHome = Environment.GetEnvironmentVariable("DOTNET_CLI_HOME"); if (!string.IsNullOrEmpty(dotnetCliHome)) { - paths[0] = Path.Combine(dotnetCliHome, ".nuget", "NuGet", "NuGet.Config"); + paths[0] = Path.Combine(dotnetCliHome, ".nuget", "NuGet", "config", configFileName); } else { string home = Environment.GetEnvironmentVariable("HOME"); if (string.IsNullOrEmpty(home)) throw new InvalidOperationException("Required environment variable 'HOME' is not set."); - paths[0] = Path.Combine(home, ".nuget", "NuGet", "NuGet.Config"); + paths[0] = Path.Combine(home, ".nuget", "NuGet", "config", configFileName); } // Mono/.NETFramework (standalone NuGet) // ApplicationData is $HOME/.config on Linux/macOS - paths[1] = Path.Combine(applicationData, "NuGet", "NuGet.Config"); + paths[1] = Path.Combine(applicationData, "NuGet", "config", configFileName); return paths; } @@ -141,28 +85,26 @@ namespace GodotTools.Build // The nuspec is not lower case inside the nupkg but must be made lower case when extracted. /// <summary> - /// Adds the specified fallback folder to the user NuGet.Config files, + /// Adds the specified fallback folder to the Godot.Offline.Config files, /// for both standalone NuGet (Mono/.NETFramework) and dotnet CLI NuGet. /// </summary> - public static void AddFallbackFolderToUserNuGetConfigs(string name, string path) + public static void AddFallbackFolderToGodotNuGetConfigs(string name, string path) { - foreach (string nuGetConfigPath in GetAllUserNuGetConfigFilePaths()) + // Make sure the fallback folder exists to avoid error: + // MSB4018: The "ResolvePackageAssets" task failed unexpectedly. + System.IO.Directory.CreateDirectory(path); + + foreach (string nuGetConfigPath in GetAllGodotNuGetConfigFilePaths()) { - if (!System.IO.File.Exists(nuGetConfigPath)) - { - // It doesn't exist, so we create a default one - const string defaultConfig = @"<?xml version=""1.0"" encoding=""utf-8""?> + string defaultConfig = @$"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> - <packageSources> - <add key=""nuget.org"" value=""https://api.nuget.org/v3/index.json"" protocolVersion=""3"" /> - </packageSources> + <fallbackPackageFolders> + <add key=""{name}"" value=""{path}"" /> + </fallbackPackageFolders> </configuration> "; - System.IO.Directory.CreateDirectory(Path.GetDirectoryName(nuGetConfigPath)); - System.IO.File.WriteAllText(nuGetConfigPath, defaultConfig, Encoding.UTF8); // UTF-8 with BOM - } - - AddFallbackFolderToNuGetConfig(nuGetConfigPath, name, path); + System.IO.Directory.CreateDirectory(Path.GetDirectoryName(nuGetConfigPath)); + System.IO.File.WriteAllText(nuGetConfigPath, defaultConfig, Encoding.UTF8); // UTF-8 with BOM } } @@ -189,6 +131,7 @@ namespace GodotTools.Build string destDir = Path.Combine(fallbackFolder, packageIdLower, packageVersionLower); string nupkgDestPath = Path.Combine(destDir, $"{packageIdLower}.{packageVersionLower}.nupkg"); string nupkgSha512DestPath = Path.Combine(destDir, $"{packageIdLower}.{packageVersionLower}.nupkg.sha512"); + string nupkgMetadataDestPath = Path.Combine(destDir, ".nupkg.metadata"); if (File.Exists(nupkgDestPath) && File.Exists(nupkgSha512DestPath)) return; // Already added (for speed we don't check if every file is properly extracted) @@ -197,12 +140,18 @@ namespace GodotTools.Build // Generate .nupkg.sha512 file - using (var alg = SHA512.Create()) - { - alg.ComputeHash(File.ReadAllBytes(nupkgPath)); - string base64Hash = Convert.ToBase64String(alg.Hash); - File.WriteAllText(nupkgSha512DestPath, base64Hash); - } + byte[] hash = SHA512.HashData(File.ReadAllBytes(nupkgPath)); + string base64Hash = Convert.ToBase64String(hash); + File.WriteAllText(nupkgSha512DestPath, base64Hash); + + // Generate .nupkg.metadata file + // Spec: https://github.com/NuGet/Home/wiki/Nupkg-Metadata-File + + File.WriteAllText(nupkgMetadataDestPath, @$"{{ + ""version"": 2, + ""contentHash"": ""{base64Hash}"", + ""source"": null +}}"); // Extract nupkg ExtractNupkg(destDir, nupkgPath, packageId, packageVersion); @@ -251,7 +200,7 @@ namespace GodotTools.Build entryFullName.EndsWith(".nupkg.sha512", StringComparison.OrdinalIgnoreCase) || entryFullName.EndsWith(".nupkg.metadata", StringComparison.OrdinalIgnoreCase) || // Nuspec at root level. We already extracted it previously but in lower case. - entryFullName.IndexOf('/') == -1 && entryFullName.EndsWith(".nuspec")) + !entryFullName.Contains('/') && entryFullName.EndsWith(".nuspec")) { continue; } @@ -297,6 +246,8 @@ namespace GodotTools.Build { ("Godot.NET.Sdk", GeneratedGodotNupkgsVersions.GodotNETSdk), ("Godot.SourceGenerators", GeneratedGodotNupkgsVersions.GodotSourceGenerators), + ("GodotSharp", GeneratedGodotNupkgsVersions.GodotSharp), + ("GodotSharpEditor", GeneratedGodotNupkgsVersions.GodotSharp), }; } } diff --git a/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs b/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs index 0d2bea2363..745a8b73f8 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs @@ -17,6 +17,8 @@ namespace GodotTools.Export { public partial class ExportPlugin : EditorExportPlugin { + private List<string> _tempFolders = new List<string>(); + public void RegisterExportSettings() { // TODO: These would be better as export preset options, but that doesn't seem to be supported yet @@ -111,62 +113,78 @@ namespace GodotTools.Export string buildConfig = isDebug ? "ExportDebug" : "ExportRelease"; - // TODO: This works for now, as we only implemented support for x86 family desktop so far, but it needs to be fixed - string arch = features.Contains("x86_64") ? "x86_64" : "x86"; - - string ridOS = DetermineRuntimeIdentifierOS(platform); - string ridArch = DetermineRuntimeIdentifierArch(arch); - string runtimeIdentifier = $"{ridOS}-{ridArch}"; - - // Create temporary publish output directory - - string publishOutputTempDir = Path.Combine(Path.GetTempPath(), "godot-publish-dotnet", - $"{Process.GetCurrentProcess().Id}-{buildConfig}-{runtimeIdentifier}"); - - if (!Directory.Exists(publishOutputTempDir)) - Directory.CreateDirectory(publishOutputTempDir); - - // Execute dotnet publish - - if (!BuildManager.PublishProjectBlocking(buildConfig, platform, - runtimeIdentifier, publishOutputTempDir)) + var archs = new List<string>(); + if (features.Contains("x86_64")) { - throw new InvalidOperationException("Failed to build project."); + archs.Add("x86_64"); } - - string soExt = ridOS switch + else if (features.Contains("x86_32")) { - OS.DotNetOS.Win or OS.DotNetOS.Win10 => "dll", - OS.DotNetOS.OSX or OS.DotNetOS.iOS => "dylib", - _ => "so" - }; - - if (!File.Exists(Path.Combine(publishOutputTempDir, $"{GodotSharpDirs.ProjectAssemblyName}.dll")) - // NativeAOT shared library output - && !File.Exists(Path.Combine(publishOutputTempDir, $"{GodotSharpDirs.ProjectAssemblyName}.{soExt}"))) + archs.Add("x86_32"); + } + else if (features.Contains("arm64")) { - throw new NotSupportedException( - "Publish succeeded but project assembly not found in the output directory"); + archs.Add("arm64"); } - - // Copy all files from the dotnet publish output directory to - // a data directory next to the Godot output executable. - - string outputDataDir = Path.Combine(outputDir, DetermineDataDirNameForProject()); - - if (Directory.Exists(outputDataDir)) - Directory.Delete(outputDataDir, recursive: true); // Clean first - - Directory.CreateDirectory(outputDataDir); - - foreach (string dir in Directory.GetDirectories(publishOutputTempDir, "*", SearchOption.AllDirectories)) + else if (features.Contains("universal")) { - Directory.CreateDirectory(Path.Combine(outputDataDir, dir.Substring(publishOutputTempDir.Length + 1))); + if (platform == OS.Platforms.MacOS) + { + archs.Add("x86_64"); + archs.Add("arm64"); + } } - foreach (string file in Directory.GetFiles(publishOutputTempDir, "*", SearchOption.AllDirectories)) + foreach (var arch in archs) { - File.Copy(file, Path.Combine(outputDataDir, file.Substring(publishOutputTempDir.Length + 1))); + string ridOS = DetermineRuntimeIdentifierOS(platform); + string ridArch = DetermineRuntimeIdentifierArch(arch); + string runtimeIdentifier = $"{ridOS}-{ridArch}"; + string projectDataDirName = $"{DetermineDataDirNameForProject()}_{arch}"; + if (platform == OS.Platforms.MacOS) + { + projectDataDirName = Path.Combine("Contents", "Resources", projectDataDirName); + } + + // Create temporary publish output directory + + string publishOutputTempDir = Path.Combine(Path.GetTempPath(), "godot-publish-dotnet", + $"{Process.GetCurrentProcess().Id}-{buildConfig}-{runtimeIdentifier}"); + + _tempFolders.Add(publishOutputTempDir); + + if (!Directory.Exists(publishOutputTempDir)) + Directory.CreateDirectory(publishOutputTempDir); + + // Execute dotnet publish + + if (!BuildManager.PublishProjectBlocking(buildConfig, platform, + runtimeIdentifier, publishOutputTempDir)) + { + throw new InvalidOperationException("Failed to build project."); + } + + string soExt = ridOS switch + { + OS.DotNetOS.Win or OS.DotNetOS.Win10 => "dll", + OS.DotNetOS.OSX or OS.DotNetOS.iOS => "dylib", + _ => "so" + }; + + if (!File.Exists(Path.Combine(publishOutputTempDir, $"{GodotSharpDirs.ProjectAssemblyName}.dll")) + // NativeAOT shared library output + && !File.Exists(Path.Combine(publishOutputTempDir, $"{GodotSharpDirs.ProjectAssemblyName}.{soExt}"))) + { + throw new NotSupportedException( + "Publish succeeded but project assembly not found in the output directory"); + } + + // Add to the exported project shared object list. + + foreach (string file in Directory.GetFiles(publishOutputTempDir, "*", SearchOption.AllDirectories)) + { + AddSharedObject(file, tags: null, projectDataDirName); + } } } @@ -198,6 +216,12 @@ namespace GodotTools.Export if (Directory.Exists(aotTempDir)) Directory.Delete(aotTempDir, recursive: true); + foreach (string folder in _tempFolders) + { + Directory.Delete(folder, recursive: true); + } + _tempFolders.Clear(); + // TODO: The following is just a workaround until the export plugins can be made to abort with errors // We check for empty as well, because it's set to empty after hot-reloading diff --git a/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs b/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs index 1cfaea3ec9..89364d1c02 100644 --- a/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs +++ b/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs @@ -123,7 +123,7 @@ namespace GodotTools try { string fallbackFolder = NuGetUtils.GodotFallbackFolderPath; - NuGetUtils.AddFallbackFolderToUserNuGetConfigs(NuGetUtils.GodotFallbackFolderName, + NuGetUtils.AddFallbackFolderToGodotNuGetConfigs(NuGetUtils.GodotFallbackFolderName, fallbackFolder); NuGetUtils.AddBundledPackagesToFallbackFolder(fallbackFolder); } @@ -497,7 +497,7 @@ namespace GodotTools try { // At startup we make sure NuGet.Config files have our Godot NuGet fallback folder included - NuGetUtils.AddFallbackFolderToUserNuGetConfigs(NuGetUtils.GodotFallbackFolderName, + NuGetUtils.AddFallbackFolderToGodotNuGetConfigs(NuGetUtils.GodotFallbackFolderName, NuGetUtils.GodotFallbackFolderPath); } catch (Exception e) diff --git a/modules/mono/editor/bindings_generator.cpp b/modules/mono/editor/bindings_generator.cpp index c27bb959fe..b90321b586 100644 --- a/modules/mono/editor/bindings_generator.cpp +++ b/modules/mono/editor/bindings_generator.cpp @@ -1614,7 +1614,7 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str output << MEMBER_BEGIN "protected internal " << (is_derived_type ? "override" : "virtual") << " bool " CS_METHOD_INVOKE_GODOT_CLASS_METHOD "(in godot_string_name method, " - << "NativeVariantPtrArgs args, int argCount, out godot_variant ret)\n" + << "NativeVariantPtrArgs args, out godot_variant ret)\n" << INDENT1 "{\n"; for (const MethodInterface &imethod : itype.methods) { @@ -1630,7 +1630,7 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str // We check both native names (snake_case) and proxy names (PascalCase) output << INDENT2 "if ((method == " << CS_STATIC_FIELD_METHOD_PROXY_NAME_PREFIX << imethod.name << " || method == MethodName." << imethod.proxy_name - << ") && argCount == " << itos(imethod.arguments.size()) + << ") && args.Count == " << itos(imethod.arguments.size()) << " && " << CS_METHOD_HAS_GODOT_CLASS_METHOD << "((godot_string_name)" << CS_STATIC_FIELD_METHOD_PROXY_NAME_PREFIX << imethod.name << ".NativeValue))\n" << INDENT2 "{\n"; @@ -1682,7 +1682,7 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str } if (is_derived_type) { - output << INDENT2 "return base." CS_METHOD_INVOKE_GODOT_CLASS_METHOD "(method, args, argCount, out ret);\n"; + output << INDENT2 "return base." CS_METHOD_INVOKE_GODOT_CLASS_METHOD "(method, args, out ret);\n"; } else { output << INDENT2 "ret = default;\n" << INDENT2 "return false;\n"; @@ -2200,6 +2200,11 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf Error BindingsGenerator::_generate_cs_signal(const BindingsGenerator::TypeInterface &p_itype, const BindingsGenerator::SignalInterface &p_isignal, StringBuilder &p_output) { String arguments_sig; + String delegate_type_params; + + if (!p_isignal.arguments.is_empty()) { + delegate_type_params += "<"; + } // Retrieve information from the arguments const ArgumentInterface &first = p_isignal.arguments.front()->get(); @@ -2220,15 +2225,82 @@ Error BindingsGenerator::_generate_cs_signal(const BindingsGenerator::TypeInterf if (&iarg != &first) { arguments_sig += ", "; + delegate_type_params += ", "; } arguments_sig += arg_type->cs_type; arguments_sig += " "; arguments_sig += iarg.name; + + delegate_type_params += arg_type->cs_type; + } + + if (!p_isignal.arguments.is_empty()) { + delegate_type_params += ">"; } // Generate signal { + p_output.append(MEMBER_BEGIN "/// <summary>\n"); + p_output.append(INDENT1 "/// "); + p_output.append("Represents the method that handles the "); + p_output.append("<see cref=\"" BINDINGS_NAMESPACE "." + p_itype.proxy_name + "." + p_isignal.proxy_name + "\"/>"); + p_output.append(" event of a "); + p_output.append("<see cref=\"" BINDINGS_NAMESPACE "." + p_itype.proxy_name + "\"/>"); + p_output.append(" class.\n"); + p_output.append(INDENT1 "/// </summary>"); + + if (p_isignal.is_deprecated) { + if (p_isignal.deprecation_message.is_empty()) { + WARN_PRINT("An empty deprecation message is discouraged. Signal: '" + p_isignal.proxy_name + "'."); + } + + p_output.append(MEMBER_BEGIN "[Obsolete(\""); + p_output.append(p_isignal.deprecation_message); + p_output.append("\")]"); + } + + bool is_parameterless = p_isignal.arguments.size() == 0; + + // Delegate name is [SignalName]EventHandler + String delegate_name = is_parameterless ? "Action" : p_isignal.proxy_name + "EventHandler"; + + if (!is_parameterless) { + // Generate delegate + p_output.append(MEMBER_BEGIN "public delegate void "); + p_output.append(delegate_name); + p_output.append("("); + p_output.append(arguments_sig); + p_output.append(");\n"); + + // Generate Callable trampoline for the delegate + p_output << MEMBER_BEGIN "private static unsafe void " << p_isignal.proxy_name << "Trampoline" + << "(object delegateObj, NativeVariantPtrArgs args, out godot_variant ret)\n" + << INDENT1 "{\n" + << INDENT2 "Callable.ThrowIfArgCountMismatch(args, " << itos(p_isignal.arguments.size()) << ");\n" + << INDENT2 "((" << delegate_name << ")delegateObj)("; + + int idx = 0; + for (const ArgumentInterface &iarg : p_isignal.arguments) { + const TypeInterface *arg_type = _get_type_or_null(iarg.type); + ERR_FAIL_NULL_V(arg_type, ERR_BUG); // Argument type not found + + if (idx != 0) { + p_output << ","; + } + + // TODO: We don't need to use VariantConversionCallbacks. We have the type information so we can use [cs_variant_to_managed] and [cs_managed_to_variant]. + p_output << "\n" INDENT3 "VariantConversionCallbacks.GetToManagedCallback<" + << arg_type->cs_type << ">()(args[" << itos(idx) << "])"; + + idx++; + } + + p_output << ");\n" + << INDENT2 "ret = default;\n" + << INDENT1 "}\n"; + } + if (p_isignal.method_doc && p_isignal.method_doc->description.size()) { String xml_summary = bbcode_to_xml(fix_doc_description(p_isignal.method_doc->description), &p_itype); Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>(); @@ -2247,25 +2319,11 @@ Error BindingsGenerator::_generate_cs_signal(const BindingsGenerator::TypeInterf } if (p_isignal.is_deprecated) { - if (p_isignal.deprecation_message.is_empty()) { - WARN_PRINT("An empty deprecation message is discouraged. Signal: '" + p_isignal.proxy_name + "'."); - } - p_output.append(MEMBER_BEGIN "[Obsolete(\""); p_output.append(p_isignal.deprecation_message); p_output.append("\")]"); } - String delegate_name = p_isignal.proxy_name; - delegate_name += "EventHandler"; // Delegate name is [SignalName]EventHandler - - // Generate delegate - p_output.append(MEMBER_BEGIN "public delegate void "); - p_output.append(delegate_name); - p_output.append("("); - p_output.append(arguments_sig); - p_output.append(");\n"); - // TODO: // Could we assume the StringName instance of signal name will never be freed (it's stored in ClassDB) before the managed world is unloaded? // If so, we could store the pointer we get from `data_unique_pointer()` instead of allocating StringName here. @@ -2277,6 +2335,11 @@ Error BindingsGenerator::_generate_cs_signal(const BindingsGenerator::TypeInterf p_output.append("static "); } + if (!is_parameterless) { + // `unsafe` is needed for taking the trampoline's function pointer + p_output << "unsafe "; + } + p_output.append("event "); p_output.append(delegate_name); p_output.append(" "); @@ -2289,8 +2352,13 @@ Error BindingsGenerator::_generate_cs_signal(const BindingsGenerator::TypeInterf p_output.append("add => Connect(SignalName."); } - p_output.append(p_isignal.proxy_name); - p_output.append(", new Callable(value));\n"); + if (is_parameterless) { + // Delegate type is Action. No need for custom trampoline. + p_output << p_isignal.proxy_name << ", Callable.From(value));\n"; + } else { + p_output << p_isignal.proxy_name + << ", Callable.CreateWithUnsafeTrampoline(value, &" << p_isignal.proxy_name << "Trampoline));\n"; + } if (p_itype.is_singleton) { p_output.append(INDENT2 "remove => " CS_PROPERTY_SINGLETON ".Disconnect(SignalName."); @@ -2298,8 +2366,14 @@ Error BindingsGenerator::_generate_cs_signal(const BindingsGenerator::TypeInterf p_output.append(INDENT2 "remove => Disconnect(SignalName."); } - p_output.append(p_isignal.proxy_name); - p_output.append(", new Callable(value));\n"); + if (is_parameterless) { + // Delegate type is Action. No need for custom trampoline. + p_output << p_isignal.proxy_name << ", Callable.From(value));\n"; + } else { + p_output << p_isignal.proxy_name + << ", Callable.CreateWithUnsafeTrampoline(value, &" << p_isignal.proxy_name << "Trampoline));\n"; + } + p_output.append(CLOSE_BLOCK_L1); } @@ -3104,9 +3178,10 @@ bool BindingsGenerator::_populate_object_type_interfaces() { for (const KeyValue<StringName, ClassDB::ClassInfo::EnumInfo> &E : enum_map) { StringName enum_proxy_cname = E.key; String enum_proxy_name = enum_proxy_cname.operator String(); - if (itype.find_property_by_proxy_name(enum_proxy_cname)) { - // We have several conflicts between enums and PascalCase properties, - // so we append 'Enum' to the enum name in those cases. + if (itype.find_property_by_proxy_name(enum_proxy_name) || itype.find_method_by_proxy_name(enum_proxy_name) || itype.find_signal_by_proxy_name(enum_proxy_name)) { + // In case the enum name conflicts with other PascalCase members, + // we append 'Enum' to the enum name in those cases. + // We have several conflicts between enums and PascalCase properties. enum_proxy_name += "Enum"; enum_proxy_cname = StringName(enum_proxy_name); } @@ -3155,7 +3230,15 @@ bool BindingsGenerator::_populate_object_type_interfaces() { int64_t *value = class_info->constant_map.getptr(StringName(constant_name)); ERR_FAIL_NULL_V(value, false); - ConstantInterface iconstant(constant_name, snake_to_pascal_case(constant_name, true), *value); + String constant_proxy_name = snake_to_pascal_case(constant_name, true); + + if (itype.find_property_by_proxy_name(constant_proxy_name) || itype.find_method_by_proxy_name(constant_proxy_name) || itype.find_signal_by_proxy_name(constant_proxy_name)) { + // In case the constant name conflicts with other PascalCase members, + // we append 'Constant' to the constant name in those cases. + constant_proxy_name += "Constant"; + } + + ConstantInterface iconstant(constant_name, constant_proxy_name, *value); iconstant.const_doc = nullptr; for (int i = 0; i < itype.class_doc->constants.size(); i++) { @@ -3311,11 +3394,11 @@ bool BindingsGenerator::_arg_default_value_from_variant(const Variant &p_val, Ar r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL; } break; case Variant::PROJECTION: { - Projection transform = p_val.operator Projection(); - if (transform == Projection()) { + Projection projection = p_val.operator Projection(); + if (projection == Projection()) { r_iarg.default_argument = "Projection.Identity"; } else { - r_iarg.default_argument = "new Projection(new Vector4" + transform.matrix[0].operator String() + ", new Vector4" + transform.matrix[1].operator String() + ", new Vector4" + transform.matrix[2].operator String() + ", new Vector4" + transform.matrix[3].operator String() + ")"; + r_iarg.default_argument = "new Projection(new Vector4" + projection.columns[0].operator String() + ", new Vector4" + projection.columns[1].operator String() + ", new Vector4" + projection.columns[2].operator String() + ", new Vector4" + projection.columns[3].operator String() + ")"; } r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL; } break; diff --git a/modules/mono/editor/code_completion.cpp b/modules/mono/editor/code_completion.cpp index 40296eef10..dc69567261 100644 --- a/modules/mono/editor/code_completion.cpp +++ b/modules/mono/editor/code_completion.cpp @@ -140,7 +140,7 @@ PackedStringArray get_code_completion(CompletionKind p_kind, const String &p_scr } } break; case CompletionKind::RESOURCE_PATHS: { - if (bool(EditorSettings::get_singleton()->get("text_editor/completion/complete_file_paths"))) { + if (bool(EDITOR_GET("text_editor/completion/complete_file_paths"))) { _get_directory_contents(EditorFileSystem::get_singleton()->get_filesystem(), suggestions); } } break; diff --git a/modules/mono/editor/editor_internal_calls.cpp b/modules/mono/editor/editor_internal_calls.cpp index 6f42ad6916..91392c8f79 100644 --- a/modules/mono/editor/editor_internal_calls.cpp +++ b/modules/mono/editor/editor_internal_calls.cpp @@ -152,7 +152,7 @@ bool godot_icall_Internal_ScriptEditorEdit(Resource *p_resource, int32_t p_line, } void godot_icall_Internal_EditorNodeShowScriptScreen() { - EditorNode::get_singleton()->call("_editor_select", EditorNode::EDITOR_SCRIPT); + EditorNode::get_singleton()->editor_select(EditorNode::EDITOR_SCRIPT); } void godot_icall_Internal_EditorRunPlay() { diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs index 1c98dfcdf6..f1b46e293b 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs @@ -489,25 +489,37 @@ namespace Godot.Collections ICollection<T>, IEnumerable<T> { + private static godot_variant ToVariantFunc(in Array<T> godotArray) => + VariantUtils.CreateFromArray(godotArray); + + private static Array<T> FromVariantFunc(in godot_variant variant) => + VariantUtils.ConvertToArrayObject<T>(variant); + // ReSharper disable StaticMemberInGenericType // Warning is about unique static fields being created for each generic type combination: // https://www.jetbrains.com/help/resharper/StaticMemberInGenericType.html // In our case this is exactly what we want. - private static unsafe delegate* managed<in T, godot_variant> _convertToVariantCallback; - private static unsafe delegate* managed<in godot_variant, T> _convertToManagedCallback; + private static readonly unsafe delegate* managed<in T, godot_variant> ConvertToVariantCallback; + private static readonly unsafe delegate* managed<in godot_variant, T> ConvertToManagedCallback; // ReSharper restore StaticMemberInGenericType static unsafe Array() { - _convertToVariantCallback = VariantConversionCallbacks.GetToVariantCallback<T>(); - _convertToManagedCallback = VariantConversionCallbacks.GetToManagedCallback<T>(); + VariantConversionCallbacks.GenericConversionCallbacks[typeof(Array<T>)] = + ( + (IntPtr)(delegate* managed<in Array<T>, godot_variant>)&ToVariantFunc, + (IntPtr)(delegate* managed<in godot_variant, Array<T>>)&FromVariantFunc + ); + + ConvertToVariantCallback = VariantConversionCallbacks.GetToVariantCallback<T>(); + ConvertToManagedCallback = VariantConversionCallbacks.GetToManagedCallback<T>(); } private static unsafe void ValidateVariantConversionCallbacks() { - if (_convertToVariantCallback == null || _convertToManagedCallback == null) + if (ConvertToVariantCallback == null || ConvertToManagedCallback == null) { throw new InvalidOperationException( $"The array element type is not supported for conversion to Variant: '{typeof(T).FullName}'."); @@ -653,7 +665,7 @@ namespace Godot.Collections get { _underlyingArray.GetVariantBorrowElementAt(index, out godot_variant borrowElem); - return _convertToManagedCallback(borrowElem); + return ConvertToManagedCallback(borrowElem); } set { @@ -663,7 +675,7 @@ namespace Godot.Collections godot_variant* ptrw = NativeFuncs.godotsharp_array_ptrw(ref self); godot_variant* itemPtr = &ptrw[index]; (*itemPtr).Dispose(); - *itemPtr = _convertToVariantCallback(value); + *itemPtr = ConvertToVariantCallback(value); } } @@ -675,7 +687,7 @@ namespace Godot.Collections /// <returns>The index of the item, or -1 if not found.</returns> public unsafe int IndexOf(T item) { - using var variantValue = _convertToVariantCallback(item); + using var variantValue = ConvertToVariantCallback(item); var self = (godot_array)_underlyingArray.NativeValue; return NativeFuncs.godotsharp_array_index_of(ref self, variantValue); } @@ -693,7 +705,7 @@ namespace Godot.Collections if (index < 0 || index > Count) throw new ArgumentOutOfRangeException(nameof(index)); - using var variantValue = _convertToVariantCallback(item); + using var variantValue = ConvertToVariantCallback(item); var self = (godot_array)_underlyingArray.NativeValue; NativeFuncs.godotsharp_array_insert(ref self, index, variantValue); } @@ -726,7 +738,7 @@ namespace Godot.Collections /// <returns>The new size after adding the item.</returns> public unsafe void Add(T item) { - using var variantValue = _convertToVariantCallback(item); + using var variantValue = ConvertToVariantCallback(item); var self = (godot_array)_underlyingArray.NativeValue; _ = NativeFuncs.godotsharp_array_add(ref self, variantValue); } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Basis.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Basis.cs index fbd59d649f..bb1d6e1661 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Basis.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Basis.cs @@ -244,50 +244,258 @@ namespace Godot } /// <summary> - /// Returns the basis's rotation in the form of Euler angles - /// (in the YXZ convention: when *decomposing*, first Z, then X, and Y last). - /// The returned vector contains the rotation angles in - /// the format (X angle, Y angle, Z angle). + /// Returns the basis's rotation in the form of Euler angles. + /// The Euler order depends on the [param order] parameter, + /// by default it uses the YXZ convention: when decomposing, + /// first Z, then X, and Y last. The returned vector contains + /// the rotation angles in the format (X angle, Y angle, Z angle). /// /// Consider using the <see cref="GetRotationQuaternion"/> method instead, which /// returns a <see cref="Quaternion"/> quaternion instead of Euler angles. /// </summary> + /// <param name="order">The Euler order to use. By default, use YXZ order (most common).</param> /// <returns>A <see cref="Vector3"/> representing the basis rotation in Euler angles.</returns> - public Vector3 GetEuler() + public Vector3 GetEuler(EulerOrder order = EulerOrder.Yxz) { - Basis m = Orthonormalized(); - - Vector3 euler; - euler.z = 0.0f; - - real_t mzy = m.Row1[2]; - - if (mzy < 1.0f) + switch (order) { - if (mzy > -1.0f) + case EulerOrder.Xyz: { - euler.x = Mathf.Asin(-mzy); - euler.y = Mathf.Atan2(m.Row0[2], m.Row2[2]); - euler.z = Mathf.Atan2(m.Row1[0], m.Row1[1]); + // Euler angles in XYZ convention. + // See https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix + // + // rot = cy*cz -cy*sz sy + // cz*sx*sy+cx*sz cx*cz-sx*sy*sz -cy*sx + // -cx*cz*sy+sx*sz cz*sx+cx*sy*sz cx*cy + Vector3 euler; + real_t sy = Row0[2]; + if (sy < (1.0f - Mathf.Epsilon)) + { + if (sy > -(1.0f - Mathf.Epsilon)) + { + // is this a pure Y rotation? + if (Row1[0] == 0 && Row0[1] == 0 && Row1[2] == 0 && Row2[1] == 0 && Row1[1] == 1) + { + // return the simplest form (human friendlier in editor and scripts) + euler.x = 0; + euler.y = Mathf.Atan2(Row0[2], Row0[0]); + euler.z = 0; + } + else + { + euler.x = Mathf.Atan2(-Row1[2], Row2[2]); + euler.y = Mathf.Asin(sy); + euler.z = Mathf.Atan2(-Row0[1], Row0[0]); + } + } + else + { + euler.x = Mathf.Atan2(Row2[1], Row1[1]); + euler.y = -Mathf.Tau / 4.0f; + euler.z = 0.0f; + } + } + else + { + euler.x = Mathf.Atan2(Row2[1], Row1[1]); + euler.y = Mathf.Tau / 4.0f; + euler.z = 0.0f; + } + return euler; } - else + case EulerOrder.Xzy: { - euler.x = Mathf.Pi * 0.5f; - euler.y = -Mathf.Atan2(-m.Row0[1], m.Row0[0]); + // Euler angles in XZY convention. + // See https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix + // + // rot = cz*cy -sz cz*sy + // sx*sy+cx*cy*sz cx*cz cx*sz*sy-cy*sx + // cy*sx*sz cz*sx cx*cy+sx*sz*sy + Vector3 euler; + real_t sz = Row0[1]; + if (sz < (1.0f - Mathf.Epsilon)) + { + if (sz > -(1.0f - Mathf.Epsilon)) + { + euler.x = Mathf.Atan2(Row2[1], Row1[1]); + euler.y = Mathf.Atan2(Row0[2], Row0[0]); + euler.z = Mathf.Asin(-sz); + } + else + { + // It's -1 + euler.x = -Mathf.Atan2(Row1[2], Row2[2]); + euler.y = 0.0f; + euler.z = Mathf.Tau / 4.0f; + } + } + else + { + // It's 1 + euler.x = -Mathf.Atan2(Row1[2], Row2[2]); + euler.y = 0.0f; + euler.z = -Mathf.Tau / 4.0f; + } + return euler; } - } - else - { - euler.x = -Mathf.Pi * 0.5f; - euler.y = -Mathf.Atan2(-m.Row0[1], m.Row0[0]); - } + case EulerOrder.Yxz: + { + // Euler angles in YXZ convention. + // See https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix + // + // rot = cy*cz+sy*sx*sz cz*sy*sx-cy*sz cx*sy + // cx*sz cx*cz -sx + // cy*sx*sz-cz*sy cy*cz*sx+sy*sz cy*cx + Vector3 euler; + real_t m12 = Row1[2]; + if (m12 < (1 - Mathf.Epsilon)) + { + if (m12 > -(1 - Mathf.Epsilon)) + { + // is this a pure X rotation? + if (Row1[0] == 0 && Row0[1] == 0 && Row0[2] == 0 && Row2[0] == 0 && Row0[0] == 1) + { + // return the simplest form (human friendlier in editor and scripts) + euler.x = Mathf.Atan2(-m12, Row1[1]); + euler.y = 0; + euler.z = 0; + } + else + { + euler.x = Mathf.Asin(-m12); + euler.y = Mathf.Atan2(Row0[2], Row2[2]); + euler.z = Mathf.Atan2(Row1[0], Row1[1]); + } + } + else + { // m12 == -1 + euler.x = Mathf.Tau / 4.0f; + euler.y = Mathf.Atan2(Row0[1], Row0[0]); + euler.z = 0; + } + } + else + { // m12 == 1 + euler.x = -Mathf.Tau / 4.0f; + euler.y = -Mathf.Atan2(Row0[1], Row0[0]); + euler.z = 0; + } - return euler; + return euler; + } + case EulerOrder.Yzx: + { + // Euler angles in YZX convention. + // See https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix + // + // rot = cy*cz sy*sx-cy*cx*sz cx*sy+cy*sz*sx + // sz cz*cx -cz*sx + // -cz*sy cy*sx+cx*sy*sz cy*cx-sy*sz*sx + Vector3 euler; + real_t sz = Row1[0]; + if (sz < (1.0f - Mathf.Epsilon)) + { + if (sz > -(1.0f - Mathf.Epsilon)) + { + euler.x = Mathf.Atan2(-Row1[2], Row1[1]); + euler.y = Mathf.Atan2(-Row2[0], Row0[0]); + euler.z = Mathf.Asin(sz); + } + else + { + // It's -1 + euler.x = Mathf.Atan2(Row2[1], Row2[2]); + euler.y = 0.0f; + euler.z = -Mathf.Tau / 4.0f; + } + } + else + { + // It's 1 + euler.x = Mathf.Atan2(Row2[1], Row2[2]); + euler.y = 0.0f; + euler.z = Mathf.Tau / 4.0f; + } + return euler; + } + case EulerOrder.Zxy: + { + // Euler angles in ZXY convention. + // See https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix + // + // rot = cz*cy-sz*sx*sy -cx*sz cz*sy+cy*sz*sx + // cy*sz+cz*sx*sy cz*cx sz*sy-cz*cy*sx + // -cx*sy sx cx*cy + Vector3 euler; + real_t sx = Row2[1]; + if (sx < (1.0f - Mathf.Epsilon)) + { + if (sx > -(1.0f - Mathf.Epsilon)) + { + euler.x = Mathf.Asin(sx); + euler.y = Mathf.Atan2(-Row2[0], Row2[2]); + euler.z = Mathf.Atan2(-Row0[1], Row1[1]); + } + else + { + // It's -1 + euler.x = -Mathf.Tau / 4.0f; + euler.y = Mathf.Atan2(Row0[2], Row0[0]); + euler.z = 0; + } + } + else + { + // It's 1 + euler.x = Mathf.Tau / 4.0f; + euler.y = Mathf.Atan2(Row0[2], Row0[0]); + euler.z = 0; + } + return euler; + } + case EulerOrder.Zyx: + { + // Euler angles in ZYX convention. + // See https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix + // + // rot = cz*cy cz*sy*sx-cx*sz sz*sx+cz*cx*cy + // cy*sz cz*cx+sz*sy*sx cx*sz*sy-cz*sx + // -sy cy*sx cy*cx + Vector3 euler; + real_t sy = Row2[0]; + if (sy < (1.0f - Mathf.Epsilon)) + { + if (sy > -(1.0f - Mathf.Epsilon)) + { + euler.x = Mathf.Atan2(Row2[1], Row2[2]); + euler.y = Mathf.Asin(-sy); + euler.z = Mathf.Atan2(Row1[0], Row0[0]); + } + else + { + // It's -1 + euler.x = 0; + euler.y = Mathf.Tau / 4.0f; + euler.z = -Mathf.Atan2(Row0[1], Row1[1]); + } + } + else + { + // It's 1 + euler.x = 0; + euler.y = -Mathf.Tau / 4.0f; + euler.z = -Mathf.Atan2(Row0[1], Row1[1]); + } + return euler; + } + default: + throw new ArgumentOutOfRangeException(nameof(order)); + } } /// <summary> /// Returns the basis's rotation in the form of a quaternion. - /// See <see cref="GetEuler()"/> if you need Euler angles, but keep in + /// See <see cref="GetEuler"/> if you need Euler angles, but keep in /// mind that quaternions should generally be preferred to Euler angles. /// </summary> /// <returns>A <see cref="Quaternion"/> representing the basis's rotation.</returns> @@ -712,35 +920,6 @@ namespace Godot } /// <summary> - /// Constructs a pure rotation basis matrix from the given Euler angles - /// (in the YXZ convention: when *composing*, first Y, then X, and Z last), - /// given in the vector format as (X angle, Y angle, Z angle). - /// - /// Consider using the <see cref="Basis(Quaternion)"/> constructor instead, which - /// uses a <see cref="Quaternion"/> quaternion instead of Euler angles. - /// </summary> - /// <param name="eulerYXZ">The Euler angles to create the basis from.</param> - public Basis(Vector3 eulerYXZ) - { - real_t c; - real_t s; - - c = Mathf.Cos(eulerYXZ.x); - s = Mathf.Sin(eulerYXZ.x); - var xmat = new Basis(1, 0, 0, 0, c, -s, 0, s, c); - - c = Mathf.Cos(eulerYXZ.y); - s = Mathf.Sin(eulerYXZ.y); - var ymat = new Basis(c, 0, s, 0, 1, 0, -s, 0, c); - - c = Mathf.Cos(eulerYXZ.z); - s = Mathf.Sin(eulerYXZ.z); - var zmat = new Basis(c, -s, 0, s, c, 0, 0, 0, 1); - - this = ymat * xmat * zmat; - } - - /// <summary> /// Constructs a pure rotation basis matrix, rotated around the given <paramref name="axis"/> /// by <paramref name="angle"/> (in radians). The axis must be a normalized vector. /// </summary> @@ -800,6 +979,46 @@ namespace Godot } /// <summary> + /// Constructs a Basis matrix from Euler angles in the specified rotation order. By default, use YXZ order (most common). + /// </summary> + /// <param name="euler">The Euler angles to use.</param> + /// <param name="order">The order to compose the Euler angles.</param> + public static Basis FromEuler(Vector3 euler, EulerOrder order = EulerOrder.Yxz) + { + real_t c, s; + + c = Mathf.Cos(euler.x); + s = Mathf.Sin(euler.x); + Basis xmat = new Basis(new Vector3(1, 0, 0), new Vector3(0, c, s), new Vector3(0, -s, c)); + + c = Mathf.Cos(euler.y); + s = Mathf.Sin(euler.y); + Basis ymat = new Basis(new Vector3(c, 0, -s), new Vector3(0, 1, 0), new Vector3(s, 0, c)); + + c = Mathf.Cos(euler.z); + s = Mathf.Sin(euler.z); + Basis zmat = new Basis(new Vector3(c, s, 0), new Vector3(-s, c, 0), new Vector3(0, 0, 1)); + + switch (order) + { + case EulerOrder.Xyz: + return xmat * ymat * zmat; + case EulerOrder.Xzy: + return xmat * zmat * ymat; + case EulerOrder.Yxz: + return ymat * xmat * zmat; + case EulerOrder.Yzx: + return ymat * zmat * xmat; + case EulerOrder.Zxy: + return zmat * xmat * ymat; + case EulerOrder.Zyx: + return zmat * ymat * xmat; + default: + throw new ArgumentOutOfRangeException(nameof(order)); + } + } + + /// <summary> /// Constructs a pure scale basis matrix with no rotation or shearing. /// The scale values are set as the main diagonal of the matrix, /// and all of the other parts of the matrix are zero. diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/CSharpInstanceBridge.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/CSharpInstanceBridge.cs index ae44f8f4ba..354212da1b 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/CSharpInstanceBridge.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/CSharpInstanceBridge.cs @@ -22,8 +22,7 @@ namespace Godot.Bridge } bool methodInvoked = godotObject.InvokeGodotClassMethod(CustomUnsafe.AsRef(method), - new NativeVariantPtrArgs(args), - argCount, out godot_variant retValue); + new NativeVariantPtrArgs(args, argCount), out godot_variant retValue); if (!methodInvoked) { @@ -102,7 +101,7 @@ namespace Godot.Bridge return godot_bool.False; } - *outRet = Marshaling.ConvertManagedObjectToVariant(ret); + *outRet = ret.CopyNativeVariant(); return godot_bool.True; } catch (Exception e) diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/ManagedCallbacks.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/ManagedCallbacks.cs index 57240624bc..44ea8fc83d 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/ManagedCallbacks.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/ManagedCallbacks.cs @@ -9,7 +9,7 @@ namespace Godot.Bridge { // @formatter:off public delegate* unmanaged<IntPtr, godot_variant**, int, godot_bool*, void> SignalAwaiter_SignalCallback; - public delegate* unmanaged<IntPtr, godot_variant**, uint, godot_variant*, void> DelegateUtils_InvokeWithVariantArgs; + public delegate* unmanaged<IntPtr, void*, godot_variant**, int, godot_variant*, void> DelegateUtils_InvokeWithVariantArgs; public delegate* unmanaged<IntPtr, IntPtr, godot_bool> DelegateUtils_DelegateEquals; public delegate* unmanaged<IntPtr, godot_array*, godot_bool> DelegateUtils_TrySerializeDelegateWithGCHandle; public delegate* unmanaged<godot_array*, IntPtr*, godot_bool> DelegateUtils_TryDeserializeDelegateWithGCHandle; diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/ScriptManagerBridge.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/ScriptManagerBridge.cs index 092724a6b1..d83cf43eb2 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/ScriptManagerBridge.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/ScriptManagerBridge.cs @@ -339,7 +339,7 @@ namespace Godot.Bridge *outOwnerIsNull = godot_bool.False; owner.RaiseGodotClassSignalCallbacks(CustomUnsafe.AsRef(eventSignalName), - new NativeVariantPtrArgs(args), argCount); + new NativeVariantPtrArgs(args, argCount)); } catch (Exception e) { diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Callable.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Callable.cs index 1b7f5158fd..f9309ca13e 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Callable.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Callable.cs @@ -26,11 +26,12 @@ namespace Godot /// } /// </code> /// </example> - public readonly struct Callable + public readonly partial struct Callable { private readonly Object _target; private readonly StringName _method; private readonly Delegate _delegate; + private readonly unsafe delegate* managed<object, NativeVariantPtrArgs, out godot_variant, void> _trampoline; /// <summary> /// Object that contains the method. @@ -48,10 +49,10 @@ namespace Godot public Delegate Delegate => _delegate; /// <summary> - /// Converts a <see cref="Delegate"/> to a <see cref="Callable"/>. + /// Trampoline function pointer for dynamically invoking <see cref="Callable.Delegate"/>. /// </summary> - /// <param name="delegate">The delegate to convert.</param> - public static implicit operator Callable(Delegate @delegate) => new Callable(@delegate); + public unsafe delegate* managed<object, NativeVariantPtrArgs, out godot_variant, void> Trampoline + => _trampoline; /// <summary> /// Constructs a new <see cref="Callable"/> for the method called <paramref name="method"/> @@ -59,22 +60,21 @@ namespace Godot /// </summary> /// <param name="target">Object that contains the method.</param> /// <param name="method">Name of the method that will be called.</param> - public Callable(Object target, StringName method) + public unsafe Callable(Object target, StringName method) { _target = target; _method = method; _delegate = null; + _trampoline = null; } - /// <summary> - /// Constructs a new <see cref="Callable"/> for the given <paramref name="delegate"/>. - /// </summary> - /// <param name="delegate">Delegate method that will be called.</param> - public Callable(Delegate @delegate) + private unsafe Callable(Delegate @delegate, + delegate* managed<object, NativeVariantPtrArgs, out godot_variant, void> trampoline) { - _target = null; + _target = @delegate?.Target as Object; _method = null; _delegate = @delegate; + _trampoline = trampoline; } private const int VarArgsSpanThreshold = 5; @@ -149,5 +149,59 @@ namespace Godot NativeFuncs.godotsharp_callable_call_deferred(callable, (godot_variant**)argsPtr, argc); } } + + /// <summary> + /// <para> + /// Constructs a new <see cref="Callable"/> using the <paramref name="trampoline"/> + /// function pointer to dynamically invoke the given <paramref name="delegate"/>. + /// </para> + /// <para> + /// The parameters passed to the <paramref name="trampoline"/> function are: + /// </para> + /// <list type="number"> + /// <item> + /// <term>delegateObj</term> + /// <description>The given <paramref name="delegate"/>, upcast to <see cref="object"/>.</description> + /// </item> + /// <item> + /// <term>args</term> + /// <description>Array of <see cref="godot_variant"/> arguments.</description> + /// </item> + /// <item> + /// <term>ret</term> + /// <description>Return value of type <see cref="godot_variant"/>.</description> + /// </item> + ///</list> + /// <para> + /// The delegate should be downcast to a more specific delegate type before invoking. + /// </para> + /// </summary> + /// <example> + /// Usage example: + /// + /// <code> + /// static void Trampoline(object delegateObj, NativeVariantPtrArgs args, out godot_variant ret) + /// { + /// if (args.Count != 1) + /// throw new ArgumentException($"Callable expected {1} arguments but received {args.Count}."); + /// + /// TResult res = ((Func<int, string>)delegateObj)( + /// VariantConversionCallbacks.GetToManagedCallback<int>()(args[0]) + /// ); + /// + /// ret = VariantConversionCallbacks.GetToVariantCallback<string>()(res); + /// } + /// + /// var callable = Callable.CreateWithUnsafeTrampoline((int num) => "foo" + num.ToString(), &Trampoline); + /// var res = (string)callable.Call(10); + /// Console.WriteLine(res); + /// </code> + /// </example> + /// <param name="delegate">Delegate method that will be called.</param> + /// <param name="trampoline">Trampoline function pointer for invoking the delegate.</param> + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe Callable CreateWithUnsafeTrampoline(Delegate @delegate, + delegate* managed<object, NativeVariantPtrArgs, out godot_variant, void> trampoline) + => new(@delegate, trampoline); } } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Callable.generics.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Callable.generics.cs new file mode 100644 index 0000000000..6c6a104019 --- /dev/null +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Callable.generics.cs @@ -0,0 +1,480 @@ +using System; +using System.Runtime.CompilerServices; +using Godot.NativeInterop; + +namespace Godot; + +#nullable enable + +public readonly partial struct Callable +{ + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void ThrowIfArgCountMismatch(NativeVariantPtrArgs args, int countExpected, + [CallerArgumentExpression("args")] string? paramName = null) + { + if (countExpected != args.Count) + ThrowArgCountMismatch(countExpected, args.Count, paramName); + + static void ThrowArgCountMismatch(int countExpected, int countReceived, string? paramName) + { + throw new ArgumentException( + "Invalid argument count for invoking callable." + + $" Expected {countExpected} arguments, received {countReceived}.", + paramName); + } + } + + /// <summary> + /// Constructs a new <see cref="Callable"/> for the given <paramref name="action"/>. + /// </summary> + /// <param name="action">Action method that will be called.</param> + public static unsafe Callable From( + Action action + ) + { + static void Trampoline(object delegateObj, NativeVariantPtrArgs args, out godot_variant ret) + { + ThrowIfArgCountMismatch(args, 0); + + ((Action)delegateObj)(); + + ret = default; + } + + return CreateWithUnsafeTrampoline(action, &Trampoline); + } + + /// <inheritdoc cref="From(Action)"/> + public static unsafe Callable From<T0>( + Action<T0> action + ) + { + static void Trampoline(object delegateObj, NativeVariantPtrArgs args, out godot_variant ret) + { + ThrowIfArgCountMismatch(args, 1); + + ((Action<T0>)delegateObj)( + VariantConversionCallbacks.GetToManagedCallback<T0>()(args[0]) + ); + + ret = default; + } + + return CreateWithUnsafeTrampoline(action, &Trampoline); + } + + /// <inheritdoc cref="From(Action)"/> + public static unsafe Callable From<T0, T1>( + Action<T0, T1> action + ) + { + static void Trampoline(object delegateObj, NativeVariantPtrArgs args, out godot_variant ret) + { + ThrowIfArgCountMismatch(args, 2); + + ((Action<T0, T1>)delegateObj)( + VariantConversionCallbacks.GetToManagedCallback<T0>()(args[0]), + VariantConversionCallbacks.GetToManagedCallback<T1>()(args[1]) + ); + + ret = default; + } + + return CreateWithUnsafeTrampoline(action, &Trampoline); + } + + /// <inheritdoc cref="From(Action)"/> + public static unsafe Callable From<T0, T1, T2>( + Action<T0, T1, T2> action + ) + { + static void Trampoline(object delegateObj, NativeVariantPtrArgs args, out godot_variant ret) + { + ThrowIfArgCountMismatch(args, 3); + + ((Action<T0, T1, T2>)delegateObj)( + VariantConversionCallbacks.GetToManagedCallback<T0>()(args[0]), + VariantConversionCallbacks.GetToManagedCallback<T1>()(args[1]), + VariantConversionCallbacks.GetToManagedCallback<T2>()(args[2]) + ); + + ret = default; + } + + return CreateWithUnsafeTrampoline(action, &Trampoline); + } + + /// <inheritdoc cref="From(Action)"/> + public static unsafe Callable From<T0, T1, T2, T3>( + Action<T0, T1, T2, T3> action + ) + { + static void Trampoline(object delegateObj, NativeVariantPtrArgs args, out godot_variant ret) + { + ThrowIfArgCountMismatch(args, 4); + + ((Action<T0, T1, T2, T3>)delegateObj)( + VariantConversionCallbacks.GetToManagedCallback<T0>()(args[0]), + VariantConversionCallbacks.GetToManagedCallback<T1>()(args[1]), + VariantConversionCallbacks.GetToManagedCallback<T2>()(args[2]), + VariantConversionCallbacks.GetToManagedCallback<T3>()(args[3]) + ); + + ret = default; + } + + return CreateWithUnsafeTrampoline(action, &Trampoline); + } + + /// <inheritdoc cref="From(Action)"/> + public static unsafe Callable From<T0, T1, T2, T3, T4>( + Action<T0, T1, T2, T3, T4> action + ) + { + static void Trampoline(object delegateObj, NativeVariantPtrArgs args, out godot_variant ret) + { + ThrowIfArgCountMismatch(args, 5); + + ((Action<T0, T1, T2, T3, T4>)delegateObj)( + VariantConversionCallbacks.GetToManagedCallback<T0>()(args[0]), + VariantConversionCallbacks.GetToManagedCallback<T1>()(args[1]), + VariantConversionCallbacks.GetToManagedCallback<T2>()(args[2]), + VariantConversionCallbacks.GetToManagedCallback<T3>()(args[3]), + VariantConversionCallbacks.GetToManagedCallback<T4>()(args[4]) + ); + + ret = default; + } + + return CreateWithUnsafeTrampoline(action, &Trampoline); + } + + /// <inheritdoc cref="From(Action)"/> + public static unsafe Callable From<T0, T1, T2, T3, T4, T5>( + Action<T0, T1, T2, T3, T4, T5> action + ) + { + static void Trampoline(object delegateObj, NativeVariantPtrArgs args, out godot_variant ret) + { + ThrowIfArgCountMismatch(args, 6); + + ((Action<T0, T1, T2, T3, T4, T5>)delegateObj)( + VariantConversionCallbacks.GetToManagedCallback<T0>()(args[0]), + VariantConversionCallbacks.GetToManagedCallback<T1>()(args[1]), + VariantConversionCallbacks.GetToManagedCallback<T2>()(args[2]), + VariantConversionCallbacks.GetToManagedCallback<T3>()(args[3]), + VariantConversionCallbacks.GetToManagedCallback<T4>()(args[4]), + VariantConversionCallbacks.GetToManagedCallback<T5>()(args[5]) + ); + + ret = default; + } + + return CreateWithUnsafeTrampoline(action, &Trampoline); + } + + /// <inheritdoc cref="From(Action)"/> + public static unsafe Callable From<T0, T1, T2, T3, T4, T5, T6>( + Action<T0, T1, T2, T3, T4, T5, T6> action + ) + { + static void Trampoline(object delegateObj, NativeVariantPtrArgs args, out godot_variant ret) + { + ThrowIfArgCountMismatch(args, 7); + + ((Action<T0, T1, T2, T3, T4, T5, T6>)delegateObj)( + VariantConversionCallbacks.GetToManagedCallback<T0>()(args[0]), + VariantConversionCallbacks.GetToManagedCallback<T1>()(args[1]), + VariantConversionCallbacks.GetToManagedCallback<T2>()(args[2]), + VariantConversionCallbacks.GetToManagedCallback<T3>()(args[3]), + VariantConversionCallbacks.GetToManagedCallback<T4>()(args[4]), + VariantConversionCallbacks.GetToManagedCallback<T5>()(args[5]), + VariantConversionCallbacks.GetToManagedCallback<T6>()(args[6]) + ); + + ret = default; + } + + return CreateWithUnsafeTrampoline(action, &Trampoline); + } + + /// <inheritdoc cref="From(Action)"/> + public static unsafe Callable From<T0, T1, T2, T3, T4, T5, T6, T7>( + Action<T0, T1, T2, T3, T4, T5, T6, T7> action + ) + { + static void Trampoline(object delegateObj, NativeVariantPtrArgs args, out godot_variant ret) + { + ThrowIfArgCountMismatch(args, 8); + + ((Action<T0, T1, T2, T3, T4, T5, T6, T7>)delegateObj)( + VariantConversionCallbacks.GetToManagedCallback<T0>()(args[0]), + VariantConversionCallbacks.GetToManagedCallback<T1>()(args[1]), + VariantConversionCallbacks.GetToManagedCallback<T2>()(args[2]), + VariantConversionCallbacks.GetToManagedCallback<T3>()(args[3]), + VariantConversionCallbacks.GetToManagedCallback<T4>()(args[4]), + VariantConversionCallbacks.GetToManagedCallback<T5>()(args[5]), + VariantConversionCallbacks.GetToManagedCallback<T6>()(args[6]), + VariantConversionCallbacks.GetToManagedCallback<T7>()(args[7]) + ); + + ret = default; + } + + return CreateWithUnsafeTrampoline(action, &Trampoline); + } + + /// <inheritdoc cref="From(Action)"/> + public static unsafe Callable From<T0, T1, T2, T3, T4, T5, T6, T7, T8>( + Action<T0, T1, T2, T3, T4, T5, T6, T7, T8> action + ) + { + static void Trampoline(object delegateObj, NativeVariantPtrArgs args, out godot_variant ret) + { + ThrowIfArgCountMismatch(args, 9); + + ((Action<T0, T1, T2, T3, T4, T5, T6, T7, T8>)delegateObj)( + VariantConversionCallbacks.GetToManagedCallback<T0>()(args[0]), + VariantConversionCallbacks.GetToManagedCallback<T1>()(args[1]), + VariantConversionCallbacks.GetToManagedCallback<T2>()(args[2]), + VariantConversionCallbacks.GetToManagedCallback<T3>()(args[3]), + VariantConversionCallbacks.GetToManagedCallback<T4>()(args[4]), + VariantConversionCallbacks.GetToManagedCallback<T5>()(args[5]), + VariantConversionCallbacks.GetToManagedCallback<T6>()(args[6]), + VariantConversionCallbacks.GetToManagedCallback<T7>()(args[7]), + VariantConversionCallbacks.GetToManagedCallback<T8>()(args[8]) + ); + + ret = default; + } + + return CreateWithUnsafeTrampoline(action, &Trampoline); + } + + /// <summary> + /// Constructs a new <see cref="Callable"/> for the given <paramref name="func"/>. + /// </summary> + /// <param name="func">Action method that will be called.</param> + public static unsafe Callable From<TResult>( + Func<TResult> func + ) + { + static void Trampoline(object delegateObj, NativeVariantPtrArgs args, out godot_variant ret) + { + ThrowIfArgCountMismatch(args, 0); + + TResult res = ((Func<TResult>)delegateObj)(); + + ret = VariantConversionCallbacks.GetToVariantCallback<TResult>()(res); + } + + return CreateWithUnsafeTrampoline(func, &Trampoline); + } + + /// <inheritdoc cref="From{TResult}(Func{TResult})"/> + public static unsafe Callable From<T0, TResult>( + Func<T0, TResult> func + ) + { + static void Trampoline(object delegateObj, NativeVariantPtrArgs args, out godot_variant ret) + { + ThrowIfArgCountMismatch(args, 1); + + TResult res = ((Func<T0, TResult>)delegateObj)( + VariantConversionCallbacks.GetToManagedCallback<T0>()(args[0]) + ); + + ret = VariantConversionCallbacks.GetToVariantCallback<TResult>()(res); + } + + return CreateWithUnsafeTrampoline(func, &Trampoline); + } + + /// <inheritdoc cref="From{TResult}(Func{TResult})"/> + public static unsafe Callable From<T0, T1, TResult>( + Func<T0, T1, TResult> func + ) + { + static void Trampoline(object delegateObj, NativeVariantPtrArgs args, out godot_variant ret) + { + ThrowIfArgCountMismatch(args, 2); + + TResult res = ((Func<T0, T1, TResult>)delegateObj)( + VariantConversionCallbacks.GetToManagedCallback<T0>()(args[0]), + VariantConversionCallbacks.GetToManagedCallback<T1>()(args[1]) + ); + + ret = VariantConversionCallbacks.GetToVariantCallback<TResult>()(res); + } + + return CreateWithUnsafeTrampoline(func, &Trampoline); + } + + /// <inheritdoc cref="From{TResult}(Func{TResult})"/> + public static unsafe Callable From<T0, T1, T2, TResult>( + Func<T0, T1, T2, TResult> func + ) + { + static void Trampoline(object delegateObj, NativeVariantPtrArgs args, out godot_variant ret) + { + ThrowIfArgCountMismatch(args, 3); + + TResult res = ((Func<T0, T1, T2, TResult>)delegateObj)( + VariantConversionCallbacks.GetToManagedCallback<T0>()(args[0]), + VariantConversionCallbacks.GetToManagedCallback<T1>()(args[1]), + VariantConversionCallbacks.GetToManagedCallback<T2>()(args[2]) + ); + + ret = VariantConversionCallbacks.GetToVariantCallback<TResult>()(res); + } + + return CreateWithUnsafeTrampoline(func, &Trampoline); + } + + /// <inheritdoc cref="From{TResult}(Func{TResult})"/> + public static unsafe Callable From<T0, T1, T2, T3, TResult>( + Func<T0, T1, T2, T3, TResult> func + ) + { + static void Trampoline(object delegateObj, NativeVariantPtrArgs args, out godot_variant ret) + { + ThrowIfArgCountMismatch(args, 4); + + TResult res = ((Func<T0, T1, T2, T3, TResult>)delegateObj)( + VariantConversionCallbacks.GetToManagedCallback<T0>()(args[0]), + VariantConversionCallbacks.GetToManagedCallback<T1>()(args[1]), + VariantConversionCallbacks.GetToManagedCallback<T2>()(args[2]), + VariantConversionCallbacks.GetToManagedCallback<T3>()(args[3]) + ); + + ret = VariantConversionCallbacks.GetToVariantCallback<TResult>()(res); + } + + return CreateWithUnsafeTrampoline(func, &Trampoline); + } + + /// <inheritdoc cref="From{TResult}(Func{TResult})"/> + public static unsafe Callable From<T0, T1, T2, T3, T4, TResult>( + Func<T0, T1, T2, T3, T4, TResult> func + ) + { + static void Trampoline(object delegateObj, NativeVariantPtrArgs args, out godot_variant ret) + { + ThrowIfArgCountMismatch(args, 5); + + TResult res = ((Func<T0, T1, T2, T3, T4, TResult>)delegateObj)( + VariantConversionCallbacks.GetToManagedCallback<T0>()(args[0]), + VariantConversionCallbacks.GetToManagedCallback<T1>()(args[1]), + VariantConversionCallbacks.GetToManagedCallback<T2>()(args[2]), + VariantConversionCallbacks.GetToManagedCallback<T3>()(args[3]), + VariantConversionCallbacks.GetToManagedCallback<T4>()(args[4]) + ); + + ret = VariantConversionCallbacks.GetToVariantCallback<TResult>()(res); + } + + return CreateWithUnsafeTrampoline(func, &Trampoline); + } + + /// <inheritdoc cref="From{TResult}(Func{TResult})"/> + public static unsafe Callable From<T0, T1, T2, T3, T4, T5, TResult>( + Func<T0, T1, T2, T3, T4, T5, TResult> func + ) + { + static void Trampoline(object delegateObj, NativeVariantPtrArgs args, out godot_variant ret) + { + ThrowIfArgCountMismatch(args, 6); + + TResult res = ((Func<T0, T1, T2, T3, T4, T5, TResult>)delegateObj)( + VariantConversionCallbacks.GetToManagedCallback<T0>()(args[0]), + VariantConversionCallbacks.GetToManagedCallback<T1>()(args[1]), + VariantConversionCallbacks.GetToManagedCallback<T2>()(args[2]), + VariantConversionCallbacks.GetToManagedCallback<T3>()(args[3]), + VariantConversionCallbacks.GetToManagedCallback<T4>()(args[4]), + VariantConversionCallbacks.GetToManagedCallback<T5>()(args[5]) + ); + + ret = VariantConversionCallbacks.GetToVariantCallback<TResult>()(res); + } + + return CreateWithUnsafeTrampoline(func, &Trampoline); + } + + /// <inheritdoc cref="From{TResult}(Func{TResult})"/> + public static unsafe Callable From<T0, T1, T2, T3, T4, T5, T6, TResult>( + Func<T0, T1, T2, T3, T4, T5, T6, TResult> func + ) + { + static void Trampoline(object delegateObj, NativeVariantPtrArgs args, out godot_variant ret) + { + ThrowIfArgCountMismatch(args, 7); + + TResult res = ((Func<T0, T1, T2, T3, T4, T5, T6, TResult>)delegateObj)( + VariantConversionCallbacks.GetToManagedCallback<T0>()(args[0]), + VariantConversionCallbacks.GetToManagedCallback<T1>()(args[1]), + VariantConversionCallbacks.GetToManagedCallback<T2>()(args[2]), + VariantConversionCallbacks.GetToManagedCallback<T3>()(args[3]), + VariantConversionCallbacks.GetToManagedCallback<T4>()(args[4]), + VariantConversionCallbacks.GetToManagedCallback<T5>()(args[5]), + VariantConversionCallbacks.GetToManagedCallback<T6>()(args[6]) + ); + + ret = VariantConversionCallbacks.GetToVariantCallback<TResult>()(res); + } + + return CreateWithUnsafeTrampoline(func, &Trampoline); + } + + /// <inheritdoc cref="From{TResult}(Func{TResult})"/> + public static unsafe Callable From<T0, T1, T2, T3, T4, T5, T6, T7, TResult>( + Func<T0, T1, T2, T3, T4, T5, T6, T7, TResult> func + ) + { + static void Trampoline(object delegateObj, NativeVariantPtrArgs args, out godot_variant ret) + { + ThrowIfArgCountMismatch(args, 8); + + TResult res = ((Func<T0, T1, T2, T3, T4, T5, T6, T7, TResult>)delegateObj)( + VariantConversionCallbacks.GetToManagedCallback<T0>()(args[0]), + VariantConversionCallbacks.GetToManagedCallback<T1>()(args[1]), + VariantConversionCallbacks.GetToManagedCallback<T2>()(args[2]), + VariantConversionCallbacks.GetToManagedCallback<T3>()(args[3]), + VariantConversionCallbacks.GetToManagedCallback<T4>()(args[4]), + VariantConversionCallbacks.GetToManagedCallback<T5>()(args[5]), + VariantConversionCallbacks.GetToManagedCallback<T6>()(args[6]), + VariantConversionCallbacks.GetToManagedCallback<T7>()(args[7]) + ); + + ret = VariantConversionCallbacks.GetToVariantCallback<TResult>()(res); + } + + return CreateWithUnsafeTrampoline(func, &Trampoline); + } + + /// <inheritdoc cref="From{TResult}(Func{TResult})"/> + public static unsafe Callable From<T0, T1, T2, T3, T4, T5, T6, T7, T8, TResult>( + Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, TResult> func + ) + { + static void Trampoline(object delegateObj, NativeVariantPtrArgs args, out godot_variant ret) + { + ThrowIfArgCountMismatch(args, 9); + + TResult res = ((Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, TResult>)delegateObj)( + VariantConversionCallbacks.GetToManagedCallback<T0>()(args[0]), + VariantConversionCallbacks.GetToManagedCallback<T1>()(args[1]), + VariantConversionCallbacks.GetToManagedCallback<T2>()(args[2]), + VariantConversionCallbacks.GetToManagedCallback<T3>()(args[3]), + VariantConversionCallbacks.GetToManagedCallback<T4>()(args[4]), + VariantConversionCallbacks.GetToManagedCallback<T5>()(args[5]), + VariantConversionCallbacks.GetToManagedCallback<T6>()(args[6]), + VariantConversionCallbacks.GetToManagedCallback<T7>()(args[7]), + VariantConversionCallbacks.GetToManagedCallback<T8>()(args[8]) + ); + + ret = VariantConversionCallbacks.GetToVariantCallback<TResult>()(res); + } + + return CreateWithUnsafeTrampoline(func, &Trampoline); + } +} diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Color.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Color.cs index 3483a04c83..ee9e59f9fa 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Color.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Color.cs @@ -597,7 +597,7 @@ namespace Godot /// <exception name="ArgumentOutOfRangeException"> /// <paramref name="rgba"/> color code is invalid. /// </exception> - private static Color FromHTML(string rgba) + private static Color FromHTML(ReadOnlySpan<char> rgba) { Color c; if (rgba.Length == 0) @@ -611,7 +611,7 @@ namespace Godot if (rgba[0] == '#') { - rgba = rgba.Substring(1); + rgba = rgba.Slice(1); } // If enabled, use 1 hex digit per channel instead of 2. @@ -665,22 +665,22 @@ namespace Godot if (c.r < 0) { - throw new ArgumentOutOfRangeException("Invalid color code. Red part is not valid hexadecimal: " + rgba); + throw new ArgumentOutOfRangeException($"Invalid color code. Red part is not valid hexadecimal: {rgba}"); } if (c.g < 0) { - throw new ArgumentOutOfRangeException("Invalid color code. Green part is not valid hexadecimal: " + rgba); + throw new ArgumentOutOfRangeException($"Invalid color code. Green part is not valid hexadecimal: {rgba}"); } if (c.b < 0) { - throw new ArgumentOutOfRangeException("Invalid color code. Blue part is not valid hexadecimal: " + rgba); + throw new ArgumentOutOfRangeException($"Invalid color code. Blue part is not valid hexadecimal: {rgba}"); } if (c.a < 0) { - throw new ArgumentOutOfRangeException("Invalid color code. Alpha part is not valid hexadecimal: " + rgba); + throw new ArgumentOutOfRangeException($"Invalid color code. Alpha part is not valid hexadecimal: {rgba}"); } return c; } @@ -817,9 +817,9 @@ namespace Godot value = max; } - private static int ParseCol4(string str, int ofs) + private static int ParseCol4(ReadOnlySpan<char> str, int index) { - char character = str[ofs]; + char character = str[index]; if (character >= '0' && character <= '9') { @@ -836,9 +836,9 @@ namespace Godot return -1; } - private static int ParseCol8(string str, int ofs) + private static int ParseCol8(ReadOnlySpan<char> str, int index) { - return ParseCol4(str, ofs) * 16 + ParseCol4(str, ofs + 1); + return ParseCol4(str, index) * 16 + ParseCol4(str, index + 1); } private static string ToHex32(float val) @@ -847,16 +847,16 @@ namespace Godot return b.HexEncode(); } - internal static bool HtmlIsValid(string color) + internal static bool HtmlIsValid(ReadOnlySpan<char> color) { - if (string.IsNullOrEmpty(color)) + if (color.IsEmpty) { return false; } if (color[0] == '#') { - color = color.Substring(1); + color = color.Slice(1); } // Check if the amount of hex digits is valid. diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/DelegateUtils.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/DelegateUtils.cs index 3c75d18943..d19e0c08f2 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/DelegateUtils.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/DelegateUtils.cs @@ -30,33 +30,23 @@ namespace Godot } [UnmanagedCallersOnly] - internal static unsafe void InvokeWithVariantArgs(IntPtr delegateGCHandle, godot_variant** args, uint argc, - godot_variant* outRet) + internal static unsafe void InvokeWithVariantArgs(IntPtr delegateGCHandle, void* trampoline, + godot_variant** args, int argc, godot_variant* outRet) { try { - // TODO: Optimize - var @delegate = (Delegate)GCHandle.FromIntPtr(delegateGCHandle).Target!; - var managedArgs = new object?[argc]; - - var parameterInfos = @delegate.Method.GetParameters(); - var paramsLength = parameterInfos.Length; - - if (argc != paramsLength) + if (trampoline == null) { - throw new InvalidOperationException( - $"The delegate expects {paramsLength} arguments, but received {argc}."); + throw new ArgumentNullException(nameof(trampoline), + "Cannot dynamically invoke delegate because the trampoline is null."); } - for (uint i = 0; i < argc; i++) - { - managedArgs[i] = Marshaling.ConvertVariantToManagedObjectOfType( - *args[i], parameterInfos[i].ParameterType); - } + var @delegate = (Delegate)GCHandle.FromIntPtr(delegateGCHandle).Target!; + var trampolineFn = (delegate* managed<object, NativeVariantPtrArgs, out godot_variant, void>)trampoline; - object? invokeRet = @delegate.DynamicInvoke(managedArgs); + trampolineFn(@delegate, new NativeVariantPtrArgs(args, argc), out godot_variant ret); - *outRet = Marshaling.ConvertManagedObjectToVariant(invokeRet); + *outRet = ret; } catch (Exception e) { @@ -76,6 +66,11 @@ namespace Godot internal static bool TrySerializeDelegate(Delegate @delegate, Collections.Array serializedData) { + if (@delegate is null) + { + return false; + } + if (@delegate is MulticastDelegate multicastDelegate) { bool someDelegatesSerialized = false; diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Dictionary.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Dictionary.cs index 93103d0f6b..f8793332a0 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Dictionary.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Dictionary.cs @@ -356,35 +356,47 @@ namespace Godot.Collections IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue> { + private static godot_variant ToVariantFunc(in Dictionary<TKey, TValue> godotDictionary) => + VariantUtils.CreateFromDictionary(godotDictionary); + + private static Dictionary<TKey, TValue> FromVariantFunc(in godot_variant variant) => + VariantUtils.ConvertToDictionaryObject<TKey, TValue>(variant); + // ReSharper disable StaticMemberInGenericType // Warning is about unique static fields being created for each generic type combination: // https://www.jetbrains.com/help/resharper/StaticMemberInGenericType.html // In our case this is exactly what we want. - private static unsafe delegate* managed<in TKey, godot_variant> _convertKeyToVariantCallback; - private static unsafe delegate* managed<in godot_variant, TKey> _convertKeyToManagedCallback; - private static unsafe delegate* managed<in TValue, godot_variant> _convertValueToVariantCallback; - private static unsafe delegate* managed<in godot_variant, TValue> _convertValueToManagedCallback; + private static readonly unsafe delegate* managed<in TKey, godot_variant> ConvertKeyToVariantCallback; + private static readonly unsafe delegate* managed<in godot_variant, TKey> ConvertKeyToManagedCallback; + private static readonly unsafe delegate* managed<in TValue, godot_variant> ConvertValueToVariantCallback; + private static readonly unsafe delegate* managed<in godot_variant, TValue> ConvertValueToManagedCallback; // ReSharper restore StaticMemberInGenericType static unsafe Dictionary() { - _convertKeyToVariantCallback = VariantConversionCallbacks.GetToVariantCallback<TKey>(); - _convertKeyToManagedCallback = VariantConversionCallbacks.GetToManagedCallback<TKey>(); - _convertValueToVariantCallback = VariantConversionCallbacks.GetToVariantCallback<TValue>(); - _convertValueToManagedCallback = VariantConversionCallbacks.GetToManagedCallback<TValue>(); + VariantConversionCallbacks.GenericConversionCallbacks[typeof(Dictionary<TKey, TValue>)] = + ( + (IntPtr)(delegate* managed<in Dictionary<TKey, TValue>, godot_variant>)&ToVariantFunc, + (IntPtr)(delegate* managed<in godot_variant, Dictionary<TKey, TValue>>)&FromVariantFunc + ); + + ConvertKeyToVariantCallback = VariantConversionCallbacks.GetToVariantCallback<TKey>(); + ConvertKeyToManagedCallback = VariantConversionCallbacks.GetToManagedCallback<TKey>(); + ConvertValueToVariantCallback = VariantConversionCallbacks.GetToVariantCallback<TValue>(); + ConvertValueToManagedCallback = VariantConversionCallbacks.GetToManagedCallback<TValue>(); } private static unsafe void ValidateVariantConversionCallbacks() { - if (_convertKeyToVariantCallback == null || _convertKeyToManagedCallback == null) + if (ConvertKeyToVariantCallback == null || ConvertKeyToManagedCallback == null) { throw new InvalidOperationException( $"The dictionary key type is not supported for conversion to Variant: '{typeof(TKey).FullName}'."); } - if (_convertValueToVariantCallback == null || _convertValueToManagedCallback == null) + if (ConvertValueToVariantCallback == null || ConvertValueToManagedCallback == null) { throw new InvalidOperationException( $"The dictionary value type is not supported for conversion to Variant: '{typeof(TValue).FullName}'."); @@ -473,14 +485,14 @@ namespace Godot.Collections { get { - using var variantKey = _convertKeyToVariantCallback(key); + using var variantKey = ConvertKeyToVariantCallback(key); var self = (godot_dictionary)_underlyingDict.NativeValue; if (NativeFuncs.godotsharp_dictionary_try_get_value(ref self, variantKey, out godot_variant value).ToBool()) { using (value) - return _convertValueToManagedCallback(value); + return ConvertValueToManagedCallback(value); } else { @@ -489,8 +501,8 @@ namespace Godot.Collections } set { - using var variantKey = _convertKeyToVariantCallback(key); - using var variantValue = _convertValueToVariantCallback(value); + using var variantKey = ConvertKeyToVariantCallback(key); + using var variantValue = ConvertValueToVariantCallback(value); var self = (godot_dictionary)_underlyingDict.NativeValue; NativeFuncs.godotsharp_dictionary_set_value(ref self, variantKey, variantValue); @@ -539,8 +551,8 @@ namespace Godot.Collections using (value) { return new KeyValuePair<TKey, TValue>( - _convertKeyToManagedCallback(key), - _convertValueToManagedCallback(value)); + ConvertKeyToManagedCallback(key), + ConvertValueToManagedCallback(value)); } } @@ -552,13 +564,13 @@ namespace Godot.Collections /// <param name="value">The object to add.</param> public unsafe void Add(TKey key, TValue value) { - using var variantKey = _convertKeyToVariantCallback(key); + using var variantKey = ConvertKeyToVariantCallback(key); var self = (godot_dictionary)_underlyingDict.NativeValue; if (NativeFuncs.godotsharp_dictionary_contains_key(ref self, variantKey).ToBool()) throw new ArgumentException("An element with the same key already exists.", nameof(key)); - using var variantValue = _convertValueToVariantCallback(value); + using var variantValue = ConvertValueToVariantCallback(value); NativeFuncs.godotsharp_dictionary_add(ref self, variantKey, variantValue); } @@ -569,7 +581,7 @@ namespace Godot.Collections /// <returns>Whether or not this dictionary contains the given key.</returns> public unsafe bool ContainsKey(TKey key) { - using var variantKey = _convertKeyToVariantCallback(key); + using var variantKey = ConvertKeyToVariantCallback(key); var self = (godot_dictionary)_underlyingDict.NativeValue; return NativeFuncs.godotsharp_dictionary_contains_key(ref self, variantKey).ToBool(); } @@ -580,7 +592,7 @@ namespace Godot.Collections /// <param name="key">The key of the element to remove.</param> public unsafe bool Remove(TKey key) { - using var variantKey = _convertKeyToVariantCallback(key); + using var variantKey = ConvertKeyToVariantCallback(key); var self = (godot_dictionary)_underlyingDict.NativeValue; return NativeFuncs.godotsharp_dictionary_remove_key(ref self, variantKey).ToBool(); } @@ -593,13 +605,13 @@ namespace Godot.Collections /// <returns>If an object was found for the given <paramref name="key"/>.</returns> public unsafe bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) { - using var variantKey = _convertKeyToVariantCallback(key); + using var variantKey = ConvertKeyToVariantCallback(key); var self = (godot_dictionary)_underlyingDict.NativeValue; bool found = NativeFuncs.godotsharp_dictionary_try_get_value(ref self, variantKey, out godot_variant retValue).ToBool(); using (retValue) - value = found ? _convertValueToManagedCallback(retValue) : default; + value = found ? ConvertValueToManagedCallback(retValue) : default; return found; } @@ -625,7 +637,7 @@ namespace Godot.Collections unsafe bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) { - using var variantKey = _convertKeyToVariantCallback(item.Key); + using var variantKey = ConvertKeyToVariantCallback(item.Key); var self = (godot_dictionary)_underlyingDict.NativeValue; bool found = NativeFuncs.godotsharp_dictionary_try_get_value(ref self, variantKey, out godot_variant retValue).ToBool(); @@ -635,7 +647,7 @@ namespace Godot.Collections if (!found) return false; - using var variantValue = _convertValueToVariantCallback(item.Value); + using var variantValue = ConvertValueToVariantCallback(item.Value); return NativeFuncs.godotsharp_variant_equals(variantValue, retValue).ToBool(); } } @@ -670,7 +682,7 @@ namespace Godot.Collections unsafe bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) { - using var variantKey = _convertKeyToVariantCallback(item.Key); + using var variantKey = ConvertKeyToVariantCallback(item.Key); var self = (godot_dictionary)_underlyingDict.NativeValue; bool found = NativeFuncs.godotsharp_dictionary_try_get_value(ref self, variantKey, out godot_variant retValue).ToBool(); @@ -680,7 +692,7 @@ namespace Godot.Collections if (!found) return false; - using var variantValue = _convertValueToVariantCallback(item.Value); + using var variantValue = ConvertValueToVariantCallback(item.Value); if (NativeFuncs.godotsharp_variant_equals(variantValue, retValue).ToBool()) { return NativeFuncs.godotsharp_dictionary_remove_key( @@ -717,6 +729,7 @@ namespace Godot.Collections public static implicit operator Variant(Dictionary<TKey, TValue> from) => Variant.CreateFrom(from); [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static explicit operator Dictionary<TKey, TValue>(Variant from) => from.AsGodotDictionary<TKey, TValue>(); + public static explicit operator Dictionary<TKey, TValue>(Variant from) => + from.AsGodotDictionary<TKey, TValue>(); } } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/Marshaling.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/Marshaling.cs index 140fc167ba..649661ee06 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/Marshaling.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/Marshaling.cs @@ -721,9 +721,19 @@ namespace Godot.NativeInterop if (p_managed_callable.Delegate != null) { var gcHandle = CustomGCHandle.AllocStrong(p_managed_callable.Delegate); - NativeFuncs.godotsharp_callable_new_with_delegate( - GCHandle.ToIntPtr(gcHandle), out godot_callable callable); - return callable; + + IntPtr objectPtr = p_managed_callable.Target != null ? + Object.GetPtr(p_managed_callable.Target) : + IntPtr.Zero; + + unsafe + { + NativeFuncs.godotsharp_callable_new_with_delegate( + GCHandle.ToIntPtr(gcHandle), (IntPtr)p_managed_callable.Trampoline, + objectPtr, out godot_callable callable); + + return callable; + } } else { @@ -747,19 +757,22 @@ namespace Godot.NativeInterop public static Callable ConvertCallableToManaged(in godot_callable p_callable) { if (NativeFuncs.godotsharp_callable_get_data_for_marshalling(p_callable, - out IntPtr delegateGCHandle, out IntPtr godotObject, - out godot_string_name name).ToBool()) + out IntPtr delegateGCHandle, out IntPtr trampoline, + out IntPtr godotObject, out godot_string_name name).ToBool()) { if (delegateGCHandle != IntPtr.Zero) { - return new Callable((Delegate?)GCHandle.FromIntPtr(delegateGCHandle).Target); - } - else - { - return new Callable( - InteropUtils.UnmanagedGetManaged(godotObject), - StringName.CreateTakingOwnershipOfDisposableValue(name)); + unsafe + { + return Callable.CreateWithUnsafeTrampoline( + (Delegate?)GCHandle.FromIntPtr(delegateGCHandle).Target, + (delegate* managed<object, NativeVariantPtrArgs, out godot_variant, void>)trampoline); + } } + + return new Callable( + InteropUtils.UnmanagedGetManaged(godotObject), + StringName.CreateTakingOwnershipOfDisposableValue(name)); } // Some other unsupported callable diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeFuncs.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeFuncs.cs index bd00611383..b30b6a0752 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeFuncs.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeFuncs.cs @@ -141,11 +141,11 @@ namespace Godot.NativeInterop public static partial void godotsharp_packed_string_array_add(ref godot_packed_string_array r_dest, in godot_string p_element); - public static partial void godotsharp_callable_new_with_delegate(IntPtr p_delegate_handle, - out godot_callable r_callable); + public static partial void godotsharp_callable_new_with_delegate(IntPtr p_delegate_handle, IntPtr p_trampoline, + IntPtr p_object, out godot_callable r_callable); internal static partial godot_bool godotsharp_callable_get_data_for_marshalling(in godot_callable p_callable, - out IntPtr r_delegate_handle, out IntPtr r_object, out godot_string_name r_name); + out IntPtr r_delegate_handle, out IntPtr r_trampoline, out IntPtr r_object, out godot_string_name r_name); internal static partial godot_variant godotsharp_callable_call(in godot_callable p_callable, godot_variant** p_args, int p_arg_count, out godot_variant_call_error p_call_error); @@ -374,7 +374,7 @@ namespace Godot.NativeInterop public static partial Error godotsharp_array_resize(ref godot_array p_self, int p_new_size); - public static partial Error godotsharp_array_shuffle(ref godot_array p_self); + public static partial void godotsharp_array_shuffle(ref godot_array p_self); public static partial void godotsharp_array_to_string(ref godot_array p_self, out godot_string r_str); diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeVariantPtrArgs.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeVariantPtrArgs.cs index 422df74c23..d8c5d99cb8 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeVariantPtrArgs.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeVariantPtrArgs.cs @@ -8,8 +8,22 @@ namespace Godot.NativeInterop public unsafe ref struct NativeVariantPtrArgs { private godot_variant** _args; + private int _argc; - internal NativeVariantPtrArgs(godot_variant** args) => _args = args; + internal NativeVariantPtrArgs(godot_variant** args, int argc) + { + _args = args; + _argc = argc; + } + + /// <summary> + /// Returns the number of arguments. + /// </summary> + public int Count + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _argc; + } public ref godot_variant this[int index] { diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/VariantConversionCallbacks.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/VariantConversionCallbacks.cs index 9cde62c7c5..4b3db0c01a 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/VariantConversionCallbacks.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/VariantConversionCallbacks.cs @@ -1,10 +1,15 @@ using System; using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; namespace Godot.NativeInterop; +// TODO: Change VariantConversionCallbacks<T>. Store the callback in a static field for quick repeated access, instead of checking every time. internal static unsafe class VariantConversionCallbacks { + internal static System.Collections.Generic.Dictionary<Type, (IntPtr ToVariant, IntPtr FromVariant)> + GenericConversionCallbacks = new(); + [SuppressMessage("ReSharper", "RedundantNameQualifier")] internal static delegate*<in T, godot_variant> GetToVariantCallback<T>() { @@ -502,6 +507,26 @@ internal static unsafe class VariantConversionCallbacks &FromVariant; } + // TODO: + // IsGenericType and GetGenericTypeDefinition don't work in NativeAOT's reflection-free mode. + // We could make the Godot collections implement an interface and use IsAssignableFrom instead. + // Or we could just skip the check and always look for a conversion callback for the type. + if (typeOfT.IsGenericType) + { + var genericTypeDef = typeOfT.GetGenericTypeDefinition(); + + if (genericTypeDef == typeof(Godot.Collections.Dictionary<,>) || + genericTypeDef == typeof(Godot.Collections.Array<>)) + { + RuntimeHelpers.RunClassConstructor(typeOfT.TypeHandle); + + if (GenericConversionCallbacks.TryGetValue(typeOfT, out var genericConversion)) + { + return (delegate*<in T, godot_variant>)genericConversion.ToVariant; + } + } + } + return null; } @@ -1005,6 +1030,26 @@ internal static unsafe class VariantConversionCallbacks &ToVariant; } + // TODO: + // IsGenericType and GetGenericTypeDefinition don't work in NativeAOT's reflection-free mode. + // We could make the Godot collections implement an interface and use IsAssignableFrom instead. + // Or we could just skip the check and always look for a conversion callback for the type. + if (typeOfT.IsGenericType) + { + var genericTypeDef = typeOfT.GetGenericTypeDefinition(); + + if (genericTypeDef == typeof(Godot.Collections.Dictionary<,>) || + genericTypeDef == typeof(Godot.Collections.Array<>)) + { + RuntimeHelpers.RunClassConstructor(typeOfT.TypeHandle); + + if (GenericConversionCallbacks.TryGetValue(typeOfT, out var genericConversion)) + { + return (delegate*<in godot_variant, T>)genericConversion.FromVariant; + } + } + } + // ReSharper restore RedundantCast return null; diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs index 5cb678c280..60ee6eb6f4 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs @@ -202,7 +202,7 @@ namespace Godot // ReSharper disable once VirtualMemberNeverOverridden.Global protected internal virtual void RaiseGodotClassSignalCallbacks(in godot_string_name signal, - NativeVariantPtrArgs args, int argCount) + NativeVariantPtrArgs args) { } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs index 13070c8033..664b2e0f34 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs @@ -292,6 +292,18 @@ namespace Godot } /// <summary> + /// Constructs a <see cref="Plane"/> from a <paramref name="normal"/> vector and + /// a <paramref name="point"/> on the plane. + /// </summary> + /// <param name="normal">The normal of the plane, must be normalized.</param> + /// <param name="point">The point on the plane.</param> + public Plane(Vector3 normal, Vector3 point) + { + _normal = normal; + D = _normal.Dot(point); + } + + /// <summary> /// Constructs a <see cref="Plane"/> from the three points, given in clockwise order. /// </summary> /// <param name="v1">The first point.</param> diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Quaternion.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Quaternion.cs index d459fe8c96..f01f0be985 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Quaternion.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Quaternion.cs @@ -312,7 +312,7 @@ namespace Godot /// the rotation angles in the format (X angle, Y angle, Z angle). /// </summary> /// <returns>The Euler angle representation of this quaternion.</returns> - public Vector3 GetEuler() + public Vector3 GetEuler(EulerOrder order = EulerOrder.Yxz) { #if DEBUG if (!IsNormalized()) @@ -321,7 +321,7 @@ namespace Godot } #endif var basis = new Basis(this); - return basis.GetEuler(); + return basis.GetEuler(order); } /// <summary> @@ -507,35 +507,6 @@ namespace Godot } /// <summary> - /// Constructs a <see cref="Quaternion"/> that will perform a rotation specified by - /// Euler angles (in the YXZ convention: when decomposing, first Z, then X, and Y last), - /// given in the vector format as (X angle, Y angle, Z angle). - /// </summary> - /// <param name="eulerYXZ">Euler angles that the quaternion will be rotated by.</param> - public Quaternion(Vector3 eulerYXZ) - { - real_t halfA1 = eulerYXZ.y * 0.5f; - real_t halfA2 = eulerYXZ.x * 0.5f; - real_t halfA3 = eulerYXZ.z * 0.5f; - - // R = Y(a1).X(a2).Z(a3) convention for Euler angles. - // Conversion to quaternion as listed in https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19770024290.pdf (page A-6) - // a3 is the angle of the first rotation, following the notation in this reference. - - real_t cosA1 = Mathf.Cos(halfA1); - real_t sinA1 = Mathf.Sin(halfA1); - real_t cosA2 = Mathf.Cos(halfA2); - real_t sinA2 = Mathf.Sin(halfA2); - real_t cosA3 = Mathf.Cos(halfA3); - real_t sinA3 = Mathf.Sin(halfA3); - - x = (sinA1 * cosA2 * sinA3) + (cosA1 * sinA2 * cosA3); - y = (sinA1 * cosA2 * cosA3) - (cosA1 * sinA2 * sinA3); - z = (cosA1 * cosA2 * sinA3) - (sinA1 * sinA2 * cosA3); - w = (sinA1 * sinA2 * sinA3) + (cosA1 * cosA2 * cosA3); - } - - /// <summary> /// Constructs a <see cref="Quaternion"/> that will rotate around the given axis /// by the specified angle. The axis must be a normalized vector. /// </summary> @@ -572,6 +543,61 @@ namespace Godot } } + public Quaternion(Vector3 arcFrom, Vector3 arcTo) + { + Vector3 c = arcFrom.Cross(arcTo); + real_t d = arcFrom.Dot(arcTo); + + if (d < -1.0f + Mathf.Epsilon) + { + x = 0f; + y = 1f; + z = 0f; + w = 0f; + } + else + { + real_t s = Mathf.Sqrt((1.0f + d) * 2.0f); + real_t rs = 1.0f / s; + + x = c.x * rs; + y = c.y * rs; + z = c.z * rs; + w = s * 0.5f; + } + } + + /// <summary> + /// Constructs a <see cref="Quaternion"/> that will perform a rotation specified by + /// Euler angles (in the YXZ convention: when decomposing, first Z, then X, and Y last), + /// given in the vector format as (X angle, Y angle, Z angle). + /// </summary> + /// <param name="eulerYXZ">Euler angles that the quaternion will be rotated by.</param> + public static Quaternion FromEuler(Vector3 eulerYXZ) + { + real_t halfA1 = eulerYXZ.y * 0.5f; + real_t halfA2 = eulerYXZ.x * 0.5f; + real_t halfA3 = eulerYXZ.z * 0.5f; + + // R = Y(a1).X(a2).Z(a3) convention for Euler angles. + // Conversion to quaternion as listed in https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19770024290.pdf (page A-6) + // a3 is the angle of the first rotation, following the notation in this reference. + + real_t cosA1 = Mathf.Cos(halfA1); + real_t sinA1 = Mathf.Sin(halfA1); + real_t cosA2 = Mathf.Cos(halfA2); + real_t sinA2 = Mathf.Sin(halfA2); + real_t cosA3 = Mathf.Cos(halfA3); + real_t sinA3 = Mathf.Sin(halfA3); + + return new Quaternion( + (sinA1 * cosA2 * sinA3) + (cosA1 * sinA2 * cosA3), + (sinA1 * cosA2 * cosA3) - (cosA1 * sinA2 * sinA3), + (cosA1 * cosA2 * sinA3) - (sinA1 * sinA2 * cosA3), + (sinA1 * sinA2 * sinA3) + (cosA1 * cosA2 * cosA3) + ); + } + /// <summary> /// Composes these two quaternions by multiplying them together. /// This has the effect of rotating the second quaternion diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs index 44f951e314..d77baab24b 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs @@ -1245,12 +1245,12 @@ namespace Godot /// <summary> /// If the string is a path, this concatenates <paramref name="file"/> /// at the end of the string as a subpath. - /// E.g. <c>"this/is".PlusFile("path") == "this/is/path"</c>. + /// E.g. <c>"this/is".PathJoin("path") == "this/is/path"</c>. /// </summary> /// <param name="instance">The path that will be concatenated.</param> /// <param name="file">File name to concatenate with the path.</param> /// <returns>The concatenated path with the given file name.</returns> - public static string PlusFile(this string instance, string file) + public static string PathJoin(this string instance, string file) { if (instance.Length > 0 && instance[instance.Length - 1] == '/') return instance + file; diff --git a/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj b/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj index 5827d3e591..e3fb254f49 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj +++ b/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj @@ -27,6 +27,8 @@ <PackageLicenseExpression>MIT</PackageLicenseExpression> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> + <IncludeSymbols>true</IncludeSymbols> + <SymbolPackageFormat>snupkg</SymbolPackageFormat> </PropertyGroup> <ItemGroup> <!-- SdkPackageVersions.props for easy access --> @@ -50,6 +52,7 @@ <Compile Include="Core\AABB.cs" /> <Compile Include="Core\Bridge\GodotSerializationInfo.cs" /> <Compile Include="Core\Bridge\MethodInfo.cs" /> + <Compile Include="Core\Callable.generics.cs" /> <Compile Include="Core\CustomGCHandle.cs" /> <Compile Include="Core\Array.cs" /> <Compile Include="Core\Attributes\AssemblyHasScriptsAttribute.cs" /> diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Variant.cs b/modules/mono/glue/GodotSharp/GodotSharp/Variant.cs index 1f37694995..d354509dbf 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Variant.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Variant.cs @@ -766,6 +766,58 @@ public partial struct Variant : IDisposable CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromSignalInfo(from)); [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Variant(byte[] from) => + (Variant)from.AsSpan(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Variant(int[] from) => + (Variant)from.AsSpan(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Variant(long[] from) => + (Variant)from.AsSpan(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Variant(float[] from) => + (Variant)from.AsSpan(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Variant(double[] from) => + (Variant)from.AsSpan(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Variant(string[] from) => + (Variant)from.AsSpan(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Variant(Vector2[] from) => + (Variant)from.AsSpan(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Variant(Vector3[] from) => + (Variant)from.AsSpan(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Variant(Color[] from) => + (Variant)from.AsSpan(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Variant(Godot.Object[] from) => + CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromSystemArrayOfGodotObject(from)); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Variant(StringName[] from) => + (Variant)from.AsSpan(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Variant(NodePath[] from) => + (Variant)from.AsSpan(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Variant(RID[] from) => + (Variant)from.AsSpan(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator Variant(Span<byte> from) => CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromPackedByteArray(from)); @@ -802,10 +854,6 @@ public partial struct Variant : IDisposable CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromPackedColorArray(from)); [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static implicit operator Variant(Godot.Object[] from) => - CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromSystemArrayOfGodotObject(from)); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator Variant(Span<StringName> from) => CreateTakingOwnershipOfDisposableValue(VariantUtils.CreateFromSystemArrayOfStringName(from)); diff --git a/modules/mono/glue/GodotSharp/GodotSharpEditor/GodotSharpEditor.csproj b/modules/mono/glue/GodotSharp/GodotSharpEditor/GodotSharpEditor.csproj index 5d69ad8ec6..8f623625fc 100644 --- a/modules/mono/glue/GodotSharp/GodotSharpEditor/GodotSharpEditor.csproj +++ b/modules/mono/glue/GodotSharp/GodotSharpEditor/GodotSharpEditor.csproj @@ -22,6 +22,8 @@ <PackageLicenseExpression>MIT</PackageLicenseExpression> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> + <IncludeSymbols>true</IncludeSymbols> + <SymbolPackageFormat>snupkg</SymbolPackageFormat> </PropertyGroup> <PropertyGroup> <DefineConstants>$(DefineConstants);GODOT</DefineConstants> diff --git a/modules/mono/glue/runtime_interop.cpp b/modules/mono/glue/runtime_interop.cpp index 276701cdaa..e20a88076a 100644 --- a/modules/mono/glue/runtime_interop.cpp +++ b/modules/mono/glue/runtime_interop.cpp @@ -447,14 +447,16 @@ void godotsharp_packed_string_array_add(PackedStringArray *r_dest, const String r_dest->append(*p_element); } -void godotsharp_callable_new_with_delegate(GCHandleIntPtr p_delegate_handle, Callable *r_callable) { +void godotsharp_callable_new_with_delegate(GCHandleIntPtr p_delegate_handle, void *p_trampoline, + const Object *p_object, Callable *r_callable) { // TODO: Use pooling for ManagedCallable instances. - CallableCustom *managed_callable = memnew(ManagedCallable(p_delegate_handle)); + ObjectID objid = p_object ? p_object->get_instance_id() : ObjectID(); + CallableCustom *managed_callable = memnew(ManagedCallable(p_delegate_handle, p_trampoline, objid)); memnew_placement(r_callable, Callable(managed_callable)); } bool godotsharp_callable_get_data_for_marshalling(const Callable *p_callable, - GCHandleIntPtr *r_delegate_handle, Object **r_object, StringName *r_name) { + GCHandleIntPtr *r_delegate_handle, void **r_trampoline, Object **r_object, StringName *r_name) { if (p_callable->is_custom()) { CallableCustom *custom = p_callable->get_custom(); CallableCustom::CompareEqualFunc compare_equal_func = custom->get_compare_equal_func(); @@ -462,18 +464,21 @@ bool godotsharp_callable_get_data_for_marshalling(const Callable *p_callable, if (compare_equal_func == ManagedCallable::compare_equal_func_ptr) { ManagedCallable *managed_callable = static_cast<ManagedCallable *>(custom); *r_delegate_handle = managed_callable->get_delegate(); + *r_trampoline = managed_callable->get_trampoline(); *r_object = nullptr; memnew_placement(r_name, StringName()); return true; } else if (compare_equal_func == SignalAwaiterCallable::compare_equal_func_ptr) { SignalAwaiterCallable *signal_awaiter_callable = static_cast<SignalAwaiterCallable *>(custom); *r_delegate_handle = { nullptr }; + *r_trampoline = nullptr; *r_object = ObjectDB::get_instance(signal_awaiter_callable->get_object()); memnew_placement(r_name, StringName(signal_awaiter_callable->get_signal())); return true; } else if (compare_equal_func == EventSignalCallable::compare_equal_func_ptr) { EventSignalCallable *event_signal_callable = static_cast<EventSignalCallable *>(custom); *r_delegate_handle = { nullptr }; + *r_trampoline = nullptr; *r_object = ObjectDB::get_instance(event_signal_callable->get_object()); memnew_placement(r_name, StringName(event_signal_callable->get_signal())); return true; @@ -481,11 +486,13 @@ bool godotsharp_callable_get_data_for_marshalling(const Callable *p_callable, // Some other CallableCustom. We only support ManagedCallable. *r_delegate_handle = { nullptr }; + *r_trampoline = nullptr; *r_object = nullptr; memnew_placement(r_name, StringName()); return false; } else { *r_delegate_handle = { nullptr }; + *r_trampoline = nullptr; *r_object = ObjectDB::get_instance(p_callable->get_object_id()); memnew_placement(r_name, StringName(p_callable->get_method())); return true; diff --git a/modules/mono/godotsharp_dirs.cpp b/modules/mono/godotsharp_dirs.cpp index c7e47d2718..d45bf4025f 100644 --- a/modules/mono/godotsharp_dirs.cpp +++ b/modules/mono/godotsharp_dirs.cpp @@ -94,138 +94,63 @@ String _get_mono_user_dir() { class _GodotSharpDirs { public: - String res_data_dir; String res_metadata_dir; - String res_config_dir; - String res_temp_dir; - String res_temp_assemblies_base_dir; String res_temp_assemblies_dir; String mono_user_dir; - String mono_logs_dir; - - String api_assemblies_base_dir; String api_assemblies_dir; #ifdef TOOLS_ENABLED - String mono_solutions_dir; String build_logs_dir; - String data_editor_tools_dir; -#else - // Equivalent of res_assemblies_dir, but in the data directory rather than in 'res://'. - // Only defined on export templates. Used when exporting assemblies outside of PCKs. - String data_game_assemblies_dir; -#endif - - String data_mono_etc_dir; - String data_mono_lib_dir; - -#ifdef WINDOWS_ENABLED - String data_mono_bin_dir; #endif private: _GodotSharpDirs() { - res_data_dir = ProjectSettings::get_singleton()->get_project_data_path().path_join("mono"); + String res_data_dir = ProjectSettings::get_singleton()->get_project_data_path().path_join("mono"); res_metadata_dir = res_data_dir.path_join("metadata"); - res_config_dir = res_data_dir.path_join("etc").path_join("mono"); // TODO use paths from csproj - res_temp_dir = res_data_dir.path_join("temp"); - res_temp_assemblies_base_dir = res_temp_dir.path_join("bin"); - res_temp_assemblies_dir = res_temp_assemblies_base_dir.path_join(_get_expected_build_config()); - - api_assemblies_base_dir = res_data_dir.path_join("assemblies"); + res_temp_assemblies_dir = res_data_dir.path_join("temp").path_join("bin").path_join(_get_expected_build_config()); #ifdef WEB_ENABLED mono_user_dir = "user://"; #else mono_user_dir = _get_mono_user_dir(); #endif - mono_logs_dir = mono_user_dir.path_join("mono_logs"); - -#ifdef TOOLS_ENABLED - mono_solutions_dir = mono_user_dir.path_join("solutions"); - build_logs_dir = mono_user_dir.path_join("build_logs"); - - String base_path = ProjectSettings::get_singleton()->globalize_path("res://"); -#endif String exe_dir = OS::get_singleton()->get_executable_path().get_base_dir(); + String res_dir = OS::get_singleton()->get_bundle_resource_dir(); #ifdef TOOLS_ENABLED - String data_dir_root = exe_dir.path_join("GodotSharp"); data_editor_tools_dir = data_dir_root.path_join("Tools"); - api_assemblies_base_dir = data_dir_root.path_join("Api"); - - String data_mono_root_dir = data_dir_root.path_join("Mono"); - data_mono_etc_dir = data_mono_root_dir.path_join("etc"); - -#ifdef ANDROID_ENABLED - data_mono_lib_dir = gdmono::android::support::get_app_native_lib_dir(); -#else - data_mono_lib_dir = data_mono_root_dir.path_join("lib"); -#endif - -#ifdef WINDOWS_ENABLED - data_mono_bin_dir = data_mono_root_dir.path_join("bin"); -#endif - + String api_assemblies_base_dir = data_dir_root.path_join("Api"); + build_logs_dir = mono_user_dir.path_join("build_logs"); #ifdef MACOS_ENABLED if (!DirAccess::exists(data_editor_tools_dir)) { - data_editor_tools_dir = exe_dir.path_join("../Resources/GodotSharp/Tools"); + data_editor_tools_dir = res_dir.path_join("GodotSharp").path_join("Tools"); } - if (!DirAccess::exists(api_assemblies_base_dir)) { - api_assemblies_base_dir = exe_dir.path_join("../Resources/GodotSharp/Api"); - } - - if (!DirAccess::exists(data_mono_root_dir)) { - data_mono_etc_dir = exe_dir.path_join("../Resources/GodotSharp/Mono/etc"); - data_mono_lib_dir = exe_dir.path_join("../Resources/GodotSharp/Mono/lib"); + api_assemblies_base_dir = res_dir.path_join("GodotSharp").path_join("Api"); } #endif - -#else - - String appname = ProjectSettings::get_singleton()->get("application/config/name"); + api_assemblies_dir = api_assemblies_base_dir.path_join(GDMono::get_expected_api_build_config()); +#else // TOOLS_ENABLED + String arch = Engine::get_singleton()->get_architecture_name(); + String appname = GLOBAL_GET("application/config/name"); String appname_safe = OS::get_singleton()->get_safe_dir_name(appname); - String data_dir_root = exe_dir.path_join("data_" + appname_safe); + String data_dir_root = exe_dir.path_join("data_" + appname_safe + "_" + arch); if (!DirAccess::exists(data_dir_root)) { - data_dir_root = exe_dir.path_join("data_Godot"); + data_dir_root = exe_dir.path_join("data_Godot_" + arch); } - - String data_mono_root_dir = data_dir_root.path_join("Mono"); - data_mono_etc_dir = data_mono_root_dir.path_join("etc"); - -#ifdef ANDROID_ENABLED - data_mono_lib_dir = gdmono::android::support::get_app_native_lib_dir(); -#else - data_mono_lib_dir = data_mono_root_dir.path_join("lib"); - data_game_assemblies_dir = data_dir_root.path_join("Assemblies"); -#endif - -#ifdef WINDOWS_ENABLED - data_mono_bin_dir = data_mono_root_dir.path_join("bin"); -#endif - #ifdef MACOS_ENABLED - if (!DirAccess::exists(data_mono_root_dir)) { - data_mono_etc_dir = exe_dir.path_join("../Resources/GodotSharp/Mono/etc"); - data_mono_lib_dir = exe_dir.path_join("../Resources/GodotSharp/Mono/lib"); + if (!DirAccess::exists(data_dir_root)) { + data_dir_root = res_dir.path_join("data_" + appname_safe + "_" + arch); } - - if (!DirAccess::exists(data_game_assemblies_dir)) { - data_game_assemblies_dir = exe_dir.path_join("../Resources/GodotSharp/Assemblies"); + if (!DirAccess::exists(data_dir_root)) { + data_dir_root = res_dir.path_join("data_Godot_" + arch); } #endif - -#endif - -#ifdef TOOLS_ENABLED - api_assemblies_dir = api_assemblies_base_dir.path_join(GDMono::get_expected_api_build_config()); -#else api_assemblies_dir = data_dir_root; #endif } @@ -237,26 +162,10 @@ public: } }; -String get_res_data_dir() { - return _GodotSharpDirs::get_singleton().res_data_dir; -} - String get_res_metadata_dir() { return _GodotSharpDirs::get_singleton().res_metadata_dir; } -String get_res_config_dir() { - return _GodotSharpDirs::get_singleton().res_config_dir; -} - -String get_res_temp_dir() { - return _GodotSharpDirs::get_singleton().res_temp_dir; -} - -String get_res_temp_assemblies_base_dir() { - return _GodotSharpDirs::get_singleton().res_temp_assemblies_base_dir; -} - String get_res_temp_assemblies_dir() { return _GodotSharpDirs::get_singleton().res_temp_assemblies_dir; } @@ -265,23 +174,11 @@ String get_api_assemblies_dir() { return _GodotSharpDirs::get_singleton().api_assemblies_dir; } -String get_api_assemblies_base_dir() { - return _GodotSharpDirs::get_singleton().api_assemblies_base_dir; -} - String get_mono_user_dir() { return _GodotSharpDirs::get_singleton().mono_user_dir; } -String get_mono_logs_dir() { - return _GodotSharpDirs::get_singleton().mono_logs_dir; -} - #ifdef TOOLS_ENABLED -String get_mono_solutions_dir() { - return _GodotSharpDirs::get_singleton().mono_solutions_dir; -} - String get_build_logs_dir() { return _GodotSharpDirs::get_singleton().build_logs_dir; } @@ -289,23 +186,6 @@ String get_build_logs_dir() { String get_data_editor_tools_dir() { return _GodotSharpDirs::get_singleton().data_editor_tools_dir; } -#else -String get_data_game_assemblies_dir() { - return _GodotSharpDirs::get_singleton().data_game_assemblies_dir; -} #endif -String get_data_mono_etc_dir() { - return _GodotSharpDirs::get_singleton().data_mono_etc_dir; -} - -String get_data_mono_lib_dir() { - return _GodotSharpDirs::get_singleton().data_mono_lib_dir; -} - -#ifdef WINDOWS_ENABLED -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 03e62ffd82..cdfb8e4787 100644 --- a/modules/mono/godotsharp_dirs.h +++ b/modules/mono/godotsharp_dirs.h @@ -35,34 +35,18 @@ namespace GodotSharpDirs { -String get_res_data_dir(); String get_res_metadata_dir(); -String get_res_config_dir(); -String get_res_temp_dir(); -String get_res_temp_assemblies_base_dir(); String get_res_temp_assemblies_dir(); String get_api_assemblies_dir(); -String get_api_assemblies_base_dir(); String get_mono_user_dir(); -String get_mono_logs_dir(); #ifdef TOOLS_ENABLED -String get_mono_solutions_dir(); String get_build_logs_dir(); - String get_data_editor_tools_dir(); -#else -String get_data_game_assemblies_dir(); #endif -String get_data_mono_etc_dir(); -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/managed_callable.cpp b/modules/mono/managed_callable.cpp index 9305dc645a..28edc41d98 100644 --- a/modules/mono/managed_callable.cpp +++ b/modules/mono/managed_callable.cpp @@ -79,7 +79,9 @@ CallableCustom::CompareLessFunc ManagedCallable::get_compare_less_func() const { } ObjectID ManagedCallable::get_object() const { - // TODO: If the delegate target extends Godot.Object, use that instead! + if (object_id != ObjectID()) { + return object_id; + } return CSharpLanguage::get_singleton()->get_managed_callable_middleman()->get_instance_id(); } @@ -90,7 +92,7 @@ void ManagedCallable::call(const Variant **p_arguments, int p_argcount, Variant ERR_FAIL_COND(delegate_handle.value == nullptr); GDMonoCache::managed_callbacks.DelegateUtils_InvokeWithVariantArgs( - delegate_handle, p_arguments, p_argcount, &r_return_value); + delegate_handle, trampoline, p_arguments, p_argcount, &r_return_value); r_call_error.error = Callable::CallError::CALL_OK; } @@ -104,7 +106,8 @@ void ManagedCallable::release_delegate_handle() { // Why you do this clang-format... /* clang-format off */ -ManagedCallable::ManagedCallable(GCHandleIntPtr p_delegate_handle) : delegate_handle(p_delegate_handle) { +ManagedCallable::ManagedCallable(GCHandleIntPtr p_delegate_handle, void *p_trampoline, ObjectID p_object_id) : + delegate_handle(p_delegate_handle), trampoline(p_trampoline), object_id(p_object_id) { #ifdef GD_MONO_HOT_RELOAD { MutexLock lock(instances_mutex); diff --git a/modules/mono/managed_callable.h b/modules/mono/managed_callable.h index aa3344f4d5..b3a137dedf 100644 --- a/modules/mono/managed_callable.h +++ b/modules/mono/managed_callable.h @@ -40,6 +40,8 @@ class ManagedCallable : public CallableCustom { friend class CSharpLanguage; GCHandleIntPtr delegate_handle; + void *trampoline = nullptr; + ObjectID object_id; #ifdef GD_MONO_HOT_RELOAD SelfList<ManagedCallable> self_instance = this; @@ -57,6 +59,7 @@ public: void call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const override; _FORCE_INLINE_ GCHandleIntPtr get_delegate() const { return delegate_handle; } + _FORCE_INLINE_ void *get_trampoline() const { return trampoline; } static bool compare_equal(const CallableCustom *p_a, const CallableCustom *p_b); static bool compare_less(const CallableCustom *p_a, const CallableCustom *p_b); @@ -66,7 +69,7 @@ public: void release_delegate_handle(); - ManagedCallable(GCHandleIntPtr p_delegate_handle); + ManagedCallable(GCHandleIntPtr p_delegate_handle, void *p_trampoline, ObjectID p_object_id); ~ManagedCallable(); }; diff --git a/modules/mono/mono_gd/gd_mono_cache.h b/modules/mono/mono_gd/gd_mono_cache.h index 13b599fe55..9c26fa2b0a 100644 --- a/modules/mono/mono_gd/gd_mono_cache.h +++ b/modules/mono/mono_gd/gd_mono_cache.h @@ -74,7 +74,7 @@ struct ManagedCallbacks { using Callback_ScriptManagerBridge_GetPropertyDefaultValues_Add = void(GD_CLR_STDCALL *)(CSharpScript *p_script, void *p_def_vals, int32_t p_count); using FuncSignalAwaiter_SignalCallback = void(GD_CLR_STDCALL *)(GCHandleIntPtr, const Variant **, int32_t, bool *); - using FuncDelegateUtils_InvokeWithVariantArgs = void(GD_CLR_STDCALL *)(GCHandleIntPtr, const Variant **, uint32_t, const Variant *); + using FuncDelegateUtils_InvokeWithVariantArgs = void(GD_CLR_STDCALL *)(GCHandleIntPtr, void *, const Variant **, int32_t, const Variant *); using FuncDelegateUtils_DelegateEquals = bool(GD_CLR_STDCALL *)(GCHandleIntPtr, GCHandleIntPtr); using FuncDelegateUtils_TrySerializeDelegateWithGCHandle = bool(GD_CLR_STDCALL *)(GCHandleIntPtr, const Array *); using FuncDelegateUtils_TryDeserializeDelegateWithGCHandle = bool(GD_CLR_STDCALL *)(const Array *, GCHandleIntPtr *); diff --git a/modules/mono/utils/macos_utils.h b/modules/mono/utils/macos_utils.h index ca4957f5a7..0b74114685 100644 --- a/modules/mono/utils/macos_utils.h +++ b/modules/mono/utils/macos_utils.h @@ -28,13 +28,13 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "core/string/ustring.h" - #ifndef MONO_MACOS_UTILS_H #define MONO_MACOS_UTILS_H #ifdef MACOS_ENABLED +#include "core/string/ustring.h" + bool macos_is_app_bundle_installed(const String &p_bundle_id); #endif diff --git a/modules/multiplayer/SCsub b/modules/multiplayer/SCsub index ff33655537..e89038c3e0 100644 --- a/modules/multiplayer/SCsub +++ b/modules/multiplayer/SCsub @@ -8,7 +8,7 @@ env_mp = env_modules.Clone() module_obj = [] env_mp.add_source_files(module_obj, "*.cpp") -if env["tools"]: +if env.editor_build: env_mp.add_source_files(module_obj, "editor/*.cpp") env.modules_sources += module_obj diff --git a/modules/multiplayer/doc_classes/MultiplayerSpawner.xml b/modules/multiplayer/doc_classes/MultiplayerSpawner.xml index c0265c9161..a3ca2d6486 100644 --- a/modules/multiplayer/doc_classes/MultiplayerSpawner.xml +++ b/modules/multiplayer/doc_classes/MultiplayerSpawner.xml @@ -6,7 +6,6 @@ <description> Spawnable scenes can be configured in the editor or through code (see [method add_spawnable_scene]). Also supports custom node spawns through [method spawn], calling [method _spawn_custom] on all peers. - Internally, [MultiplayerSpawner] uses [method MultiplayerAPI.object_configuration_add] to notify spawns passing the spawned node as the [code]object[/code] and itself as the [code]configuration[/code], and [method MultiplayerAPI.object_configuration_remove] to notify despawns in a similar way. </description> <tutorials> @@ -17,8 +16,7 @@ <param index="0" name="data" type="Variant" /> <description> Method called on all peers when a custom spawn was requested by the authority using [method spawn]. Should return a [Node] that is not in the scene tree. - - [b]Note:[/b] Spawned nodes should [b]not[/b] be added to the scene with `add_child`. This is done automatically. + [b]Note:[/b] Spawned nodes should [b]not[/b] be added to the scene with [method Node.add_child]. This is done automatically. </description> </method> <method name="add_spawnable_scene"> @@ -52,7 +50,6 @@ <param index="0" name="data" type="Variant" default="null" /> <description> Requests a custom spawn, with [code]data[/code] passed to [method _spawn_custom] on all peers. Returns the locally spawned node instance already inside the scene tree, and added as a child of the node pointed by [member spawn_path]. - [b]Note:[/b] Spawnable scenes are spawned automatically. [method spawn] is only needed for custom spawns. </description> </method> @@ -60,7 +57,6 @@ <members> <member name="spawn_limit" type="int" setter="set_spawn_limit" getter="get_spawn_limit" default="0"> Maximum nodes that is allowed to be spawned by this spawner. Includes both spawnable scenes and custom spawns. - When set to [code]0[/code] (the default), there is no limit. </member> <member name="spawn_path" type="NodePath" setter="set_spawn_path" getter="get_spawn_path" default="NodePath("")"> diff --git a/modules/multiplayer/doc_classes/MultiplayerSynchronizer.xml b/modules/multiplayer/doc_classes/MultiplayerSynchronizer.xml index 9a4d755d64..7ed6255a62 100644 --- a/modules/multiplayer/doc_classes/MultiplayerSynchronizer.xml +++ b/modules/multiplayer/doc_classes/MultiplayerSynchronizer.xml @@ -5,10 +5,8 @@ </brief_description> <description> By default, [MultiplayerSynchronizer] synchronizes configured properties to all peers. - Visiblity can be handled directly with [method set_visibility_for] or as-needed with [method add_visibility_filter] and [method update_visibility]. - + Visibility can be handled directly with [method set_visibility_for] or as-needed with [method add_visibility_filter] and [method update_visibility]. [MultiplayerSpawner]s will handle nodes according to visibility of synchronizers as long as the node at [member root_path] was spawned by one. - Internally, [MultiplayerSynchronizer] uses [method MultiplayerAPI.object_configuration_add] to notify synchronization start passing the [Node] at [member root_path] as the [code]object[/code] and itself as the [code]configuration[/code], and uses [method MultiplayerAPI.object_configuration_remove] to notify synchronization end in a similar way. </description> <tutorials> @@ -19,7 +17,6 @@ <param index="0" name="filter" type="Callable" /> <description> Adds a peer visibility filter for this synchronizer. - [code]filter[/code] should take a peer id [int] and return a [bool]. </description> </method> @@ -34,7 +31,7 @@ <return type="void" /> <param index="0" name="filter" type="Callable" /> <description> - Removes a peer visiblity filter from this synchronizer. + Removes a peer visibility filter from this synchronizer. </description> </method> <method name="set_visibility_for"> diff --git a/modules/multiplayer/doc_classes/SceneMultiplayer.xml b/modules/multiplayer/doc_classes/SceneMultiplayer.xml index 62bb396d15..e4e2b4f631 100644 --- a/modules/multiplayer/doc_classes/SceneMultiplayer.xml +++ b/modules/multiplayer/doc_classes/SceneMultiplayer.xml @@ -19,6 +19,35 @@ Clears the current SceneMultiplayer network state (you shouldn't call this unless you know what you are doing). </description> </method> + <method name="complete_auth"> + <return type="int" enum="Error" /> + <param index="0" name="id" type="int" /> + <description> + Mark the authentication step as completed for the remote peer identified by [param id]. The [signal MultiplayerAPI.peer_connected] signal will be emitted for this peer once the remote side also completes the authentication. No further authentication messages are expected to be received from this peer. + If a peer disconnects before completing authentication, either due to a network issue, the [member auth_timeout] expiring, or manually calling [method disconnect_peer], the [signal peer_authentication_failed] signal will be emitted instead of [signal MultiplayerAPI.peer_disconnected]. + </description> + </method> + <method name="disconnect_peer"> + <return type="void" /> + <param index="0" name="id" type="int" /> + <description> + Disconnects the peer identified by [param id], removing it from the list of connected peers, and closing the underlying connection with it. + </description> + </method> + <method name="get_authenticating_peers"> + <return type="PackedInt32Array" /> + <description> + Returns the IDs of the peers currently trying to authenticate with this [MultiplayerAPI]. + </description> + </method> + <method name="send_auth"> + <return type="int" enum="Error" /> + <param index="0" name="id" type="int" /> + <param index="1" name="data" type="PackedByteArray" /> + <description> + Sends the specified [param data] to the remote peer identified by [param id] as part of an authentication message. This can be used to authenticate peers, and control when [signal MultiplayerAPI.peer_connected] is emitted (and the remote peer accepted as one of the connected peers). + </description> + </method> <method name="send_bytes"> <return type="int" enum="Error" /> <param index="0" name="bytes" type="PackedByteArray" /> @@ -35,6 +64,12 @@ If [code]true[/code], the MultiplayerAPI will allow encoding and decoding of object during RPCs. [b]Warning:[/b] Deserialized objects can contain code which gets executed. Do not use this option if the serialized object comes from untrusted sources to avoid potential security threat such as remote code execution. </member> + <member name="auth_callback" type="Callable" setter="set_auth_callback" getter="get_auth_callback"> + The callback to execute when when receiving authentication data sent via [method send_auth]. If the [Callable] is empty (default), peers will be automatically accepted as soon as they connect. + </member> + <member name="auth_timeout" type="float" setter="set_auth_timeout" getter="get_auth_timeout" default="3.0"> + If set to a value greater than [code]0.0[/code], the maximum amount of time peers can stay in the authenticating state, after which the authentication will automatically fail. See the [signal peer_authenticating] and [signal peer_authentication_failed] signals. + </member> <member name="refuse_new_connections" type="bool" setter="set_refuse_new_connections" getter="is_refusing_new_connections" default="false"> If [code]true[/code], the MultiplayerAPI's [member MultiplayerAPI.multiplayer_peer] refuses new incoming connections. </member> @@ -42,8 +77,24 @@ The root path to use for RPCs and replication. Instead of an absolute path, a relative path will be used to find the node upon which the RPC should be executed. This effectively allows to have different branches of the scene tree to be managed by different MultiplayerAPI, allowing for example to run both client and server in the same scene. </member> + <member name="server_relay" type="bool" setter="set_server_relay_enabled" getter="is_server_relay_enabled" default="true"> + Enable or disable the server feature that notifies clients of other peers' connection/disconnection, and relays messages between them. When this option is [code]false[/code], clients won't be automatically notified of other peers and won't be able to send them packets through the server. + [b]Note:[/b] Support for this feature may depend on the current [MultiplayerPeer] configuration. See [method MultiplayerPeer.is_server_relay_supported]. + </member> </members> <signals> + <signal name="peer_authenticating"> + <param index="0" name="id" type="int" /> + <description> + Emitted when this MultiplayerAPI's [member MultiplayerAPI.multiplayer_peer] connects to a new peer and a valid [member auth_callback] is set. In this case, the [signal MultiplayerAPI.peer_connected] will not be emitted until [method complete_auth] is called with given peer [param id]. While in this state, the peer will not be included in the list returned by [method MultiplayerAPI.get_peers] (but in the one returned by [method get_authenticating_peers]), and only authentication data will be sent or received. See [method send_auth] for sending authentication data. + </description> + </signal> + <signal name="peer_authentication_failed"> + <param index="0" name="id" type="int" /> + <description> + Emitted when this MultiplayerAPI's [member MultiplayerAPI.multiplayer_peer] disconnects from a peer for which authentication had not yet completed. See [signal peer_authenticating]. + </description> + </signal> <signal name="peer_packet"> <param index="0" name="id" type="int" /> <param index="1" name="packet" type="PackedByteArray" /> diff --git a/modules/multiplayer/editor/editor_network_profiler.cpp b/modules/multiplayer/editor/editor_network_profiler.cpp new file mode 100644 index 0000000000..a7e5b80b66 --- /dev/null +++ b/modules/multiplayer/editor/editor_network_profiler.cpp @@ -0,0 +1,197 @@ +/*************************************************************************/ +/* editor_network_profiler.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 "editor_network_profiler.h" + +#include "core/os/os.h" +#include "editor/editor_scale.h" +#include "editor/editor_settings.h" + +void EditorNetworkProfiler::_bind_methods() { + ADD_SIGNAL(MethodInfo("enable_profiling", PropertyInfo(Variant::BOOL, "enable"))); +} + +void EditorNetworkProfiler::_notification(int p_what) { + switch (p_what) { + case NOTIFICATION_ENTER_TREE: + case NOTIFICATION_THEME_CHANGED: { + activate->set_icon(get_theme_icon(SNAME("Play"), SNAME("EditorIcons"))); + clear_button->set_icon(get_theme_icon(SNAME("Clear"), SNAME("EditorIcons"))); + incoming_bandwidth_text->set_right_icon(get_theme_icon(SNAME("ArrowDown"), SNAME("EditorIcons"))); + outgoing_bandwidth_text->set_right_icon(get_theme_icon(SNAME("ArrowUp"), SNAME("EditorIcons"))); + + // This needs to be done here to set the faded color when the profiler is first opened + incoming_bandwidth_text->add_theme_color_override("font_uneditable_color", get_theme_color(SNAME("font_color"), SNAME("Editor")) * Color(1, 1, 1, 0.5)); + outgoing_bandwidth_text->add_theme_color_override("font_uneditable_color", get_theme_color(SNAME("font_color"), SNAME("Editor")) * Color(1, 1, 1, 0.5)); + } break; + } +} + +void EditorNetworkProfiler::_update_frame() { + counters_display->clear(); + + TreeItem *root = counters_display->create_item(); + + for (const KeyValue<ObjectID, RPCNodeInfo> &E : nodes_data) { + TreeItem *node = counters_display->create_item(root); + + for (int j = 0; j < counters_display->get_columns(); ++j) { + node->set_text_alignment(j, j > 0 ? HORIZONTAL_ALIGNMENT_RIGHT : HORIZONTAL_ALIGNMENT_LEFT); + } + + node->set_text(0, E.value.node_path); + node->set_text(1, E.value.incoming_rpc == 0 ? "-" : itos(E.value.incoming_rpc)); + node->set_text(2, E.value.outgoing_rpc == 0 ? "-" : itos(E.value.outgoing_rpc)); + } +} + +void EditorNetworkProfiler::_activate_pressed() { + if (activate->is_pressed()) { + activate->set_icon(get_theme_icon(SNAME("Stop"), SNAME("EditorIcons"))); + activate->set_text(TTR("Stop")); + } else { + activate->set_icon(get_theme_icon(SNAME("Play"), SNAME("EditorIcons"))); + activate->set_text(TTR("Start")); + } + emit_signal(SNAME("enable_profiling"), activate->is_pressed()); +} + +void EditorNetworkProfiler::_clear_pressed() { + nodes_data.clear(); + set_bandwidth(0, 0); + if (frame_delay->is_stopped()) { + frame_delay->set_wait_time(0.1); + frame_delay->start(); + } +} + +void EditorNetworkProfiler::add_node_frame_data(const RPCNodeInfo p_frame) { + if (!nodes_data.has(p_frame.node)) { + nodes_data.insert(p_frame.node, p_frame); + } else { + nodes_data[p_frame.node].incoming_rpc += p_frame.incoming_rpc; + nodes_data[p_frame.node].outgoing_rpc += p_frame.outgoing_rpc; + } + + if (frame_delay->is_stopped()) { + frame_delay->set_wait_time(0.1); + frame_delay->start(); + } +} + +void EditorNetworkProfiler::set_bandwidth(int p_incoming, int p_outgoing) { + incoming_bandwidth_text->set_text(vformat(TTR("%s/s"), String::humanize_size(p_incoming))); + outgoing_bandwidth_text->set_text(vformat(TTR("%s/s"), String::humanize_size(p_outgoing))); + + // Make labels more prominent when the bandwidth is greater than 0 to attract user attention + incoming_bandwidth_text->add_theme_color_override( + "font_uneditable_color", + get_theme_color(SNAME("font_color"), SNAME("Editor")) * Color(1, 1, 1, p_incoming > 0 ? 1 : 0.5)); + outgoing_bandwidth_text->add_theme_color_override( + "font_uneditable_color", + get_theme_color(SNAME("font_color"), SNAME("Editor")) * Color(1, 1, 1, p_outgoing > 0 ? 1 : 0.5)); +} + +bool EditorNetworkProfiler::is_profiling() { + return activate->is_pressed(); +} + +EditorNetworkProfiler::EditorNetworkProfiler() { + HBoxContainer *hb = memnew(HBoxContainer); + hb->add_theme_constant_override("separation", 8 * EDSCALE); + add_child(hb); + + activate = memnew(Button); + activate->set_toggle_mode(true); + activate->set_text(TTR("Start")); + activate->connect("pressed", callable_mp(this, &EditorNetworkProfiler::_activate_pressed)); + hb->add_child(activate); + + clear_button = memnew(Button); + clear_button->set_text(TTR("Clear")); + clear_button->connect("pressed", callable_mp(this, &EditorNetworkProfiler::_clear_pressed)); + hb->add_child(clear_button); + + hb->add_spacer(); + + Label *lb = memnew(Label); + lb->set_text(TTR("Down")); + hb->add_child(lb); + + incoming_bandwidth_text = memnew(LineEdit); + incoming_bandwidth_text->set_editable(false); + incoming_bandwidth_text->set_custom_minimum_size(Size2(120, 0) * EDSCALE); + incoming_bandwidth_text->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_RIGHT); + hb->add_child(incoming_bandwidth_text); + + Control *down_up_spacer = memnew(Control); + down_up_spacer->set_custom_minimum_size(Size2(30, 0) * EDSCALE); + hb->add_child(down_up_spacer); + + lb = memnew(Label); + lb->set_text(TTR("Up")); + hb->add_child(lb); + + outgoing_bandwidth_text = memnew(LineEdit); + outgoing_bandwidth_text->set_editable(false); + outgoing_bandwidth_text->set_custom_minimum_size(Size2(120, 0) * EDSCALE); + outgoing_bandwidth_text->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_RIGHT); + hb->add_child(outgoing_bandwidth_text); + + // Set initial texts in the incoming/outgoing bandwidth labels + set_bandwidth(0, 0); + + counters_display = memnew(Tree); + counters_display->set_custom_minimum_size(Size2(300, 0) * EDSCALE); + counters_display->set_v_size_flags(SIZE_EXPAND_FILL); + counters_display->set_hide_folding(true); + counters_display->set_hide_root(true); + counters_display->set_columns(3); + counters_display->set_column_titles_visible(true); + counters_display->set_column_title(0, TTR("Node")); + counters_display->set_column_expand(0, true); + counters_display->set_column_clip_content(0, true); + counters_display->set_column_custom_minimum_width(0, 60 * EDSCALE); + counters_display->set_column_title(1, TTR("Incoming RPC")); + counters_display->set_column_expand(1, false); + counters_display->set_column_clip_content(1, true); + counters_display->set_column_custom_minimum_width(1, 120 * EDSCALE); + counters_display->set_column_title(2, TTR("Outgoing RPC")); + counters_display->set_column_expand(2, false); + counters_display->set_column_clip_content(2, true); + counters_display->set_column_custom_minimum_width(2, 120 * EDSCALE); + add_child(counters_display); + + frame_delay = memnew(Timer); + frame_delay->set_wait_time(0.1); + frame_delay->set_one_shot(true); + add_child(frame_delay); + frame_delay->connect("timeout", callable_mp(this, &EditorNetworkProfiler::_update_frame)); +} diff --git a/modules/websocket/websocket_client.h b/modules/multiplayer/editor/editor_network_profiler.h index e747aee4e4..98d12e3c0a 100644 --- a/modules/websocket/websocket_client.h +++ b/modules/multiplayer/editor/editor_network_profiler.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* websocket_client.h */ +/* editor_network_profiler.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,48 +28,49 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef WEBSOCKET_CLIENT_H -#define WEBSOCKET_CLIENT_H +#ifndef EDITOR_NETWORK_PROFILER_H +#define EDITOR_NETWORK_PROFILER_H -#include "core/crypto/crypto.h" -#include "core/error/error_list.h" -#include "websocket_multiplayer_peer.h" -#include "websocket_peer.h" +#include "scene/debugger/scene_debugger.h" +#include "scene/gui/box_container.h" +#include "scene/gui/button.h" +#include "scene/gui/label.h" +#include "scene/gui/split_container.h" +#include "scene/gui/tree.h" -class WebSocketClient : public WebSocketMultiplayerPeer { - GDCLASS(WebSocketClient, WebSocketMultiplayerPeer); - GDCICLASS(WebSocketClient); +#include "../multiplayer_debugger.h" -protected: - Ref<WebSocketPeer> _peer; - bool verify_tls = true; - Ref<X509Certificate> tls_cert; +class EditorNetworkProfiler : public VBoxContainer { + GDCLASS(EditorNetworkProfiler, VBoxContainer) - static void _bind_methods(); +private: + using RPCNodeInfo = MultiplayerDebugger::RPCNodeInfo; -public: - Error connect_to_url(String p_url, const Vector<String> p_protocols = Vector<String>(), bool gd_mp_api = false, const Vector<String> p_custom_headers = Vector<String>()); + Button *activate = nullptr; + Button *clear_button = nullptr; + Tree *counters_display = nullptr; + LineEdit *incoming_bandwidth_text = nullptr; + LineEdit *outgoing_bandwidth_text = nullptr; + + Timer *frame_delay = nullptr; - void set_verify_tls_enabled(bool p_verify_tls); - bool is_verify_tls_enabled() const; - Ref<X509Certificate> get_trusted_tls_certificate() const; - void set_trusted_tls_certificate(Ref<X509Certificate> p_cert); + HashMap<ObjectID, RPCNodeInfo> nodes_data; - virtual Error connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_tls, const Vector<String> p_protocol = Vector<String>(), const Vector<String> p_custom_headers = Vector<String>()) = 0; - virtual void disconnect_from_host(int p_code = 1000, String p_reason = "") = 0; - virtual IPAddress get_connected_host() const = 0; - virtual uint16_t get_connected_port() const = 0; + void _update_frame(); - virtual bool is_server() const override; + void _activate_pressed(); + void _clear_pressed(); - void _on_peer_packet(); - void _on_connect(String p_protocol); - void _on_close_request(int p_code, String p_reason); - void _on_disconnect(bool p_was_clean); - void _on_error(); +protected: + void _notification(int p_what); + static void _bind_methods(); + +public: + void add_node_frame_data(const RPCNodeInfo p_frame); + void set_bandwidth(int p_incoming, int p_outgoing); + bool is_profiling(); - WebSocketClient(); - ~WebSocketClient(); + EditorNetworkProfiler(); }; -#endif // WEBSOCKET_CLIENT_H +#endif // EDITOR_NETWORK_PROFILER_H diff --git a/modules/multiplayer/editor/multiplayer_editor_plugin.cpp b/modules/multiplayer/editor/multiplayer_editor_plugin.cpp new file mode 100644 index 0000000000..00b1537827 --- /dev/null +++ b/modules/multiplayer/editor/multiplayer_editor_plugin.cpp @@ -0,0 +1,140 @@ +/*************************************************************************/ +/* multiplayer_editor_plugin.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 "multiplayer_editor_plugin.h" + +#include "../multiplayer_synchronizer.h" +#include "editor_network_profiler.h" +#include "replication_editor.h" + +#include "editor/editor_node.h" + +bool MultiplayerEditorDebugger::has_capture(const String &p_capture) const { + return p_capture == "multiplayer"; +} + +bool MultiplayerEditorDebugger::capture(const String &p_message, const Array &p_data, int p_session) { + ERR_FAIL_COND_V(!profilers.has(p_session), false); + EditorNetworkProfiler *profiler = profilers[p_session]; + if (p_message == "multiplayer:rpc") { + MultiplayerDebugger::RPCFrame frame; + frame.deserialize(p_data); + for (int i = 0; i < frame.infos.size(); i++) { + profiler->add_node_frame_data(frame.infos[i]); + } + return true; + + } else if (p_message == "multiplayer:bandwidth") { + ERR_FAIL_COND_V(p_data.size() < 2, false); + profiler->set_bandwidth(p_data[0], p_data[1]); + return true; + } + return false; +} + +void MultiplayerEditorDebugger::_profiler_activate(bool p_enable, int p_session_id) { + Ref<EditorDebuggerSession> session = get_session(p_session_id); + ERR_FAIL_COND(session.is_null()); + session->toggle_profiler("multiplayer", p_enable); + session->toggle_profiler("rpc", p_enable); +} + +void MultiplayerEditorDebugger::setup_session(int p_session_id) { + Ref<EditorDebuggerSession> session = get_session(p_session_id); + ERR_FAIL_COND(session.is_null()); + EditorNetworkProfiler *profiler = memnew(EditorNetworkProfiler); + profiler->connect("enable_profiling", callable_mp(this, &MultiplayerEditorDebugger::_profiler_activate).bind(p_session_id)); + profiler->set_name(TTR("Network Profiler")); + session->add_session_tab(profiler); + profilers[p_session_id] = profiler; +} + +MultiplayerEditorPlugin::MultiplayerEditorPlugin() { + repl_editor = memnew(ReplicationEditor); + button = EditorNode::get_singleton()->add_bottom_panel_item(TTR("Replication"), repl_editor); + button->hide(); + repl_editor->get_pin()->connect("pressed", callable_mp(this, &MultiplayerEditorPlugin::_pinned)); + debugger.instantiate(); +} + +MultiplayerEditorPlugin::~MultiplayerEditorPlugin() { +} + +void MultiplayerEditorPlugin::_notification(int p_what) { + switch (p_what) { + case NOTIFICATION_ENTER_TREE: { + get_tree()->connect("node_removed", callable_mp(this, &MultiplayerEditorPlugin::_node_removed)); + add_debugger_plugin(debugger); + } break; + case NOTIFICATION_EXIT_TREE: { + remove_debugger_plugin(debugger); + } + } +} + +void MultiplayerEditorPlugin::_node_removed(Node *p_node) { + if (p_node && p_node == repl_editor->get_current()) { + repl_editor->edit(nullptr); + if (repl_editor->is_visible_in_tree()) { + EditorNode::get_singleton()->hide_bottom_panel(); + } + button->hide(); + repl_editor->get_pin()->set_pressed(false); + } +} + +void MultiplayerEditorPlugin::_pinned() { + if (!repl_editor->get_pin()->is_pressed()) { + if (repl_editor->is_visible_in_tree()) { + EditorNode::get_singleton()->hide_bottom_panel(); + } + button->hide(); + } +} + +void MultiplayerEditorPlugin::edit(Object *p_object) { + repl_editor->edit(Object::cast_to<MultiplayerSynchronizer>(p_object)); +} + +bool MultiplayerEditorPlugin::handles(Object *p_object) const { + return p_object->is_class("MultiplayerSynchronizer"); +} + +void MultiplayerEditorPlugin::make_visible(bool p_visible) { + if (p_visible) { + button->show(); + EditorNode::get_singleton()->make_bottom_panel_item_visible(repl_editor); + } else if (!repl_editor->get_pin()->is_pressed()) { + if (repl_editor->is_visible_in_tree()) { + EditorNode::get_singleton()->hide_bottom_panel(); + } + button->hide(); + } +} diff --git a/modules/websocket/emws_client.h b/modules/multiplayer/editor/multiplayer_editor_plugin.h index cdcec31e19..6d1514cdb1 100644 --- a/modules/websocket/emws_client.h +++ b/modules/multiplayer/editor/multiplayer_editor_plugin.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* emws_client.h */ +/* multiplayer_editor_plugin.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,44 +28,54 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef EMWS_CLIENT_H -#define EMWS_CLIENT_H +#ifndef MULTIPLAYER_EDITOR_PLUGIN_H +#define MULTIPLAYER_EDITOR_PLUGIN_H -#ifdef WEB_ENABLED +#include "editor/editor_plugin.h" -#include "core/error/error_list.h" -#include "emws_peer.h" -#include "websocket_client.h" +#include "editor/plugins/editor_debugger_plugin.h" -class EMWSClient : public WebSocketClient { - GDCIIMPL(EMWSClient, WebSocketClient); +class EditorNetworkProfiler; +class MultiplayerEditorDebugger : public EditorDebuggerPlugin { + GDCLASS(MultiplayerEditorDebugger, EditorDebuggerPlugin); private: - int _js_id = 0; - bool _is_connecting = false; - int _in_buf_size = DEF_BUF_SHIFT; - int _in_pkt_size = DEF_PKT_SHIFT; - int _out_buf_size = DEF_BUF_SHIFT; + HashMap<int, EditorNetworkProfiler *> profilers; - static void _esws_on_connect(void *obj, char *proto); - static void _esws_on_message(void *obj, const uint8_t *p_data, int p_data_size, int p_is_string); - static void _esws_on_error(void *obj); - static void _esws_on_close(void *obj, int code, const char *reason, int was_clean); + void _profiler_activate(bool p_enable, int p_session_id); public: - Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) override; - Error connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_tls, const Vector<String> p_protocol = Vector<String>(), const Vector<String> p_custom_headers = Vector<String>()) override; - Ref<WebSocketPeer> get_peer(int p_peer_id) const override; - void disconnect_from_host(int p_code = 1000, String p_reason = "") override; - IPAddress get_connected_host() const override; - uint16_t get_connected_port() const override; - virtual ConnectionStatus get_connection_status() const override; - int get_max_packet_size() const override; - virtual void poll() override; - EMWSClient(); - ~EMWSClient(); + virtual bool has_capture(const String &p_capture) const override; + virtual bool capture(const String &p_message, const Array &p_data, int p_index) override; + virtual void setup_session(int p_session_id) override; + + MultiplayerEditorDebugger() {} }; -#endif // WEB_ENABLED +class ReplicationEditor; + +class MultiplayerEditorPlugin : public EditorPlugin { + GDCLASS(MultiplayerEditorPlugin, EditorPlugin); + +private: + Button *button = nullptr; + ReplicationEditor *repl_editor = nullptr; + Ref<MultiplayerEditorDebugger> debugger; + + void _node_removed(Node *p_node); + + void _pinned(); + +protected: + void _notification(int p_what); + +public: + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; + + MultiplayerEditorPlugin(); + ~MultiplayerEditorPlugin(); +}; -#endif // EMWS_CLIENT_H +#endif // MULTIPLAYER_EDITOR_PLUGIN_H diff --git a/modules/multiplayer/editor/replication_editor_plugin.cpp b/modules/multiplayer/editor/replication_editor.cpp index f045018f25..4ba9cd14f0 100644 --- a/modules/multiplayer/editor/replication_editor_plugin.cpp +++ b/modules/multiplayer/editor/replication_editor.cpp @@ -1,5 +1,5 @@ /*************************************************************************/ -/* replication_editor_plugin.cpp */ +/* replication_editor.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,15 +28,17 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "replication_editor_plugin.h" +#include "replication_editor.h" + +#include "../multiplayer_synchronizer.h" #include "editor/editor_node.h" #include "editor/editor_scale.h" #include "editor/editor_settings.h" #include "editor/editor_undo_redo_manager.h" #include "editor/inspector_dock.h" +#include "editor/property_selector.h" #include "editor/scene_tree_editor.h" -#include "modules/multiplayer/multiplayer_synchronizer.h" #include "scene/gui/dialogs.h" #include "scene/gui/separator.h" #include "scene/gui/tree.h" @@ -140,7 +142,7 @@ void ReplicationEditor::_add_sync_property(String p_path) { return; } - Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_singleton()->get_undo_redo(); + Ref<EditorUndoRedoManager> &undo_redo = EditorNode::get_singleton()->get_undo_redo(); undo_redo->create_action(TTR("Add property to synchronizer")); if (config.is_null()) { @@ -355,7 +357,7 @@ void ReplicationEditor::_tree_item_edited() { int column = tree->get_edited_column(); ERR_FAIL_COND(column < 1 || column > 2); const NodePath prop = ti->get_metadata(0); - Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_undo_redo(); + Ref<EditorUndoRedoManager> &undo_redo = EditorNode::get_undo_redo(); bool value = ti->is_checked(column); String method; if (column == 1) { @@ -395,7 +397,7 @@ void ReplicationEditor::_dialog_closed(bool p_confirmed) { int idx = config->property_get_index(prop); bool spawn = config->property_get_spawn(prop); bool sync = config->property_get_sync(prop); - Ref<EditorUndoRedoManager> undo_redo = EditorNode::get_undo_redo(); + Ref<EditorUndoRedoManager> &undo_redo = EditorNode::get_undo_redo(); undo_redo->create_action(TTR("Remove Property")); undo_redo->add_do_method(config.ptr(), "remove_property", prop); undo_redo->add_undo_method(config.ptr(), "add_property", prop, idx); @@ -492,62 +494,3 @@ void ReplicationEditor::_add_property(const NodePath &p_property, bool p_spawn, item->set_checked(2, p_sync); item->set_editable(2, true); } - -/// ReplicationEditorPlugin -ReplicationEditorPlugin::ReplicationEditorPlugin() { - repl_editor = memnew(ReplicationEditor); - button = EditorNode::get_singleton()->add_bottom_panel_item(TTR("Replication"), repl_editor); - button->hide(); - repl_editor->get_pin()->connect("pressed", callable_mp(this, &ReplicationEditorPlugin::_pinned)); -} - -ReplicationEditorPlugin::~ReplicationEditorPlugin() { -} - -void ReplicationEditorPlugin::_notification(int p_what) { - switch (p_what) { - case NOTIFICATION_ENTER_TREE: { - get_tree()->connect("node_removed", callable_mp(this, &ReplicationEditorPlugin::_node_removed)); - } break; - } -} - -void ReplicationEditorPlugin::_node_removed(Node *p_node) { - if (p_node && p_node == repl_editor->get_current()) { - repl_editor->edit(nullptr); - if (repl_editor->is_visible_in_tree()) { - EditorNode::get_singleton()->hide_bottom_panel(); - } - button->hide(); - repl_editor->get_pin()->set_pressed(false); - } -} - -void ReplicationEditorPlugin::_pinned() { - if (!repl_editor->get_pin()->is_pressed()) { - if (repl_editor->is_visible_in_tree()) { - EditorNode::get_singleton()->hide_bottom_panel(); - } - button->hide(); - } -} - -void ReplicationEditorPlugin::edit(Object *p_object) { - repl_editor->edit(Object::cast_to<MultiplayerSynchronizer>(p_object)); -} - -bool ReplicationEditorPlugin::handles(Object *p_object) const { - return p_object->is_class("MultiplayerSynchronizer"); -} - -void ReplicationEditorPlugin::make_visible(bool p_visible) { - if (p_visible) { - button->show(); - EditorNode::get_singleton()->make_bottom_panel_item_visible(repl_editor); - } else if (!repl_editor->get_pin()->is_pressed()) { - if (repl_editor->is_visible_in_tree()) { - EditorNode::get_singleton()->hide_bottom_panel(); - } - button->hide(); - } -} diff --git a/modules/multiplayer/editor/replication_editor_plugin.h b/modules/multiplayer/editor/replication_editor.h index e60e49cc25..8a48e8dbe7 100644 --- a/modules/multiplayer/editor/replication_editor_plugin.h +++ b/modules/multiplayer/editor/replication_editor.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* replication_editor_plugin.h */ +/* replication_editor.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,21 +28,21 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef REPLICATION_EDITOR_PLUGIN_H -#define REPLICATION_EDITOR_PLUGIN_H +#ifndef REPLICATION_EDITOR_H +#define REPLICATION_EDITOR_H #include "editor/editor_plugin.h" - -#include "editor/editor_spin_slider.h" -#include "editor/property_selector.h" - -#include "../scene_replication_config.h" +#include "modules/multiplayer/scene_replication_config.h" +#include "scene/gui/box_container.h" class ConfirmationDialog; class MultiplayerSynchronizer; -class SceneTreeDialog; +class AcceptDialog; +class LineEdit; class Tree; class TreeItem; +class PropertySelector; +class SceneTreeDialog; class ReplicationEditor : public VBoxContainer { GDCLASS(ReplicationEditor, VBoxContainer); @@ -105,27 +105,4 @@ public: ~ReplicationEditor() {} }; -class ReplicationEditorPlugin : public EditorPlugin { - GDCLASS(ReplicationEditorPlugin, EditorPlugin); - -private: - Button *button = nullptr; - ReplicationEditor *repl_editor = nullptr; - - void _node_removed(Node *p_node); - - void _pinned(); - -protected: - void _notification(int p_what); - -public: - virtual void edit(Object *p_object) override; - virtual bool handles(Object *p_object) const override; - virtual void make_visible(bool p_visible) override; - - ReplicationEditorPlugin(); - ~ReplicationEditorPlugin(); -}; - -#endif // REPLICATION_EDITOR_PLUGIN_H +#endif // REPLICATION_EDITOR_H diff --git a/modules/multiplayer/multiplayer_debugger.cpp b/modules/multiplayer/multiplayer_debugger.cpp new file mode 100644 index 0000000000..3d22af04dc --- /dev/null +++ b/modules/multiplayer/multiplayer_debugger.cpp @@ -0,0 +1,194 @@ +/*************************************************************************/ +/* multiplayer_debugger.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 "multiplayer_debugger.h" + +#include "core/debugger/engine_debugger.h" +#include "scene/main/node.h" + +List<Ref<EngineProfiler>> multiplayer_profilers; + +void MultiplayerDebugger::initialize() { + Ref<BandwidthProfiler> bandwidth; + bandwidth.instantiate(); + bandwidth->bind("multiplayer"); + multiplayer_profilers.push_back(bandwidth); + + Ref<RPCProfiler> rpc_profiler; + rpc_profiler.instantiate(); + rpc_profiler->bind("rpc"); + multiplayer_profilers.push_back(rpc_profiler); +} + +void MultiplayerDebugger::deinitialize() { + multiplayer_profilers.clear(); +} + +// BandwidthProfiler + +int MultiplayerDebugger::BandwidthProfiler::bandwidth_usage(const Vector<BandwidthFrame> &p_buffer, int p_pointer) { + ERR_FAIL_COND_V(p_buffer.size() == 0, 0); + int total_bandwidth = 0; + + uint64_t timestamp = OS::get_singleton()->get_ticks_msec(); + uint64_t final_timestamp = timestamp - 1000; + + int i = (p_pointer + p_buffer.size() - 1) % p_buffer.size(); + + while (i != p_pointer && p_buffer[i].packet_size > 0) { + if (p_buffer[i].timestamp < final_timestamp) { + return total_bandwidth; + } + total_bandwidth += p_buffer[i].packet_size; + i = (i + p_buffer.size() - 1) % p_buffer.size(); + } + + ERR_FAIL_COND_V_MSG(i == p_pointer, total_bandwidth, "Reached the end of the bandwidth profiler buffer, values might be inaccurate."); + return total_bandwidth; +} + +void MultiplayerDebugger::BandwidthProfiler::toggle(bool p_enable, const Array &p_opts) { + if (!p_enable) { + bandwidth_in.clear(); + bandwidth_out.clear(); + } else { + bandwidth_in_ptr = 0; + bandwidth_in.resize(16384); // ~128kB + for (int i = 0; i < bandwidth_in.size(); ++i) { + bandwidth_in.write[i].packet_size = -1; + } + bandwidth_out_ptr = 0; + bandwidth_out.resize(16384); // ~128kB + for (int i = 0; i < bandwidth_out.size(); ++i) { + bandwidth_out.write[i].packet_size = -1; + } + } +} + +void MultiplayerDebugger::BandwidthProfiler::add(const Array &p_data) { + ERR_FAIL_COND(p_data.size() < 3); + const String inout = p_data[0]; + int time = p_data[1]; + int size = p_data[2]; + if (inout == "in") { + bandwidth_in.write[bandwidth_in_ptr].timestamp = time; + bandwidth_in.write[bandwidth_in_ptr].packet_size = size; + bandwidth_in_ptr = (bandwidth_in_ptr + 1) % bandwidth_in.size(); + } else if (inout == "out") { + bandwidth_out.write[bandwidth_out_ptr].timestamp = time; + bandwidth_out.write[bandwidth_out_ptr].packet_size = size; + bandwidth_out_ptr = (bandwidth_out_ptr + 1) % bandwidth_out.size(); + } +} + +void MultiplayerDebugger::BandwidthProfiler::tick(double p_frame_time, double p_process_time, double p_physics_time, double p_physics_frame_time) { + uint64_t pt = OS::get_singleton()->get_ticks_msec(); + if (pt - last_bandwidth_time > 200) { + last_bandwidth_time = pt; + int incoming_bandwidth = bandwidth_usage(bandwidth_in, bandwidth_in_ptr); + int outgoing_bandwidth = bandwidth_usage(bandwidth_out, bandwidth_out_ptr); + + Array arr; + arr.push_back(incoming_bandwidth); + arr.push_back(outgoing_bandwidth); + EngineDebugger::get_singleton()->send_message("multiplayer:bandwidth", arr); + } +} + +// RPCProfiler + +Array MultiplayerDebugger::RPCFrame::serialize() { + Array arr; + arr.push_back(infos.size() * 4); + for (int i = 0; i < infos.size(); ++i) { + arr.push_back(uint64_t(infos[i].node)); + arr.push_back(infos[i].node_path); + arr.push_back(infos[i].incoming_rpc); + arr.push_back(infos[i].outgoing_rpc); + } + return arr; +} + +bool MultiplayerDebugger::RPCFrame::deserialize(const Array &p_arr) { + ERR_FAIL_COND_V(p_arr.size() < 1, false); + uint32_t size = p_arr[0]; + ERR_FAIL_COND_V(size % 4, false); + ERR_FAIL_COND_V((uint32_t)p_arr.size() != size + 1, false); + infos.resize(size / 4); + int idx = 1; + for (uint32_t i = 0; i < size / 4; ++i) { + infos.write[i].node = uint64_t(p_arr[idx]); + infos.write[i].node_path = p_arr[idx + 1]; + infos.write[i].incoming_rpc = p_arr[idx + 2]; + infos.write[i].outgoing_rpc = p_arr[idx + 3]; + } + return true; +} + +void MultiplayerDebugger::RPCProfiler::init_node(const ObjectID p_node) { + if (rpc_node_data.has(p_node)) { + return; + } + rpc_node_data.insert(p_node, RPCNodeInfo()); + rpc_node_data[p_node].node = p_node; + rpc_node_data[p_node].node_path = Object::cast_to<Node>(ObjectDB::get_instance(p_node))->get_path(); + rpc_node_data[p_node].incoming_rpc = 0; + rpc_node_data[p_node].outgoing_rpc = 0; +} + +void MultiplayerDebugger::RPCProfiler::toggle(bool p_enable, const Array &p_opts) { + rpc_node_data.clear(); +} + +void MultiplayerDebugger::RPCProfiler::add(const Array &p_data) { + ERR_FAIL_COND(p_data.size() < 2); + const ObjectID id = p_data[0]; + const String what = p_data[1]; + init_node(id); + RPCNodeInfo &info = rpc_node_data[id]; + if (what == "rpc_in") { + info.incoming_rpc++; + } else if (what == "rpc_out") { + info.outgoing_rpc++; + } +} + +void MultiplayerDebugger::RPCProfiler::tick(double p_frame_time, double p_process_time, double p_physics_time, double p_physics_frame_time) { + uint64_t pt = OS::get_singleton()->get_ticks_msec(); + if (pt - last_profile_time > 100) { + last_profile_time = pt; + RPCFrame frame; + for (const KeyValue<ObjectID, RPCNodeInfo> &E : rpc_node_data) { + frame.infos.push_back(E.value); + } + rpc_node_data.clear(); + EngineDebugger::get_singleton()->send_message("multiplayer:rpc", frame.serialize()); + } +} diff --git a/modules/multiplayer/multiplayer_debugger.h b/modules/multiplayer/multiplayer_debugger.h new file mode 100644 index 0000000000..4efd1da016 --- /dev/null +++ b/modules/multiplayer/multiplayer_debugger.h @@ -0,0 +1,95 @@ +/*************************************************************************/ +/* multiplayer_debugger.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 MULTIPLAYER_DEBUGGER_H +#define MULTIPLAYER_DEBUGGER_H + +#include "core/debugger/engine_profiler.h" + +#include "core/os/os.h" + +class MultiplayerDebugger { +public: + struct RPCNodeInfo { + ObjectID node; + String node_path; + int incoming_rpc = 0; + int outgoing_rpc = 0; + }; + + struct RPCFrame { + Vector<RPCNodeInfo> infos; + + Array serialize(); + bool deserialize(const Array &p_arr); + }; + +private: + class BandwidthProfiler : public EngineProfiler { + protected: + struct BandwidthFrame { + uint32_t timestamp; + int packet_size; + }; + + int bandwidth_in_ptr = 0; + Vector<BandwidthFrame> bandwidth_in; + int bandwidth_out_ptr = 0; + Vector<BandwidthFrame> bandwidth_out; + uint64_t last_bandwidth_time = 0; + + int bandwidth_usage(const Vector<BandwidthFrame> &p_buffer, int p_pointer); + + public: + void toggle(bool p_enable, const Array &p_opts); + void add(const Array &p_data); + void tick(double p_frame_time, double p_process_time, double p_physics_time, double p_physics_frame_time); + }; + + class RPCProfiler : public EngineProfiler { + public: + private: + HashMap<ObjectID, RPCNodeInfo> rpc_node_data; + uint64_t last_profile_time = 0; + + void init_node(const ObjectID p_node); + + public: + void toggle(bool p_enable, const Array &p_opts); + void add(const Array &p_data); + void tick(double p_frame_time, double p_process_time, double p_physics_time, double p_physics_frame_time); + }; + +public: + static void initialize(); + static void deinitialize(); +}; + +#endif // MULTIPLAYER_DEBUGGER_H diff --git a/modules/multiplayer/multiplayer_spawner.cpp b/modules/multiplayer/multiplayer_spawner.cpp index 6f60318b3b..620e4f2f6c 100644 --- a/modules/multiplayer/multiplayer_spawner.cpp +++ b/modules/multiplayer/multiplayer_spawner.cpp @@ -86,23 +86,41 @@ void MultiplayerSpawner::_get_property_list(List<PropertyInfo> *p_list) const { } } #endif + +PackedStringArray MultiplayerSpawner::get_configuration_warnings() const { + PackedStringArray warnings = Node::get_configuration_warnings(); + + if (spawn_path.is_empty() || !has_node(spawn_path)) { + warnings.push_back(RTR("A valid NodePath must be set in the \"Spawn Path\" property in order for MultiplayerSpawner to be able to spawn Nodes.")); + } + bool has_scenes = get_spawnable_scene_count() > 0; + // Can't check if method is overridden in placeholder scripts. + bool has_placeholder_script = get_script_instance() && get_script_instance()->is_placeholder(); + if (!has_scenes && !GDVIRTUAL_IS_OVERRIDDEN(_spawn_custom) && !has_placeholder_script) { + warnings.push_back(RTR("A list of PackedScenes must be set in the \"Auto Spawn List\" property in order for MultiplayerSpawner to automatically spawn them remotely when added as child of \"spawn_path\".")); + warnings.push_back(RTR("Alternatively, a Script implementing the function \"_spawn_custom\" must be set for this MultiplayerSpawner, and \"spawn\" must be called explicitly in code.")); + } + return warnings; +} + void MultiplayerSpawner::add_spawnable_scene(const String &p_path) { SpawnableScene sc; sc.path = p_path; if (Engine::get_singleton()->is_editor_hint()) { ERR_FAIL_COND(!FileAccess::exists(p_path)); - } else { - sc.cache = ResourceLoader::load(p_path); - ERR_FAIL_COND_MSG(sc.cache.is_null(), "Invalid spawnable scene: " + p_path); } spawnable_scenes.push_back(sc); } + int MultiplayerSpawner::get_spawnable_scene_count() const { return spawnable_scenes.size(); } + String MultiplayerSpawner::get_spawnable_scene(int p_idx) const { + ERR_FAIL_INDEX_V(p_idx, (int)spawnable_scenes.size(), ""); return spawnable_scenes[p_idx].path; } + void MultiplayerSpawner::clear_spawnable_scenes() { spawnable_scenes.clear(); } @@ -270,9 +288,12 @@ const Variant MultiplayerSpawner::get_spawn_argument(const ObjectID &p_id) const Node *MultiplayerSpawner::instantiate_scene(int p_id) { ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!"); ERR_FAIL_UNSIGNED_INDEX_V((uint32_t)p_id, spawnable_scenes.size(), nullptr); - Ref<PackedScene> scene = spawnable_scenes[p_id].cache; - ERR_FAIL_COND_V(scene.is_null(), nullptr); - return scene->instantiate(); + SpawnableScene &sc = spawnable_scenes[p_id]; + if (sc.cache.is_null()) { + sc.cache = ResourceLoader::load(sc.path); + } + ERR_FAIL_COND_V_MSG(sc.cache.is_null(), nullptr, "Invalid spawnable scene: " + sc.path); + return sc.cache->instantiate(); } Node *MultiplayerSpawner::instantiate_custom(const Variant &p_data) { diff --git a/modules/multiplayer/multiplayer_spawner.h b/modules/multiplayer/multiplayer_spawner.h index fc3befc2d4..587c99efd1 100644 --- a/modules/multiplayer/multiplayer_spawner.h +++ b/modules/multiplayer/multiplayer_spawner.h @@ -91,6 +91,8 @@ protected: void _get_property_list(List<PropertyInfo> *p_list) const; #endif public: + PackedStringArray get_configuration_warnings() const override; + Node *get_spawn_node() const { return spawn_node.is_valid() ? Object::cast_to<Node>(ObjectDB::get_instance(spawn_node)) : nullptr; } diff --git a/modules/multiplayer/multiplayer_synchronizer.cpp b/modules/multiplayer/multiplayer_synchronizer.cpp index eee1495c14..95857392c7 100644 --- a/modules/multiplayer/multiplayer_synchronizer.cpp +++ b/modules/multiplayer/multiplayer_synchronizer.cpp @@ -48,6 +48,8 @@ void MultiplayerSynchronizer::_stop() { return; } #endif + root_node_cache = ObjectID(); + reset(); Node *node = is_inside_tree() ? get_node_or_null(root_path) : nullptr; if (node) { get_multiplayer()->object_configuration_remove(node, this); @@ -60,8 +62,11 @@ void MultiplayerSynchronizer::_start() { return; } #endif + root_node_cache = ObjectID(); + reset(); Node *node = is_inside_tree() ? get_node_or_null(root_path) : nullptr; if (node) { + root_node_cache = node->get_instance_id(); get_multiplayer()->object_configuration_add(node, this); _update_process(); } @@ -94,6 +99,54 @@ void MultiplayerSynchronizer::_update_process() { } } +Node *MultiplayerSynchronizer::get_root_node() { + return root_node_cache.is_valid() ? Object::cast_to<Node>(ObjectDB::get_instance(root_node_cache)) : nullptr; +} + +void MultiplayerSynchronizer::reset() { + net_id = 0; + last_sync_msec = 0; + last_inbound_sync = 0; +} + +uint32_t MultiplayerSynchronizer::get_net_id() const { + return net_id; +} + +void MultiplayerSynchronizer::set_net_id(uint32_t p_net_id) { + net_id = p_net_id; +} + +bool MultiplayerSynchronizer::update_outbound_sync_time(uint64_t p_msec) { + if (last_sync_msec == p_msec) { + // last_sync_msec has been updated on this frame. + return true; + } + if (p_msec >= last_sync_msec + interval_msec) { + last_sync_msec = p_msec; + return true; + } + return false; +} + +bool MultiplayerSynchronizer::update_inbound_sync_time(uint16_t p_network_time) { + if (p_network_time <= last_inbound_sync && last_inbound_sync - p_network_time < 32767) { + return false; + } + last_inbound_sync = p_network_time; + return true; +} + +PackedStringArray MultiplayerSynchronizer::get_configuration_warnings() const { + PackedStringArray warnings = Node::get_configuration_warnings(); + + if (root_path.is_empty() || !has_node(root_path)) { + warnings.push_back(RTR("A valid NodePath must be set in the \"Root Path\" property in order for MultiplayerSynchronizer to be able to synchronize properties.")); + } + + return warnings; +} + Error MultiplayerSynchronizer::get_state(const List<NodePath> &p_properties, Object *p_obj, Vector<Variant> &r_variant, Vector<const Variant *> &r_variant_ptrs) { ERR_FAIL_COND_V(!p_obj, ERR_INVALID_PARAMETER); r_variant.resize(p_properties.size()); @@ -253,10 +306,6 @@ double MultiplayerSynchronizer::get_replication_interval() const { return double(interval_msec) / 1000.0; } -uint64_t MultiplayerSynchronizer::get_replication_interval_msec() const { - return interval_msec; -} - void MultiplayerSynchronizer::set_replication_config(Ref<SceneReplicationConfig> p_config) { replication_config = p_config; } @@ -289,10 +338,11 @@ NodePath MultiplayerSynchronizer::get_root_path() const { void MultiplayerSynchronizer::set_multiplayer_authority(int p_peer_id, bool p_recursive) { Node *node = is_inside_tree() ? get_node_or_null(root_path) : nullptr; - if (!node) { + if (!node || get_multiplayer_authority() == p_peer_id) { Node::set_multiplayer_authority(p_peer_id, p_recursive); return; } + get_multiplayer()->object_configuration_remove(node, this); Node::set_multiplayer_authority(p_peer_id, p_recursive); get_multiplayer()->object_configuration_add(node, this); diff --git a/modules/multiplayer/multiplayer_synchronizer.h b/modules/multiplayer/multiplayer_synchronizer.h index e84d41db86..9a7ce717cd 100644 --- a/modules/multiplayer/multiplayer_synchronizer.h +++ b/modules/multiplayer/multiplayer_synchronizer.h @@ -53,6 +53,11 @@ private: HashSet<Callable> visibility_filters; HashSet<int> peer_visibility; + ObjectID root_node_cache; + uint64_t last_sync_msec = 0; + uint16_t last_inbound_sync = 0; + uint32_t net_id = 0; + static Object *_get_prop_target(Object *p_obj, const NodePath &p_prop); void _start(); void _stop(); @@ -66,9 +71,19 @@ public: static Error get_state(const List<NodePath> &p_properties, Object *p_obj, Vector<Variant> &r_variant, Vector<const Variant *> &r_variant_ptrs); static Error set_state(const List<NodePath> &p_properties, Object *p_obj, const Vector<Variant> &p_state); + void reset(); + Node *get_root_node(); + + uint32_t get_net_id() const; + void set_net_id(uint32_t p_net_id); + + bool update_outbound_sync_time(uint64_t p_msec); + bool update_inbound_sync_time(uint16_t p_network_time); + + PackedStringArray get_configuration_warnings() const override; + void set_replication_interval(double p_interval); double get_replication_interval() const; - uint64_t get_replication_interval_msec() const; void set_replication_config(Ref<SceneReplicationConfig> p_config); Ref<SceneReplicationConfig> get_replication_config(); diff --git a/modules/multiplayer/register_types.cpp b/modules/multiplayer/register_types.cpp index a2c524da80..2bf1041029 100644 --- a/modules/multiplayer/register_types.cpp +++ b/modules/multiplayer/register_types.cpp @@ -36,9 +36,10 @@ #include "scene_replication_interface.h" #include "scene_rpc_interface.h" +#include "multiplayer_debugger.h" + #ifdef TOOLS_ENABLED -#include "editor/editor_plugin.h" -#include "editor/replication_editor_plugin.h" +#include "editor/multiplayer_editor_plugin.h" #endif void initialize_multiplayer_module(ModuleInitializationLevel p_level) { @@ -48,13 +49,15 @@ void initialize_multiplayer_module(ModuleInitializationLevel p_level) { GDREGISTER_CLASS(MultiplayerSynchronizer); GDREGISTER_CLASS(SceneMultiplayer); MultiplayerAPI::set_default_interface("SceneMultiplayer"); + MultiplayerDebugger::initialize(); } #ifdef TOOLS_ENABLED if (p_level == MODULE_INITIALIZATION_LEVEL_EDITOR) { - EditorPlugins::add_by_type<ReplicationEditorPlugin>(); + EditorPlugins::add_by_type<MultiplayerEditorPlugin>(); } #endif } void uninitialize_multiplayer_module(ModuleInitializationLevel p_level) { + MultiplayerDebugger::deinitialize(); } diff --git a/modules/multiplayer/scene_cache_interface.cpp b/modules/multiplayer/scene_cache_interface.cpp index b3b642f815..7df9b95b30 100644 --- a/modules/multiplayer/scene_cache_interface.cpp +++ b/modules/multiplayer/scene_cache_interface.cpp @@ -105,8 +105,7 @@ void SceneCacheInterface::process_simplify_path(int p_from, const uint8_t *p_pac multiplayer_peer->set_transfer_channel(0); multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE); - multiplayer_peer->set_target_peer(p_from); - multiplayer_peer->put_packet(packet.ptr(), packet.size()); + multiplayer->send_command(p_from, packet.ptr(), packet.size()); } void SceneCacheInterface::process_confirm_path(int p_from, const uint8_t *p_packet, int p_packet_len) { @@ -162,10 +161,9 @@ Error SceneCacheInterface::_send_confirm_path(Node *p_node, NodePath p_path, Pat Error err = OK; for (int peer_id : p_peers) { - multiplayer_peer->set_target_peer(peer_id); multiplayer_peer->set_transfer_channel(0); multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE); - err = multiplayer_peer->put_packet(packet.ptr(), packet.size()); + err = multiplayer->send_command(peer_id, packet.ptr(), packet.size()); ERR_FAIL_COND_V(err != OK, err); // Insert into confirmed, but as false since it was not confirmed. psc->confirmed_peers.insert(peer_id, false); diff --git a/modules/multiplayer/scene_multiplayer.cpp b/modules/multiplayer/scene_multiplayer.cpp index 3fc1eef366..db7c5037cd 100644 --- a/modules/multiplayer/scene_multiplayer.cpp +++ b/modules/multiplayer/scene_multiplayer.cpp @@ -51,14 +51,32 @@ void SceneMultiplayer::profile_bandwidth(const String &p_inout, int p_size) { } #endif +void SceneMultiplayer::_update_status() { + MultiplayerPeer::ConnectionStatus status = multiplayer_peer.is_valid() ? multiplayer_peer->get_connection_status() : MultiplayerPeer::CONNECTION_DISCONNECTED; + if (last_connection_status != status) { + if (status == MultiplayerPeer::CONNECTION_DISCONNECTED) { + if (last_connection_status == MultiplayerPeer::CONNECTION_CONNECTING) { + emit_signal(SNAME("connection_failed")); + } else { + emit_signal(SNAME("server_disconnected")); + } + clear(); + } + last_connection_status = status; + } +} + Error SceneMultiplayer::poll() { - if (!multiplayer_peer.is_valid() || multiplayer_peer->get_connection_status() == MultiplayerPeer::CONNECTION_DISCONNECTED) { - return ERR_UNCONFIGURED; + _update_status(); + if (last_connection_status == MultiplayerPeer::CONNECTION_DISCONNECTED) { + return OK; } multiplayer_peer->poll(); - if (!multiplayer_peer.is_valid()) { // It's possible that polling might have resulted in a disconnection, so check here. + _update_status(); + if (last_connection_status != MultiplayerPeer::CONNECTION_CONNECTED) { + // We might be still connecting, or polling might have resulted in a disconnection. return OK; } @@ -67,25 +85,99 @@ Error SceneMultiplayer::poll() { const uint8_t *packet; int len; + int channel = multiplayer_peer->get_packet_channel(); + MultiplayerPeer::TransferMode mode = multiplayer_peer->get_packet_mode(); + Error err = multiplayer_peer->get_packet(&packet, len); ERR_FAIL_COND_V_MSG(err != OK, err, vformat("Error getting packet! %d", err)); - remote_sender_id = sender; - _process_packet(sender, packet, len); - remote_sender_id = 0; + if (pending_peers.has(sender)) { + if (pending_peers[sender].local) { + // If the auth is over, admit the peer at the first packet. + pending_peers.erase(sender); + _admit_peer(sender); + } else { + ERR_CONTINUE(len < 2 || (packet[0] & CMD_MASK) != NETWORK_COMMAND_SYS || packet[1] != SYS_COMMAND_AUTH); + // Auth message. + PackedByteArray pba; + pba.resize(len - 2); + if (pba.size()) { + memcpy(pba.ptrw(), &packet[2], len - 2); + // User callback + const Variant sv = sender; + const Variant pbav = pba; + const Variant *argv[2] = { &sv, &pbav }; + Variant ret; + Callable::CallError ce; + auth_callback.callp(argv, 2, ret, ce); + ERR_CONTINUE_MSG(ce.error != Callable::CallError::CALL_OK, "Failed to call authentication callback"); + } else { + // Remote complete notification. + pending_peers[sender].remote = true; + if (pending_peers[sender].local) { + pending_peers.erase(sender); + _admit_peer(sender); + } + } + continue; // Auth in progress. + } + } - if (!multiplayer_peer.is_valid()) { - return OK; // It's also possible that a packet or RPC caused a disconnection, so also check here. + ERR_CONTINUE(!connected_peers.has(sender)); + + if (len && (packet[0] & CMD_MASK) == NETWORK_COMMAND_SYS) { + // Sys messages are processed separately since they might call _process_packet themselves. + if (len > 1 && packet[1] == SYS_COMMAND_AUTH) { + ERR_CONTINUE(len != 2); + // If we are here, we already admitted the peer locally, and this is just a confirmation packet. + continue; + } + + _process_sys(sender, packet, len, mode, channel); + } else { + remote_sender_id = sender; + _process_packet(sender, packet, len); + remote_sender_id = 0; + } + + _update_status(); + if (last_connection_status != MultiplayerPeer::CONNECTION_CONNECTED) { // It's possible that processing a packet might have resulted in a disconnection, so check here. + return OK; + } + } + if (pending_peers.size() && auth_timeout) { + HashSet<int> to_drop; + uint64_t time = OS::get_singleton()->get_ticks_msec(); + for (const KeyValue<int, PendingPeer> &pending : pending_peers) { + if (pending.value.time + auth_timeout <= time) { + multiplayer_peer->disconnect_peer(pending.key); + to_drop.insert(pending.key); + } + } + for (const int &P : to_drop) { + // Each signal might trigger a disconnection. + pending_peers.erase(P); + emit_signal(SNAME("peer_authentication_failed"), P); } } + + _update_status(); + if (last_connection_status != MultiplayerPeer::CONNECTION_CONNECTED) { // Signals might have triggered disconnection. + return OK; + } + replicator->on_network_process(); return OK; } void SceneMultiplayer::clear() { + last_connection_status = MultiplayerPeer::CONNECTION_DISCONNECTED; + pending_peers.clear(); connected_peers.clear(); packet_cache.clear(); + replicator->on_reset(); cache->clear(); + relay_buffer->clear(); } void SceneMultiplayer::set_root_path(const NodePath &p_path) { @@ -108,9 +200,6 @@ void SceneMultiplayer::set_multiplayer_peer(const Ref<MultiplayerPeer> &p_peer) if (multiplayer_peer.is_valid()) { multiplayer_peer->disconnect("peer_connected", callable_mp(this, &SceneMultiplayer::_add_peer)); multiplayer_peer->disconnect("peer_disconnected", callable_mp(this, &SceneMultiplayer::_del_peer)); - multiplayer_peer->disconnect("connection_succeeded", callable_mp(this, &SceneMultiplayer::_connected_to_server)); - multiplayer_peer->disconnect("connection_failed", callable_mp(this, &SceneMultiplayer::_connection_failed)); - multiplayer_peer->disconnect("server_disconnected", callable_mp(this, &SceneMultiplayer::_server_disconnected)); clear(); } @@ -119,11 +208,8 @@ void SceneMultiplayer::set_multiplayer_peer(const Ref<MultiplayerPeer> &p_peer) if (multiplayer_peer.is_valid()) { multiplayer_peer->connect("peer_connected", callable_mp(this, &SceneMultiplayer::_add_peer)); multiplayer_peer->connect("peer_disconnected", callable_mp(this, &SceneMultiplayer::_del_peer)); - multiplayer_peer->connect("connection_succeeded", callable_mp(this, &SceneMultiplayer::_connected_to_server)); - multiplayer_peer->connect("connection_failed", callable_mp(this, &SceneMultiplayer::_connection_failed)); - multiplayer_peer->connect("server_disconnected", callable_mp(this, &SceneMultiplayer::_server_disconnected)); } - replicator->on_reset(); + _update_status(); } Ref<MultiplayerPeer> SceneMultiplayer::get_multiplayer_peer() { @@ -166,34 +252,184 @@ void SceneMultiplayer::_process_packet(int p_from, const uint8_t *p_packet, int case NETWORK_COMMAND_SYNC: { replicator->on_sync_receive(p_from, p_packet, p_packet_len); } break; + default: { + ERR_FAIL_MSG("Invalid network command from " + itos(p_from)); + } break; + } +} + +Error SceneMultiplayer::send_command(int p_to, const uint8_t *p_packet, int p_packet_len) { + if (server_relay && get_unique_id() != 1 && p_to != 1 && multiplayer_peer->is_server_relay_supported()) { + // Send relay packet. + relay_buffer->seek(0); + relay_buffer->put_u8(NETWORK_COMMAND_SYS); + relay_buffer->put_u8(SYS_COMMAND_RELAY); + relay_buffer->put_32(p_to); // Set the destination. + relay_buffer->put_data(p_packet, p_packet_len); + multiplayer_peer->set_target_peer(1); + const Vector<uint8_t> data = relay_buffer->get_data_array(); + return multiplayer_peer->put_packet(data.ptr(), relay_buffer->get_position()); + } + if (p_to > 0) { + ERR_FAIL_COND_V(!connected_peers.has(p_to), ERR_BUG); + multiplayer_peer->set_target_peer(p_to); + return multiplayer_peer->put_packet(p_packet, p_packet_len); + } else { + for (const int &pid : connected_peers) { + if (p_to && pid == -p_to) { + continue; + } + multiplayer_peer->set_target_peer(pid); + multiplayer_peer->put_packet(p_packet, p_packet_len); + } + return OK; + } +} + +void SceneMultiplayer::_process_sys(int p_from, const uint8_t *p_packet, int p_packet_len, MultiplayerPeer::TransferMode p_mode, int p_channel) { + ERR_FAIL_COND_MSG(p_packet_len < SYS_CMD_SIZE, "Invalid packet received. Size too small."); + uint8_t sys_cmd_type = p_packet[1]; + int32_t peer = int32_t(decode_uint32(&p_packet[2])); + switch (sys_cmd_type) { + case SYS_COMMAND_ADD_PEER: { + ERR_FAIL_COND(!server_relay || !multiplayer_peer->is_server_relay_supported() || get_unique_id() == 1 || p_from != 1); + _admit_peer(peer); // Relayed peers are automatically accepted. + } break; + case SYS_COMMAND_DEL_PEER: { + ERR_FAIL_COND(!server_relay || !multiplayer_peer->is_server_relay_supported() || get_unique_id() == 1 || p_from != 1); + _del_peer(peer); + } break; + case SYS_COMMAND_RELAY: { + ERR_FAIL_COND(!server_relay || !multiplayer_peer->is_server_relay_supported()); + ERR_FAIL_COND(p_packet_len < SYS_CMD_SIZE + 1); + const uint8_t *packet = p_packet + SYS_CMD_SIZE; + int len = p_packet_len - SYS_CMD_SIZE; + bool should_process = false; + if (get_unique_id() == 1) { // I am the server. + // Direct messages to server should not go through relay. + ERR_FAIL_COND(peer > 0 && !connected_peers.has(peer)); + // Send relay packet. + relay_buffer->seek(0); + relay_buffer->put_u8(NETWORK_COMMAND_SYS); + relay_buffer->put_u8(SYS_COMMAND_RELAY); + relay_buffer->put_32(p_from); // Set the source. + relay_buffer->put_data(packet, len); + const Vector<uint8_t> data = relay_buffer->get_data_array(); + multiplayer_peer->set_transfer_mode(p_mode); + multiplayer_peer->set_transfer_channel(p_channel); + if (peer > 0) { + multiplayer_peer->set_target_peer(peer); + multiplayer_peer->put_packet(data.ptr(), relay_buffer->get_position()); + } else { + for (const int &P : connected_peers) { + // Not to sender, nor excluded. + if (P == p_from || (peer < 0 && P != -peer)) { + continue; + } + multiplayer_peer->set_target_peer(P); + multiplayer_peer->put_packet(data.ptr(), relay_buffer->get_position()); + } + } + if (peer == 0 || peer == -1) { + should_process = true; + peer = p_from; // Process as the source. + } + } else { + ERR_FAIL_COND(p_from != 1); // Bug. + should_process = true; + } + if (should_process) { + remote_sender_id = peer; + _process_packet(peer, packet, len); + remote_sender_id = 0; + } + } break; + default: { + ERR_FAIL(); + } } } void SceneMultiplayer::_add_peer(int p_id) { + if (auth_callback.is_valid()) { + pending_peers[p_id] = PendingPeer(); + pending_peers[p_id].time = OS::get_singleton()->get_ticks_msec(); + emit_signal(SNAME("peer_authenticating"), p_id); + return; + } else { + _admit_peer(p_id); + } +} + +void SceneMultiplayer::_admit_peer(int p_id) { + if (server_relay && get_unique_id() == 1 && multiplayer_peer->is_server_relay_supported()) { + // Notify others of connection, and send connected peers to newly connected one. + uint8_t buf[SYS_CMD_SIZE]; + buf[0] = NETWORK_COMMAND_SYS; + buf[1] = SYS_COMMAND_ADD_PEER; + multiplayer_peer->set_transfer_channel(0); + multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE); + for (const int &P : connected_peers) { + // Send new peer to already connected. + encode_uint32(p_id, &buf[2]); + multiplayer_peer->set_target_peer(P); + multiplayer_peer->put_packet(buf, sizeof(buf)); + // Send already connected to new peer. + encode_uint32(P, &buf[2]); + multiplayer_peer->set_target_peer(p_id); + multiplayer_peer->put_packet(buf, sizeof(buf)); + } + } + connected_peers.insert(p_id); cache->on_peer_change(p_id, true); replicator->on_peer_change(p_id, true); + if (p_id == 1) { + emit_signal(SNAME("connected_to_server")); + } emit_signal(SNAME("peer_connected"), p_id); } void SceneMultiplayer::_del_peer(int p_id) { + if (pending_peers.has(p_id)) { + pending_peers.erase(p_id); + emit_signal(SNAME("peer_authentication_failed"), p_id); + return; + } else if (!connected_peers.has(p_id)) { + return; + } + + if (server_relay && get_unique_id() == 1 && multiplayer_peer->is_server_relay_supported()) { + // Notify others of disconnection. + uint8_t buf[SYS_CMD_SIZE]; + buf[0] = NETWORK_COMMAND_SYS; + buf[1] = SYS_COMMAND_DEL_PEER; + multiplayer_peer->set_transfer_channel(0); + multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE); + encode_uint32(p_id, &buf[2]); + for (const int &P : connected_peers) { + if (P == p_id) { + continue; + } + multiplayer_peer->set_target_peer(P); + multiplayer_peer->put_packet(buf, sizeof(buf)); + } + } + replicator->on_peer_change(p_id, false); cache->on_peer_change(p_id, false); connected_peers.erase(p_id); emit_signal(SNAME("peer_disconnected"), p_id); } -void SceneMultiplayer::_connected_to_server() { - emit_signal(SNAME("connected_to_server")); -} - -void SceneMultiplayer::_connection_failed() { - emit_signal(SNAME("connection_failed")); -} - -void SceneMultiplayer::_server_disconnected() { - replicator->on_reset(); - emit_signal(SNAME("server_disconnected")); +void SceneMultiplayer::disconnect_peer(int p_id) { + ERR_FAIL_COND(multiplayer_peer.is_null() || multiplayer_peer->get_connection_status() != MultiplayerPeer::CONNECTION_CONNECTED); + if (pending_peers.has(p_id)) { + pending_peers.erase(p_id); + } else if (connected_peers.has(p_id)) { + connected_peers.has(p_id); + } + multiplayer_peer->disconnect_peer(p_id); } Error SceneMultiplayer::send_bytes(Vector<uint8_t> p_data, int p_to, MultiplayerPeer::TransferMode p_mode, int p_channel) { @@ -209,11 +445,64 @@ Error SceneMultiplayer::send_bytes(Vector<uint8_t> p_data, int p_to, Multiplayer packet_cache.write[0] = NETWORK_COMMAND_RAW; memcpy(&packet_cache.write[1], &r[0], p_data.size()); - multiplayer_peer->set_target_peer(p_to); multiplayer_peer->set_transfer_channel(p_channel); multiplayer_peer->set_transfer_mode(p_mode); + return send_command(p_to, packet_cache.ptr(), p_data.size() + 1); +} + +Error SceneMultiplayer::send_auth(int p_to, Vector<uint8_t> p_data) { + ERR_FAIL_COND_V(multiplayer_peer.is_null() || multiplayer_peer->get_connection_status() != MultiplayerPeer::CONNECTION_CONNECTED, ERR_UNCONFIGURED); + ERR_FAIL_COND_V(!pending_peers.has(p_to), ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_data.size() < 1, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V_MSG(pending_peers[p_to].local, ERR_FILE_CANT_WRITE, "The authentication session was previously marked as completed, no more authentication data can be sent."); + ERR_FAIL_COND_V_MSG(pending_peers[p_to].remote, ERR_FILE_CANT_WRITE, "The remote peer notified that the authentication session was completed, no more authentication data can be sent."); + + if (packet_cache.size() < p_data.size() + 2) { + packet_cache.resize(p_data.size() + 2); + } + + packet_cache.write[0] = NETWORK_COMMAND_SYS; + packet_cache.write[1] = SYS_COMMAND_AUTH; + memcpy(&packet_cache.write[2], p_data.ptr(), p_data.size()); + + multiplayer_peer->set_target_peer(p_to); + multiplayer_peer->set_transfer_channel(0); + multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE); + return multiplayer_peer->put_packet(packet_cache.ptr(), p_data.size() + 2); +} + +Error SceneMultiplayer::complete_auth(int p_peer) { + ERR_FAIL_COND_V(multiplayer_peer.is_null() || multiplayer_peer->get_connection_status() != MultiplayerPeer::CONNECTION_CONNECTED, ERR_UNCONFIGURED); + ERR_FAIL_COND_V(!pending_peers.has(p_peer), ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V_MSG(pending_peers[p_peer].local, ERR_FILE_CANT_WRITE, "The authentication session was already marked as completed."); + pending_peers[p_peer].local = true; + // Notify the remote peer that the authentication has completed. + uint8_t buf[2] = { NETWORK_COMMAND_SYS, SYS_COMMAND_AUTH }; + Error err = multiplayer_peer->put_packet(buf, 2); + // The remote peer already reported the authentication as completed, so admit the peer. + // May generate new packets, so it must happen after sending confirmation. + if (pending_peers[p_peer].remote) { + pending_peers.erase(p_peer); + _admit_peer(p_peer); + } + return err; +} + +void SceneMultiplayer::set_auth_callback(Callable p_callback) { + auth_callback = p_callback; +} + +Callable SceneMultiplayer::get_auth_callback() const { + return auth_callback; +} + +void SceneMultiplayer::set_auth_timeout(double p_timeout) { + ERR_FAIL_COND_MSG(p_timeout < 0, "Timeout must be greater or equal to 0 (where 0 means no timeout)"); + auth_timeout = uint64_t(p_timeout * 1000); +} - return multiplayer_peer->put_packet(packet_cache.ptr(), p_data.size() + 1); +double SceneMultiplayer::get_auth_timeout() const { + return double(auth_timeout) / 1000.0; } void SceneMultiplayer::_process_raw(int p_from, const uint8_t *p_packet, int p_packet_len) { @@ -255,6 +544,16 @@ Vector<int> SceneMultiplayer::get_peer_ids() { return ret; } +Vector<int> SceneMultiplayer::get_authenticating_peer_ids() { + Vector<int> out; + out.resize(pending_peers.size()); + int idx = 0; + for (const KeyValue<int, PendingPeer> &E : pending_peers) { + out.write[idx++] = E.key; + } + return out; +} + void SceneMultiplayer::set_allow_object_decoding(bool p_enable) { allow_object_decoding = p_enable; } @@ -303,25 +602,55 @@ Error SceneMultiplayer::object_configuration_remove(Object *p_obj, Variant p_con return ERR_INVALID_PARAMETER; } +void SceneMultiplayer::set_server_relay_enabled(bool p_enabled) { + ERR_FAIL_COND_MSG(multiplayer_peer.is_valid() && multiplayer_peer->get_connection_status() != MultiplayerPeer::CONNECTION_DISCONNECTED, "Cannot change the server relay option while the multiplayer peer is active."); + server_relay = p_enabled; +} + +bool SceneMultiplayer::is_server_relay_enabled() const { + return server_relay; +} + void SceneMultiplayer::_bind_methods() { ClassDB::bind_method(D_METHOD("set_root_path", "path"), &SceneMultiplayer::set_root_path); ClassDB::bind_method(D_METHOD("get_root_path"), &SceneMultiplayer::get_root_path); ClassDB::bind_method(D_METHOD("clear"), &SceneMultiplayer::clear); + + ClassDB::bind_method(D_METHOD("disconnect_peer", "id"), &SceneMultiplayer::disconnect_peer); + + ClassDB::bind_method(D_METHOD("get_authenticating_peers"), &SceneMultiplayer::get_authenticating_peer_ids); + ClassDB::bind_method(D_METHOD("send_auth", "id", "data"), &SceneMultiplayer::send_auth); + ClassDB::bind_method(D_METHOD("complete_auth", "id"), &SceneMultiplayer::complete_auth); + + ClassDB::bind_method(D_METHOD("set_auth_callback", "callback"), &SceneMultiplayer::set_auth_callback); + ClassDB::bind_method(D_METHOD("get_auth_callback"), &SceneMultiplayer::get_auth_callback); + ClassDB::bind_method(D_METHOD("set_auth_timeout", "timeout"), &SceneMultiplayer::set_auth_timeout); + ClassDB::bind_method(D_METHOD("get_auth_timeout"), &SceneMultiplayer::get_auth_timeout); + ClassDB::bind_method(D_METHOD("set_refuse_new_connections", "refuse"), &SceneMultiplayer::set_refuse_new_connections); ClassDB::bind_method(D_METHOD("is_refusing_new_connections"), &SceneMultiplayer::is_refusing_new_connections); ClassDB::bind_method(D_METHOD("set_allow_object_decoding", "enable"), &SceneMultiplayer::set_allow_object_decoding); ClassDB::bind_method(D_METHOD("is_object_decoding_allowed"), &SceneMultiplayer::is_object_decoding_allowed); + ClassDB::bind_method(D_METHOD("set_server_relay_enabled", "enabled"), &SceneMultiplayer::set_server_relay_enabled); + ClassDB::bind_method(D_METHOD("is_server_relay_enabled"), &SceneMultiplayer::is_server_relay_enabled); ClassDB::bind_method(D_METHOD("send_bytes", "bytes", "id", "mode", "channel"), &SceneMultiplayer::send_bytes, DEFVAL(MultiplayerPeer::TARGET_PEER_BROADCAST), DEFVAL(MultiplayerPeer::TRANSFER_MODE_RELIABLE), DEFVAL(0)); ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "root_path"), "set_root_path", "get_root_path"); + ADD_PROPERTY(PropertyInfo(Variant::CALLABLE, "auth_callback"), "set_auth_callback", "get_auth_callback"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "auth_timeout", PROPERTY_HINT_RANGE, "0,30,0.1,or_greater,suffix:s"), "set_auth_timeout", "get_auth_timeout"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "allow_object_decoding"), "set_allow_object_decoding", "is_object_decoding_allowed"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "refuse_new_connections"), "set_refuse_new_connections", "is_refusing_new_connections"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "server_relay"), "set_server_relay_enabled", "is_server_relay_enabled"); + ADD_PROPERTY_DEFAULT("refuse_new_connections", false); + ADD_SIGNAL(MethodInfo("peer_authenticating", PropertyInfo(Variant::INT, "id"))); + ADD_SIGNAL(MethodInfo("peer_authentication_failed", PropertyInfo(Variant::INT, "id"))); ADD_SIGNAL(MethodInfo("peer_packet", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::PACKED_BYTE_ARRAY, "packet"))); } SceneMultiplayer::SceneMultiplayer() { + relay_buffer.instantiate(); replicator = Ref<SceneReplicationInterface>(memnew(SceneReplicationInterface(this))); rpc = Ref<SceneRPCInterface>(memnew(SceneRPCInterface(this))); cache = Ref<SceneCacheInterface>(memnew(SceneCacheInterface(this))); diff --git a/modules/multiplayer/scene_multiplayer.h b/modules/multiplayer/scene_multiplayer.h index a99cca7b21..b0ecc48f8c 100644 --- a/modules/multiplayer/scene_multiplayer.h +++ b/modules/multiplayer/scene_multiplayer.h @@ -49,6 +49,18 @@ public: NETWORK_COMMAND_SPAWN, NETWORK_COMMAND_DESPAWN, NETWORK_COMMAND_SYNC, + NETWORK_COMMAND_SYS, + }; + + enum SysCommands { + SYS_COMMAND_AUTH, + SYS_COMMAND_ADD_PEER, + SYS_COMMAND_DEL_PEER, + SYS_COMMAND_RELAY, + }; + + enum { + SYS_CMD_SIZE = 6, // Command + sys command + peer_id (+ optional payload). }; // For each command, the 4 MSB can contain custom flags, as defined by subsystems. @@ -65,7 +77,17 @@ public: }; private: + struct PendingPeer { + bool local = false; + bool remote = false; + uint64_t time = 0; + }; + Ref<MultiplayerPeer> multiplayer_peer; + MultiplayerPeer::ConnectionStatus last_connection_status = MultiplayerPeer::CONNECTION_DISCONNECTED; + HashMap<int, PendingPeer> pending_peers; // true if locally finalized. + Callable auth_callback; + uint64_t auth_timeout = 3000; HashSet<int> connected_peers; int remote_sender_id = 0; int remote_sender_override = 0; @@ -74,6 +96,8 @@ private: NodePath root_path; bool allow_object_decoding = false; + bool server_relay = true; + Ref<StreamPeerBuffer> relay_buffer; Ref<SceneCacheInterface> cache; Ref<SceneReplicationInterface> replicator; @@ -84,12 +108,12 @@ protected: void _process_packet(int p_from, const uint8_t *p_packet, int p_packet_len); void _process_raw(int p_from, const uint8_t *p_packet, int p_packet_len); + void _process_sys(int p_from, const uint8_t *p_packet, int p_packet_len, MultiplayerPeer::TransferMode p_mode, int p_channel); void _add_peer(int p_id); + void _admit_peer(int p_id); void _del_peer(int p_id); - void _connected_to_server(); - void _connection_failed(); - void _server_disconnected(); + void _update_status(); public: virtual void set_multiplayer_peer(const Ref<MultiplayerPeer> &p_peer) override; @@ -111,6 +135,17 @@ public: void set_root_path(const NodePath &p_path); NodePath get_root_path() const; + void disconnect_peer(int p_id); + + Error send_auth(int p_to, Vector<uint8_t> p_bytes); + Error complete_auth(int p_peer); + void set_auth_callback(Callable p_callback); + Callable get_auth_callback() const; + void set_auth_timeout(double p_timeout); + double get_auth_timeout() const; + Vector<int> get_authenticating_peer_ids(); + + Error send_command(int p_to, const uint8_t *p_packet, int p_packet_len); // Used internally to relay packets when needed. Error send_bytes(Vector<uint8_t> p_data, int p_to = MultiplayerPeer::TARGET_PEER_BROADCAST, MultiplayerPeer::TransferMode p_mode = MultiplayerPeer::TRANSFER_MODE_RELIABLE, int p_channel = 0); String get_rpc_md5(const Object *p_obj); @@ -123,6 +158,9 @@ public: void set_allow_object_decoding(bool p_enable); bool is_object_decoding_allowed() const; + void set_server_relay_enabled(bool p_enabled); + bool is_server_relay_enabled() const; + Ref<SceneCacheInterface> get_path_cache() { return cache; } #ifdef DEBUG_ENABLED diff --git a/modules/multiplayer/scene_replication_config.cpp b/modules/multiplayer/scene_replication_config.cpp index ae06516b7b..61fe51b6c9 100644 --- a/modules/multiplayer/scene_replication_config.cpp +++ b/modules/multiplayer/scene_replication_config.cpp @@ -34,11 +34,11 @@ #include "scene/main/node.h" bool SceneReplicationConfig::_set(const StringName &p_name, const Variant &p_value) { - String name = p_name; + String prop_name = p_name; - if (name.begins_with("properties/")) { - int idx = name.get_slicec('/', 1).to_int(); - String what = name.get_slicec('/', 2); + if (prop_name.begins_with("properties/")) { + int idx = prop_name.get_slicec('/', 1).to_int(); + String what = prop_name.get_slicec('/', 2); if (properties.size() == idx && what == "path") { ERR_FAIL_COND_V(p_value.get_type() != Variant::NODE_PATH, false); @@ -72,11 +72,11 @@ bool SceneReplicationConfig::_set(const StringName &p_name, const Variant &p_val } bool SceneReplicationConfig::_get(const StringName &p_name, Variant &r_ret) const { - String name = p_name; + String prop_name = p_name; - if (name.begins_with("properties/")) { - int idx = name.get_slicec('/', 1).to_int(); - String what = name.get_slicec('/', 2); + if (prop_name.begins_with("properties/")) { + int idx = prop_name.get_slicec('/', 1).to_int(); + String what = prop_name.get_slicec('/', 2); ERR_FAIL_INDEX_V(idx, properties.size(), false); const ReplicationProperty &prop = properties[idx]; if (what == "path") { diff --git a/modules/multiplayer/scene_replication_interface.cpp b/modules/multiplayer/scene_replication_interface.cpp index 6e3dbfab47..f1bab7327a 100644 --- a/modules/multiplayer/scene_replication_interface.cpp +++ b/modules/multiplayer/scene_replication_interface.cpp @@ -30,56 +30,96 @@ #include "scene_replication_interface.h" +#include "scene_multiplayer.h" + #include "core/io/marshalls.h" #include "scene/main/node.h" - -#include "multiplayer_spawner.h" -#include "multiplayer_synchronizer.h" -#include "scene_multiplayer.h" +#include "scene/scene_string_names.h" #define MAKE_ROOM(m_amount) \ if (packet_cache.size() < m_amount) \ packet_cache.resize(m_amount); -void SceneReplicationInterface::_free_remotes(int p_id) { - const HashMap<uint32_t, ObjectID> remotes = rep_state->peer_get_remotes(p_id); - for (const KeyValue<uint32_t, ObjectID> &E : remotes) { - Node *node = rep_state->get_node(E.value); +SceneReplicationInterface::TrackedNode &SceneReplicationInterface::_track(const ObjectID &p_id) { + if (!tracked_nodes.has(p_id)) { + tracked_nodes[p_id] = TrackedNode(p_id); + Node *node = get_id_as<Node>(p_id); + node->connect(SceneStringNames::get_singleton()->tree_exited, callable_mp(this, &SceneReplicationInterface::_untrack).bind(p_id), Node::CONNECT_ONE_SHOT); + } + return tracked_nodes[p_id]; +} + +void SceneReplicationInterface::_untrack(const ObjectID &p_id) { + if (!tracked_nodes.has(p_id)) { + return; + } + uint32_t net_id = tracked_nodes[p_id].net_id; + uint32_t peer = tracked_nodes[p_id].remote_peer; + tracked_nodes.erase(p_id); + // If it was spawned by a remote, remove it from the received nodes. + if (peer && peers_info.has(peer)) { + peers_info[peer].recv_nodes.erase(net_id); + } + // If we spawned or synced it, we need to remove it from any peer it was sent to. + if (net_id || peer == 0) { + for (KeyValue<int, PeerInfo> &E : peers_info) { + E.value.spawn_nodes.erase(p_id); + } + } +} + +void SceneReplicationInterface::_free_remotes(const PeerInfo &p_info) { + for (const KeyValue<uint32_t, ObjectID> &E : p_info.recv_nodes) { + Node *node = tracked_nodes.has(E.value) ? get_id_as<Node>(E.value) : nullptr; ERR_CONTINUE(!node); - node->queue_delete(); + node->queue_free(); } } void SceneReplicationInterface::on_peer_change(int p_id, bool p_connected) { if (p_connected) { - rep_state->on_peer_change(p_id, p_connected); - for (const ObjectID &oid : rep_state->get_spawned_nodes()) { + peers_info[p_id] = PeerInfo(); + for (const ObjectID &oid : spawned_nodes) { _update_spawn_visibility(p_id, oid); } - for (const ObjectID &oid : rep_state->get_synced_nodes()) { - MultiplayerSynchronizer *sync = rep_state->get_synchronizer(oid); - ERR_CONTINUE(!sync); // ERR_BUG - if (sync->is_multiplayer_authority()) { - _update_sync_visibility(p_id, oid); - } + for (const ObjectID &oid : sync_nodes) { + _update_sync_visibility(p_id, get_id_as<MultiplayerSynchronizer>(oid)); } } else { - _free_remotes(p_id); - rep_state->on_peer_change(p_id, p_connected); + ERR_FAIL_COND(!peers_info.has(p_id)); + _free_remotes(peers_info[p_id]); + peers_info.erase(p_id); } } void SceneReplicationInterface::on_reset() { - for (int pid : rep_state->get_peers()) { - _free_remotes(pid); + for (const KeyValue<int, PeerInfo> &E : peers_info) { + _free_remotes(E.value); } - rep_state->reset(); + peers_info.clear(); + // Tracked nodes are cleared on deletion, here we only reset the ids so they can be later re-assigned. + for (KeyValue<ObjectID, TrackedNode> &E : tracked_nodes) { + TrackedNode &tobj = E.value; + tobj.net_id = 0; + tobj.remote_peer = 0; + } + for (const ObjectID &oid : sync_nodes) { + MultiplayerSynchronizer *sync = get_id_as<MultiplayerSynchronizer>(oid); + ERR_CONTINUE(!sync); + sync->reset(); + } + last_net_id = 0; } void SceneReplicationInterface::on_network_process() { uint64_t msec = OS::get_singleton()->get_ticks_msec(); - for (int peer : rep_state->get_peers()) { - _send_sync(peer, msec); + for (KeyValue<int, PeerInfo> &E : peers_info) { + const HashSet<ObjectID> to_sync = E.value.sync_nodes; + if (to_sync.is_empty()) { + continue; // Nothing to sync + } + uint16_t sync_net_time = ++E.value.last_sent_sync; + _send_sync(E.key, to_sync, sync_net_time, msec); } } @@ -88,14 +128,19 @@ Error SceneReplicationInterface::on_spawn(Object *p_obj, Variant p_config) { ERR_FAIL_COND_V(!node || p_config.get_type() != Variant::OBJECT, ERR_INVALID_PARAMETER); MultiplayerSpawner *spawner = Object::cast_to<MultiplayerSpawner>(p_config.get_validated_object()); ERR_FAIL_COND_V(!spawner, ERR_INVALID_PARAMETER); - Error err = rep_state->config_add_spawn(node, spawner); - ERR_FAIL_COND_V(err != OK, err); + // Track node. const ObjectID oid = node->get_instance_id(); + TrackedNode &tobj = _track(oid); + ERR_FAIL_COND_V(tobj.spawner != ObjectID(), ERR_ALREADY_IN_USE); + tobj.spawner = spawner->get_instance_id(); + spawned_nodes.insert(oid); + if (multiplayer->has_multiplayer_peer() && spawner->is_multiplayer_authority()) { - rep_state->ensure_net_id(oid); + if (tobj.net_id == 0) { + tobj.net_id = ++last_net_id; + } _update_spawn_visibility(0, oid); } - ERR_FAIL_COND_V(err != OK, err); return OK; } @@ -109,14 +154,22 @@ Error SceneReplicationInterface::on_despawn(Object *p_obj, Variant p_config) { Error err = _make_despawn_packet(node, len); ERR_FAIL_COND_V(err != OK, ERR_BUG); const ObjectID oid = p_obj->get_instance_id(); - for (int pid : rep_state->get_peers()) { - if (!rep_state->is_peer_spawn(pid, oid)) { + for (const KeyValue<int, PeerInfo> &E : peers_info) { + if (!E.value.spawn_nodes.has(oid)) { continue; } - _send_raw(packet_cache.ptr(), len, pid, true); + _send_raw(packet_cache.ptr(), len, E.key, true); } // Also remove spawner tracking from the replication state. - return rep_state->config_del_spawn(node, spawner); + ERR_FAIL_COND_V(!tracked_nodes.has(oid), ERR_INVALID_PARAMETER); + TrackedNode &tobj = _track(oid); + ERR_FAIL_COND_V(tobj.spawner != spawner->get_instance_id(), ERR_INVALID_PARAMETER); + tobj.spawner = ObjectID(); + spawned_nodes.erase(oid); + for (KeyValue<int, PeerInfo> &E : peers_info) { + E.value.spawn_nodes.erase(oid); + } + return OK; } Error SceneReplicationInterface::on_replication_start(Object *p_obj, Variant p_config) { @@ -125,25 +178,40 @@ Error SceneReplicationInterface::on_replication_start(Object *p_obj, Variant p_c MultiplayerSynchronizer *sync = Object::cast_to<MultiplayerSynchronizer>(p_config.get_validated_object()); ERR_FAIL_COND_V(!sync, ERR_INVALID_PARAMETER); - // Add to synchronizer list and setup visibility. - rep_state->config_add_sync(node, sync); - const ObjectID oid = node->get_instance_id(); - sync->connect("visibility_changed", callable_mp(this, &SceneReplicationInterface::_visibility_changed).bind(oid)); - if (multiplayer->has_multiplayer_peer() && sync->is_multiplayer_authority()) { - _update_sync_visibility(0, oid); - } - - // Try to apply initial state if spawning (hack to apply if before ready). - if (pending_spawn == p_obj->get_instance_id()) { - pending_spawn = ObjectID(); // Make sure this only happens once. - const List<NodePath> props = sync->get_replication_config()->get_spawn_properties(); - Vector<Variant> vars; - vars.resize(props.size()); - int consumed; - Error err = MultiplayerAPI::decode_and_decompress_variants(vars, pending_buffer, pending_buffer_size, consumed); - ERR_FAIL_COND_V(err, err); - err = MultiplayerSynchronizer::set_state(props, node, vars); - ERR_FAIL_COND_V(err, err); + // Add to synchronizer list. + TrackedNode &tobj = _track(p_obj->get_instance_id()); + const ObjectID sid = sync->get_instance_id(); + tobj.synchronizers.insert(sid); + sync_nodes.insert(sid); + + // Update visibility. + sync->connect("visibility_changed", callable_mp(this, &SceneReplicationInterface::_visibility_changed).bind(sync->get_instance_id())); + _update_sync_visibility(0, sync); + + if (pending_spawn == p_obj->get_instance_id() && sync->get_multiplayer_authority() == pending_spawn_remote) { + // Try to apply synchronizer Net ID + ERR_FAIL_COND_V_MSG(pending_sync_net_ids.is_empty(), ERR_INVALID_DATA, vformat("The MultiplayerSynchronizer at path \"%s\" is unable to process the pending spawn since it has no network ID. This might happen when changing the multiplayer authority during the \"_ready\" callback. Make sure to only change the authority of multiplayer synchronizers during \"_enter_tree\" or the \"_spawn_custom\" callback of their multiplayer spawner.", sync->get_path())); + ERR_FAIL_COND_V(!peers_info.has(pending_spawn_remote), ERR_INVALID_DATA); + uint32_t net_id = pending_sync_net_ids[0]; + pending_sync_net_ids.pop_front(); + peers_info[pending_spawn_remote].recv_sync_ids[net_id] = sync->get_instance_id(); + + // Try to apply spawn state (before ready). + if (pending_buffer_size > 0) { + ERR_FAIL_COND_V(!node || sync->get_replication_config().is_null(), ERR_UNCONFIGURED); + int consumed = 0; + const List<NodePath> props = sync->get_replication_config()->get_spawn_properties(); + Vector<Variant> vars; + vars.resize(props.size()); + Error err = MultiplayerAPI::decode_and_decompress_variants(vars, pending_buffer, pending_buffer_size, consumed); + ERR_FAIL_COND_V(err, err); + if (consumed > 0) { + pending_buffer += consumed; + pending_buffer_size -= consumed; + err = MultiplayerSynchronizer::set_state(props, node, vars); + ERR_FAIL_COND_V(err, err); + } + } } return OK; } @@ -154,59 +222,98 @@ Error SceneReplicationInterface::on_replication_stop(Object *p_obj, Variant p_co MultiplayerSynchronizer *sync = Object::cast_to<MultiplayerSynchronizer>(p_config.get_validated_object()); ERR_FAIL_COND_V(!sync, ERR_INVALID_PARAMETER); sync->disconnect("visibility_changed", callable_mp(this, &SceneReplicationInterface::_visibility_changed)); - return rep_state->config_del_sync(node, sync); + // Untrack synchronizer. + const ObjectID oid = node->get_instance_id(); + const ObjectID sid = sync->get_instance_id(); + ERR_FAIL_COND_V(!tracked_nodes.has(oid), ERR_INVALID_PARAMETER); + TrackedNode &tobj = _track(oid); + tobj.synchronizers.erase(sid); + sync_nodes.erase(sid); + for (KeyValue<int, PeerInfo> &E : peers_info) { + E.value.sync_nodes.erase(sid); + if (sync->get_net_id()) { + E.value.recv_sync_ids.erase(sync->get_net_id()); + } + } + return OK; } -void SceneReplicationInterface::_visibility_changed(int p_peer, ObjectID p_oid) { - if (rep_state->is_spawned_node(p_oid)) { - _update_spawn_visibility(p_peer, p_oid); - } - if (rep_state->is_synced_node(p_oid)) { - _update_sync_visibility(p_peer, p_oid); +void SceneReplicationInterface::_visibility_changed(int p_peer, ObjectID p_sid) { + MultiplayerSynchronizer *sync = get_id_as<MultiplayerSynchronizer>(p_sid); + ERR_FAIL_COND(!sync); // Bug. + Node *node = sync->get_root_node(); + ERR_FAIL_COND(!node); // Bug. + const ObjectID oid = node->get_instance_id(); + if (spawned_nodes.has(oid)) { + _update_spawn_visibility(p_peer, oid); } + _update_sync_visibility(p_peer, sync); } -Error SceneReplicationInterface::_update_sync_visibility(int p_peer, const ObjectID &p_oid) { - MultiplayerSynchronizer *sync = rep_state->get_synchronizer(p_oid); - ERR_FAIL_COND_V(!sync || !sync->is_multiplayer_authority(), ERR_BUG); - bool is_visible = sync->is_visible_to(p_peer); +Error SceneReplicationInterface::_update_sync_visibility(int p_peer, MultiplayerSynchronizer *p_sync) { + ERR_FAIL_COND_V(!p_sync, ERR_BUG); + if (!multiplayer->has_multiplayer_peer() || !p_sync->is_multiplayer_authority()) { + return OK; + } + + const ObjectID &sid = p_sync->get_instance_id(); + bool is_visible = p_sync->is_visible_to(p_peer); if (p_peer == 0) { - for (int pid : rep_state->get_peers()) { + for (KeyValue<int, PeerInfo> &E : peers_info) { // Might be visible to this specific peer. - is_visible = is_visible || sync->is_visible_to(pid); - if (rep_state->is_peer_sync(pid, p_oid) == is_visible) { + bool is_visible_to_peer = is_visible || p_sync->is_visible_to(E.key); + if (is_visible_to_peer == E.value.sync_nodes.has(sid)) { continue; } - if (is_visible) { - rep_state->peer_add_sync(pid, p_oid); + if (is_visible_to_peer) { + E.value.sync_nodes.insert(sid); } else { - rep_state->peer_del_sync(pid, p_oid); + E.value.sync_nodes.erase(sid); } } return OK; } else { - if (is_visible == rep_state->is_peer_sync(p_peer, p_oid)) { + ERR_FAIL_COND_V(!peers_info.has(p_peer), ERR_INVALID_PARAMETER); + if (is_visible == peers_info[p_peer].sync_nodes.has(sid)) { return OK; } if (is_visible) { - return rep_state->peer_add_sync(p_peer, p_oid); + peers_info[p_peer].sync_nodes.insert(sid); } else { - return rep_state->peer_del_sync(p_peer, p_oid); + peers_info[p_peer].sync_nodes.erase(sid); } + return OK; } } Error SceneReplicationInterface::_update_spawn_visibility(int p_peer, const ObjectID &p_oid) { - MultiplayerSpawner *spawner = rep_state->get_spawner(p_oid); - MultiplayerSynchronizer *sync = rep_state->get_synchronizer(p_oid); - Node *node = Object::cast_to<Node>(ObjectDB::get_instance(p_oid)); + const TrackedNode *tnode = tracked_nodes.getptr(p_oid); + ERR_FAIL_COND_V(!tnode, ERR_BUG); + MultiplayerSpawner *spawner = get_id_as<MultiplayerSpawner>(tnode->spawner); + Node *node = get_id_as<Node>(p_oid); ERR_FAIL_COND_V(!node || !spawner || !spawner->is_multiplayer_authority(), ERR_BUG); - bool is_visible = !sync || sync->is_visible_to(p_peer); + ERR_FAIL_COND_V(!tracked_nodes.has(p_oid), ERR_BUG); + const HashSet<ObjectID> synchronizers = tracked_nodes[p_oid].synchronizers; + bool is_visible = true; + for (const ObjectID &sid : synchronizers) { + MultiplayerSynchronizer *sync = get_id_as<MultiplayerSynchronizer>(sid); + ERR_CONTINUE(!sync); + if (!sync->is_multiplayer_authority()) { + continue; + } + // Spawn visibility is composed using OR when multiple synchronizers are present. + if (sync->is_visible_to(p_peer)) { + is_visible = true; + break; + } + is_visible = false; + } // Spawn (and despawn) when needed. HashSet<int> to_spawn; HashSet<int> to_despawn; if (p_peer) { - if (is_visible == rep_state->is_peer_spawn(p_peer, p_oid)) { + ERR_FAIL_COND_V(!peers_info.has(p_peer), ERR_INVALID_PARAMETER); + if (is_visible == peers_info[p_peer].spawn_nodes.has(p_oid)) { return OK; } if (is_visible) { @@ -216,33 +323,37 @@ Error SceneReplicationInterface::_update_spawn_visibility(int p_peer, const Obje } } else { // Check visibility for each peers. - for (int pid : rep_state->get_peers()) { - bool peer_visible = is_visible || sync->is_visible_to(pid); - if (peer_visible == rep_state->is_peer_spawn(pid, p_oid)) { - continue; - } - if (peer_visible) { - to_spawn.insert(pid); + for (const KeyValue<int, PeerInfo> &E : peers_info) { + if (is_visible) { + // This is fast, since the the object is visible to everyone, we don't need to check each peer. + if (E.value.spawn_nodes.has(p_oid)) { + // Already spawned. + continue; + } + to_spawn.insert(E.key); } else { - to_despawn.insert(pid); + // Need to check visibility for each peer. + _update_spawn_visibility(E.key, p_oid); } } } if (to_spawn.size()) { int len = 0; - _make_spawn_packet(node, len); + _make_spawn_packet(node, spawner, len); for (int pid : to_spawn) { + ERR_CONTINUE(!peers_info.has(pid)); int path_id; multiplayer->get_path_cache()->send_object_cache(spawner, pid, path_id); _send_raw(packet_cache.ptr(), len, pid, true); - rep_state->peer_add_spawn(pid, p_oid); + peers_info[pid].spawn_nodes.insert(p_oid); } } if (to_despawn.size()) { int len = 0; _make_despawn_packet(node, len); for (int pid : to_despawn) { - rep_state->peer_del_spawn(pid, p_oid); + ERR_CONTINUE(!peers_info.has(pid)); + peers_info[pid].spawn_nodes.erase(p_oid); _send_raw(packet_cache.ptr(), len, pid, true); } } @@ -259,26 +370,25 @@ Error SceneReplicationInterface::_send_raw(const uint8_t *p_buffer, int p_size, #endif Ref<MultiplayerPeer> peer = multiplayer->get_multiplayer_peer(); - peer->set_target_peer(p_peer); peer->set_transfer_channel(0); peer->set_transfer_mode(p_reliable ? MultiplayerPeer::TRANSFER_MODE_RELIABLE : MultiplayerPeer::TRANSFER_MODE_UNRELIABLE); - return peer->put_packet(p_buffer, p_size); + return multiplayer->send_command(p_peer, p_buffer, p_size); } -Error SceneReplicationInterface::_make_spawn_packet(Node *p_node, int &r_len) { - ERR_FAIL_COND_V(!multiplayer, ERR_BUG); +Error SceneReplicationInterface::_make_spawn_packet(Node *p_node, MultiplayerSpawner *p_spawner, int &r_len) { + ERR_FAIL_COND_V(!multiplayer || !p_node || !p_spawner, ERR_BUG); const ObjectID oid = p_node->get_instance_id(); - MultiplayerSpawner *spawner = rep_state->get_spawner(oid); - ERR_FAIL_COND_V(!spawner || !p_node, ERR_BUG); + const TrackedNode *tnode = tracked_nodes.getptr(oid); + ERR_FAIL_COND_V(!tnode, ERR_INVALID_PARAMETER); - uint32_t nid = rep_state->get_net_id(oid); + uint32_t nid = tnode->net_id; ERR_FAIL_COND_V(!nid, ERR_UNCONFIGURED); // Prepare custom arg and scene_id - uint8_t scene_id = spawner->find_spawnable_scene_index_from_object(oid); + uint8_t scene_id = p_spawner->find_spawnable_scene_index_from_object(oid); bool is_custom = scene_id == MultiplayerSpawner::INVALID_ID; - Variant spawn_arg = spawner->get_spawn_argument(oid); + Variant spawn_arg = p_spawner->get_spawn_argument(oid); int spawn_arg_size = 0; if (is_custom) { Error err = MultiplayerAPI::encode_and_compress_variant(spawn_arg, nullptr, spawn_arg_size, false); @@ -286,31 +396,51 @@ Error SceneReplicationInterface::_make_spawn_packet(Node *p_node, int &r_len) { } // Prepare spawn state. + List<NodePath> state_props; + List<uint32_t> sync_ids; + const HashSet<ObjectID> synchronizers = tnode->synchronizers; + for (const ObjectID &sid : synchronizers) { + MultiplayerSynchronizer *sync = get_id_as<MultiplayerSynchronizer>(sid); + if (!sync->is_multiplayer_authority()) { + continue; + } + ERR_CONTINUE(!sync); + ERR_FAIL_COND_V(sync->get_replication_config().is_null(), ERR_BUG); + for (const NodePath &prop : sync->get_replication_config()->get_spawn_properties()) { + state_props.push_back(prop); + } + // Ensure the synchronizer has an ID. + if (sync->get_net_id() == 0) { + sync->set_net_id(++last_net_id); + } + sync_ids.push_back(sync->get_net_id()); + } int state_size = 0; Vector<Variant> state_vars; Vector<const Variant *> state_varp; - MultiplayerSynchronizer *synchronizer = rep_state->get_synchronizer(oid); - if (synchronizer) { - ERR_FAIL_COND_V(synchronizer->get_replication_config().is_null(), ERR_BUG); - const List<NodePath> props = synchronizer->get_replication_config()->get_spawn_properties(); - Error err = MultiplayerSynchronizer::get_state(props, p_node, state_vars, state_varp); + if (state_props.size()) { + Error err = MultiplayerSynchronizer::get_state(state_props, p_node, state_vars, state_varp); ERR_FAIL_COND_V_MSG(err != OK, err, "Unable to retrieve spawn state."); err = MultiplayerAPI::encode_and_compress_variants(state_varp.ptrw(), state_varp.size(), nullptr, state_size); ERR_FAIL_COND_V_MSG(err != OK, err, "Unable to encode spawn state."); } // Encode scene ID, path ID, net ID, node name. - int path_id = multiplayer->get_path_cache()->make_object_cache(spawner); + int path_id = multiplayer->get_path_cache()->make_object_cache(p_spawner); CharString cname = p_node->get_name().operator String().utf8(); int nlen = encode_cstring(cname.get_data(), nullptr); - MAKE_ROOM(1 + 1 + 4 + 4 + 4 + nlen + (is_custom ? 4 + spawn_arg_size : 0) + state_size); + MAKE_ROOM(1 + 1 + 4 + 4 + 4 + 4 * sync_ids.size() + 4 + nlen + (is_custom ? 4 + spawn_arg_size : 0) + state_size); uint8_t *ptr = packet_cache.ptrw(); ptr[0] = (uint8_t)SceneMultiplayer::NETWORK_COMMAND_SPAWN; ptr[1] = scene_id; int ofs = 2; ofs += encode_uint32(path_id, &ptr[ofs]); ofs += encode_uint32(nid, &ptr[ofs]); + ofs += encode_uint32(sync_ids.size(), &ptr[ofs]); ofs += encode_uint32(nlen, &ptr[ofs]); + for (uint32_t snid : sync_ids) { + ofs += encode_uint32(snid, &ptr[ofs]); + } ofs += encode_cstring(cname.get_data(), &ptr[ofs]); // Write args if (is_custom) { @@ -331,18 +461,20 @@ Error SceneReplicationInterface::_make_spawn_packet(Node *p_node, int &r_len) { Error SceneReplicationInterface::_make_despawn_packet(Node *p_node, int &r_len) { const ObjectID oid = p_node->get_instance_id(); + const TrackedNode *tnode = tracked_nodes.getptr(oid); + ERR_FAIL_COND_V(!tnode, ERR_INVALID_PARAMETER); MAKE_ROOM(5); uint8_t *ptr = packet_cache.ptrw(); ptr[0] = (uint8_t)SceneMultiplayer::NETWORK_COMMAND_DESPAWN; int ofs = 1; - uint32_t nid = rep_state->get_net_id(oid); + uint32_t nid = tnode->net_id; ofs += encode_uint32(nid, &ptr[ofs]); r_len = ofs; return OK; } Error SceneReplicationInterface::on_spawn_receive(int p_from, const uint8_t *p_buffer, int p_buffer_len) { - ERR_FAIL_COND_V_MSG(p_buffer_len < 14, ERR_INVALID_DATA, "Invalid spawn packet received"); + ERR_FAIL_COND_V_MSG(p_buffer_len < 18, ERR_INVALID_DATA, "Invalid spawn packet received"); int ofs = 1; // The spawn/despawn command. uint8_t scene_id = p_buffer[ofs]; ofs += 1; @@ -354,9 +486,16 @@ Error SceneReplicationInterface::on_spawn_receive(int p_from, const uint8_t *p_b uint32_t net_id = decode_uint32(&p_buffer[ofs]); ofs += 4; + uint32_t sync_len = decode_uint32(&p_buffer[ofs]); + ofs += 4; uint32_t name_len = decode_uint32(&p_buffer[ofs]); ofs += 4; - ERR_FAIL_COND_V_MSG(name_len > uint32_t(p_buffer_len - ofs), ERR_INVALID_DATA, vformat("Invalid spawn packet size: %d, wants: %d", p_buffer_len, ofs + name_len)); + ERR_FAIL_COND_V_MSG(name_len + (sync_len * 4) > uint32_t(p_buffer_len - ofs), ERR_INVALID_DATA, vformat("Invalid spawn packet size: %d, wants: %d", p_buffer_len, ofs + name_len + (sync_len * 4))); + List<uint32_t> sync_ids; + for (uint32_t i = 0; i < sync_len; i++) { + sync_ids.push_back(decode_uint32(&p_buffer[ofs])); + ofs += 4; + } ERR_FAIL_COND_V_MSG(name_len < 1, ERR_INVALID_DATA, "Zero spawn name size."); // We need to make sure no trickery happens here, but we want to allow autogenerated ("@") node names. @@ -387,20 +526,35 @@ Error SceneReplicationInterface::on_spawn_receive(int p_from, const uint8_t *p_b } ERR_FAIL_COND_V(!node, ERR_UNAUTHORIZED); node->set_name(name); - rep_state->peer_add_remote(p_from, net_id, node, spawner); + + // Add and track remote + ERR_FAIL_COND_V(!peers_info.has(p_from), ERR_UNAVAILABLE); + ERR_FAIL_COND_V(peers_info[p_from].recv_nodes.has(net_id), ERR_ALREADY_IN_USE); + ObjectID oid = node->get_instance_id(); + TrackedNode &tobj = _track(oid); + tobj.spawner = spawner->get_instance_id(); + tobj.net_id = net_id; + tobj.remote_peer = p_from; + peers_info[p_from].recv_nodes[net_id] = oid; + // The initial state will be applied during the sync config (i.e. before _ready). - int state_len = p_buffer_len - ofs; - if (state_len) { - pending_spawn = node->get_instance_id(); - pending_buffer = &p_buffer[ofs]; - pending_buffer_size = state_len; - } + pending_spawn = node->get_instance_id(); + pending_spawn_remote = p_from; + pending_buffer_size = p_buffer_len - ofs; + pending_buffer = pending_buffer_size > 0 ? &p_buffer[ofs] : nullptr; + pending_sync_net_ids = sync_ids; + parent->add_child(node); spawner->emit_signal(SNAME("spawned"), node); pending_spawn = ObjectID(); + pending_spawn_remote = 0; pending_buffer = nullptr; pending_buffer_size = 0; + if (pending_sync_net_ids.size()) { + pending_sync_net_ids.clear(); + ERR_FAIL_V(ERR_INVALID_DATA); // Should have been consumed. + } return OK; } @@ -409,45 +563,48 @@ Error SceneReplicationInterface::on_despawn_receive(int p_from, const uint8_t *p int ofs = 1; // The spawn/despawn command. uint32_t net_id = decode_uint32(&p_buffer[ofs]); ofs += 4; - Node *node = nullptr; - Error err = rep_state->peer_del_remote(p_from, net_id, &node); - ERR_FAIL_COND_V(err != OK, err); + + // Untrack remote + ERR_FAIL_COND_V(!peers_info.has(p_from), ERR_UNAUTHORIZED); + PeerInfo &pinfo = peers_info[p_from]; + ERR_FAIL_COND_V(!pinfo.recv_nodes.has(net_id), ERR_UNAUTHORIZED); + Node *node = get_id_as<Node>(pinfo.recv_nodes[net_id]); ERR_FAIL_COND_V(!node, ERR_BUG); + pinfo.recv_nodes.erase(net_id); - MultiplayerSpawner *spawner = rep_state->get_spawner(node->get_instance_id()); + const ObjectID oid = node->get_instance_id(); + ERR_FAIL_COND_V(!tracked_nodes.has(oid), ERR_BUG); + MultiplayerSpawner *spawner = get_id_as<MultiplayerSpawner>(tracked_nodes[oid].spawner); ERR_FAIL_COND_V(!spawner, ERR_DOES_NOT_EXIST); ERR_FAIL_COND_V(p_from != spawner->get_multiplayer_authority(), ERR_UNAUTHORIZED); if (node->get_parent() != nullptr) { node->get_parent()->remove_child(node); } - node->queue_delete(); + node->queue_free(); spawner->emit_signal(SNAME("despawned"), node); return OK; } -void SceneReplicationInterface::_send_sync(int p_peer, uint64_t p_msec) { - const HashSet<ObjectID> &to_sync = rep_state->get_peer_sync_nodes(p_peer); - if (to_sync.is_empty()) { - return; - } +void SceneReplicationInterface::_send_sync(int p_peer, const HashSet<ObjectID> p_synchronizers, uint16_t p_sync_net_time, uint64_t p_msec) { MAKE_ROOM(sync_mtu); uint8_t *ptr = packet_cache.ptrw(); ptr[0] = SceneMultiplayer::NETWORK_COMMAND_SYNC; int ofs = 1; - ofs += encode_uint16(rep_state->peer_sync_next(p_peer), &ptr[1]); + ofs += encode_uint16(p_sync_net_time, &ptr[1]); // Can only send updates for already notified nodes. // This is a lazy implementation, we could optimize much more here with by grouping by replication config. - for (const ObjectID &oid : to_sync) { - if (!rep_state->update_sync_time(oid, p_msec)) { + for (const ObjectID &oid : p_synchronizers) { + MultiplayerSynchronizer *sync = get_id_as<MultiplayerSynchronizer>(oid); + ERR_CONTINUE(!sync || !sync->get_replication_config().is_valid() || !sync->is_multiplayer_authority()); + if (!sync->update_outbound_sync_time(p_msec)) { continue; // nothing to sync. } - MultiplayerSynchronizer *sync = rep_state->get_synchronizer(oid); - ERR_CONTINUE(!sync || !sync->get_replication_config().is_valid()); - Node *node = rep_state->get_node(oid); + + Node *node = sync->get_root_node(); ERR_CONTINUE(!node); - uint32_t net_id = rep_state->get_net_id(oid); + uint32_t net_id = sync->get_net_id(); if (net_id == 0 || (net_id & 0x80000000)) { int path_id = 0; bool verified = multiplayer->get_path_cache()->send_object_cache(sync, p_peer, path_id); @@ -455,7 +612,7 @@ void SceneReplicationInterface::_send_sync(int p_peer, uint64_t p_msec) { if (net_id == 0) { // First time path based ID. net_id = path_id | 0x80000000; - rep_state->set_net_id(oid, net_id | 0x80000000); + sync->set_net_id(net_id | 0x80000000); } if (!verified) { // The path based sync is not yet confirmed, skipping. @@ -478,7 +635,7 @@ void SceneReplicationInterface::_send_sync(int p_peer, uint64_t p_msec) { ofs = 3; } if (size) { - ofs += encode_uint32(rep_state->get_net_id(oid), &ptr[ofs]); + ofs += encode_uint32(sync->get_net_id(), &ptr[ofs]); ofs += encode_uint32(size, &ptr[ofs]); MultiplayerAPI::encode_and_compress_variants(varp.ptrw(), varp.size(), &ptr[ofs], size); ofs += size; @@ -494,33 +651,32 @@ Error SceneReplicationInterface::on_sync_receive(int p_from, const uint8_t *p_bu ERR_FAIL_COND_V_MSG(p_buffer_len < 11, ERR_INVALID_DATA, "Invalid sync packet received"); uint16_t time = decode_uint16(&p_buffer[1]); int ofs = 3; - rep_state->peer_sync_recv(p_from, time); while (ofs + 8 < p_buffer_len) { uint32_t net_id = decode_uint32(&p_buffer[ofs]); ofs += 4; uint32_t size = decode_uint32(&p_buffer[ofs]); ofs += 4; - Node *node = nullptr; + MultiplayerSynchronizer *sync = nullptr; if (net_id & 0x80000000) { - MultiplayerSynchronizer *sync = Object::cast_to<MultiplayerSynchronizer>(multiplayer->get_path_cache()->get_cached_object(p_from, net_id & 0x7FFFFFFF)); - ERR_FAIL_COND_V(!sync || sync->get_multiplayer_authority() != p_from, ERR_UNAUTHORIZED); - node = sync->get_node(sync->get_root_path()); - } else { - node = rep_state->peer_get_remote(p_from, net_id); + sync = Object::cast_to<MultiplayerSynchronizer>(multiplayer->get_path_cache()->get_cached_object(p_from, net_id & 0x7FFFFFFF)); + } else if (peers_info[p_from].recv_sync_ids.has(net_id)) { + const ObjectID &sid = peers_info[p_from].recv_sync_ids[net_id]; + sync = get_id_as<MultiplayerSynchronizer>(sid); } - if (!node) { + if (!sync) { // Not received yet. ofs += size; continue; } - const ObjectID oid = node->get_instance_id(); - if (!rep_state->update_last_node_sync(oid, time)) { + Node *node = sync->get_root_node(); + if (sync->get_multiplayer_authority() != p_from || !node) { + ERR_CONTINUE(true); + } + if (!sync->update_inbound_sync_time(time)) { // State is too old. ofs += size; continue; } - MultiplayerSynchronizer *sync = rep_state->get_synchronizer(oid); - ERR_FAIL_COND_V(!sync, ERR_BUG); ERR_FAIL_COND_V(size > uint32_t(p_buffer_len - ofs), ERR_BUG); const List<NodePath> props = sync->get_replication_config()->get_sync_properties(); Vector<Variant> vars; diff --git a/modules/multiplayer/scene_replication_interface.h b/modules/multiplayer/scene_replication_interface.h index 8981647429..c8bd96eb87 100644 --- a/modules/multiplayer/scene_replication_interface.h +++ b/modules/multiplayer/scene_replication_interface.h @@ -31,9 +31,10 @@ #ifndef SCENE_REPLICATION_INTERFACE_H #define SCENE_REPLICATION_INTERFACE_H -#include "scene/main/multiplayer_api.h" +#include "core/object/ref_counted.h" -#include "scene_replication_state.h" +#include "multiplayer_spawner.h" +#include "multiplayer_synchronizer.h" class SceneMultiplayer; @@ -41,25 +42,68 @@ class SceneReplicationInterface : public RefCounted { GDCLASS(SceneReplicationInterface, RefCounted); private: - void _send_sync(int p_peer, uint64_t p_msec); - Error _make_spawn_packet(Node *p_node, int &r_len); - Error _make_despawn_packet(Node *p_node, int &r_len); - Error _send_raw(const uint8_t *p_buffer, int p_size, int p_peer, bool p_reliable); + struct TrackedNode { + ObjectID id; + uint32_t net_id = 0; + uint32_t remote_peer = 0; + ObjectID spawner; + HashSet<ObjectID> synchronizers; - void _visibility_changed(int p_peer, ObjectID p_oid); - Error _update_sync_visibility(int p_peer, const ObjectID &p_oid); - Error _update_spawn_visibility(int p_peer, const ObjectID &p_oid); - void _free_remotes(int p_peer); + bool operator==(const ObjectID &p_other) { return id == p_other; } - Ref<SceneReplicationState> rep_state; - SceneMultiplayer *multiplayer = nullptr; - PackedByteArray packet_cache; - int sync_mtu = 1350; // Highly dependent on underlying protocol. + _FORCE_INLINE_ MultiplayerSpawner *get_spawner() const { return spawner.is_valid() ? Object::cast_to<MultiplayerSpawner>(ObjectDB::get_instance(spawner)) : nullptr; } + TrackedNode() {} + TrackedNode(const ObjectID &p_id) { id = p_id; } + TrackedNode(const ObjectID &p_id, uint32_t p_net_id) { + id = p_id; + net_id = p_net_id; + } + }; + + struct PeerInfo { + HashSet<ObjectID> sync_nodes; + HashSet<ObjectID> spawn_nodes; + HashMap<uint32_t, ObjectID> recv_sync_ids; + HashMap<uint32_t, ObjectID> recv_nodes; + uint16_t last_sent_sync = 0; + }; + + // Replication state. + HashMap<int, PeerInfo> peers_info; + uint32_t last_net_id = 0; + HashMap<ObjectID, TrackedNode> tracked_nodes; + HashSet<ObjectID> spawned_nodes; + HashSet<ObjectID> sync_nodes; - // An hack to apply the initial state before ready. + // Pending spawn information. ObjectID pending_spawn; + int pending_spawn_remote = 0; const uint8_t *pending_buffer = nullptr; int pending_buffer_size = 0; + List<uint32_t> pending_sync_net_ids; + + // Replicator config. + SceneMultiplayer *multiplayer = nullptr; + PackedByteArray packet_cache; + int sync_mtu = 1350; // Highly dependent on underlying protocol. + + TrackedNode &_track(const ObjectID &p_id); + void _untrack(const ObjectID &p_id); + + void _send_sync(int p_peer, const HashSet<ObjectID> p_synchronizers, uint16_t p_sync_net_time, uint64_t p_msec); + Error _make_spawn_packet(Node *p_node, MultiplayerSpawner *p_spawner, int &r_len); + Error _make_despawn_packet(Node *p_node, int &r_len); + Error _send_raw(const uint8_t *p_buffer, int p_size, int p_peer, bool p_reliable); + + void _visibility_changed(int p_peer, ObjectID p_oid); + Error _update_sync_visibility(int p_peer, MultiplayerSynchronizer *p_sync); + Error _update_spawn_visibility(int p_peer, const ObjectID &p_oid); + void _free_remotes(const PeerInfo &p_info); + + template <class T> + static T *get_id_as(const ObjectID &p_id) { + return p_id.is_valid() ? Object::cast_to<T>(ObjectDB::get_instance(p_id)) : nullptr; + } public: static void make_default(); @@ -78,7 +122,6 @@ public: Error on_sync_receive(int p_from, const uint8_t *p_buffer, int p_buffer_len); SceneReplicationInterface(SceneMultiplayer *p_multiplayer) { - rep_state.instantiate(); multiplayer = p_multiplayer; } }; diff --git a/modules/multiplayer/scene_replication_state.cpp b/modules/multiplayer/scene_replication_state.cpp deleted file mode 100644 index fbcf0acadb..0000000000 --- a/modules/multiplayer/scene_replication_state.cpp +++ /dev/null @@ -1,267 +0,0 @@ -/*************************************************************************/ -/* scene_replication_state.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "scene_replication_state.h" - -#include "scene/scene_string_names.h" - -#include "multiplayer_spawner.h" -#include "multiplayer_synchronizer.h" - -SceneReplicationState::TrackedNode &SceneReplicationState::_track(const ObjectID &p_id) { - if (!tracked_nodes.has(p_id)) { - tracked_nodes[p_id] = TrackedNode(p_id); - Node *node = Object::cast_to<Node>(ObjectDB::get_instance(p_id)); - node->connect(SceneStringNames::get_singleton()->tree_exited, callable_mp(this, &SceneReplicationState::_untrack).bind(p_id), Node::CONNECT_ONE_SHOT); - } - return tracked_nodes[p_id]; -} - -void SceneReplicationState::_untrack(const ObjectID &p_id) { - if (tracked_nodes.has(p_id)) { - uint32_t net_id = tracked_nodes[p_id].net_id; - uint32_t peer = tracked_nodes[p_id].remote_peer; - tracked_nodes.erase(p_id); - // If it was spawned by a remote, remove it from the received nodes. - if (peer && peers_info.has(peer)) { - peers_info[peer].recv_nodes.erase(net_id); - } - // If we spawned or synced it, we need to remove it from any peer it was sent to. - if (net_id || peer == 0) { - for (KeyValue<int, PeerInfo> &E : peers_info) { - E.value.sync_nodes.erase(p_id); - E.value.spawn_nodes.erase(p_id); - } - } - } -} - -const HashMap<uint32_t, ObjectID> SceneReplicationState::peer_get_remotes(int p_peer) const { - return peers_info.has(p_peer) ? peers_info[p_peer].recv_nodes : HashMap<uint32_t, ObjectID>(); -} - -bool SceneReplicationState::update_last_node_sync(const ObjectID &p_id, uint16_t p_time) { - TrackedNode *tnode = tracked_nodes.getptr(p_id); - ERR_FAIL_COND_V(!tnode, false); - if (p_time <= tnode->last_sync && tnode->last_sync - p_time < 32767) { - return false; - } - tnode->last_sync = p_time; - return true; -} - -bool SceneReplicationState::update_sync_time(const ObjectID &p_id, uint64_t p_msec) { - TrackedNode *tnode = tracked_nodes.getptr(p_id); - ERR_FAIL_COND_V(!tnode, false); - MultiplayerSynchronizer *sync = get_synchronizer(p_id); - if (!sync) { - return false; - } - if (tnode->last_sync_msec == p_msec) { - return true; - } - if (p_msec >= tnode->last_sync_msec + sync->get_replication_interval_msec()) { - tnode->last_sync_msec = p_msec; - return true; - } - return false; -} - -uint32_t SceneReplicationState::get_net_id(const ObjectID &p_id) const { - const TrackedNode *tnode = tracked_nodes.getptr(p_id); - ERR_FAIL_COND_V(!tnode, 0); - return tnode->net_id; -} - -void SceneReplicationState::set_net_id(const ObjectID &p_id, uint32_t p_net_id) { - TrackedNode *tnode = tracked_nodes.getptr(p_id); - ERR_FAIL_COND(!tnode); - tnode->net_id = p_net_id; -} - -uint32_t SceneReplicationState::ensure_net_id(const ObjectID &p_id) { - TrackedNode *tnode = tracked_nodes.getptr(p_id); - ERR_FAIL_COND_V(!tnode, 0); - if (tnode->net_id == 0) { - tnode->net_id = ++last_net_id; - } - return tnode->net_id; -} - -void SceneReplicationState::on_peer_change(int p_peer, bool p_connected) { - if (p_connected) { - peers_info[p_peer] = PeerInfo(); - known_peers.insert(p_peer); - } else { - peers_info.erase(p_peer); - known_peers.erase(p_peer); - } -} - -void SceneReplicationState::reset() { - peers_info.clear(); - known_peers.clear(); - // Tracked nodes are cleared on deletion, here we only reset the ids so they can be later re-assigned. - for (KeyValue<ObjectID, TrackedNode> &E : tracked_nodes) { - TrackedNode &tobj = E.value; - tobj.net_id = 0; - tobj.remote_peer = 0; - tobj.last_sync = 0; - } -} - -Error SceneReplicationState::config_add_spawn(Node *p_node, MultiplayerSpawner *p_spawner) { - const ObjectID oid = p_node->get_instance_id(); - TrackedNode &tobj = _track(oid); - ERR_FAIL_COND_V(tobj.spawner != ObjectID(), ERR_ALREADY_IN_USE); - tobj.spawner = p_spawner->get_instance_id(); - spawned_nodes.insert(oid); - return OK; -} - -Error SceneReplicationState::config_del_spawn(Node *p_node, MultiplayerSpawner *p_spawner) { - const ObjectID oid = p_node->get_instance_id(); - ERR_FAIL_COND_V(!is_tracked(oid), ERR_INVALID_PARAMETER); - TrackedNode &tobj = _track(oid); - ERR_FAIL_COND_V(tobj.spawner != p_spawner->get_instance_id(), ERR_INVALID_PARAMETER); - tobj.spawner = ObjectID(); - spawned_nodes.erase(oid); - for (KeyValue<int, PeerInfo> &E : peers_info) { - E.value.spawn_nodes.erase(oid); - } - return OK; -} - -Error SceneReplicationState::config_add_sync(Node *p_node, MultiplayerSynchronizer *p_sync) { - const ObjectID oid = p_node->get_instance_id(); - TrackedNode &tobj = _track(oid); - ERR_FAIL_COND_V(tobj.synchronizer != ObjectID(), ERR_ALREADY_IN_USE); - tobj.synchronizer = p_sync->get_instance_id(); - synced_nodes.insert(oid); - return OK; -} - -Error SceneReplicationState::config_del_sync(Node *p_node, MultiplayerSynchronizer *p_sync) { - const ObjectID oid = p_node->get_instance_id(); - ERR_FAIL_COND_V(!is_tracked(oid), ERR_INVALID_PARAMETER); - TrackedNode &tobj = _track(oid); - ERR_FAIL_COND_V(tobj.synchronizer != p_sync->get_instance_id(), ERR_INVALID_PARAMETER); - tobj.synchronizer = ObjectID(); - synced_nodes.erase(oid); - for (KeyValue<int, PeerInfo> &E : peers_info) { - E.value.sync_nodes.erase(oid); - } - return OK; -} - -Error SceneReplicationState::peer_add_sync(int p_peer, const ObjectID &p_id) { - ERR_FAIL_COND_V(!peers_info.has(p_peer), ERR_INVALID_PARAMETER); - peers_info[p_peer].sync_nodes.insert(p_id); - return OK; -} - -Error SceneReplicationState::peer_del_sync(int p_peer, const ObjectID &p_id) { - ERR_FAIL_COND_V(!peers_info.has(p_peer), ERR_INVALID_PARAMETER); - peers_info[p_peer].sync_nodes.erase(p_id); - return OK; -} - -const HashSet<ObjectID> SceneReplicationState::get_peer_sync_nodes(int p_peer) { - ERR_FAIL_COND_V(!peers_info.has(p_peer), HashSet<ObjectID>()); - return peers_info[p_peer].sync_nodes; -} - -bool SceneReplicationState::is_peer_sync(int p_peer, const ObjectID &p_id) const { - ERR_FAIL_COND_V(!peers_info.has(p_peer), false); - return peers_info[p_peer].sync_nodes.has(p_id); -} - -Error SceneReplicationState::peer_add_spawn(int p_peer, const ObjectID &p_id) { - ERR_FAIL_COND_V(!peers_info.has(p_peer), ERR_INVALID_PARAMETER); - peers_info[p_peer].spawn_nodes.insert(p_id); - return OK; -} - -Error SceneReplicationState::peer_del_spawn(int p_peer, const ObjectID &p_id) { - ERR_FAIL_COND_V(!peers_info.has(p_peer), ERR_INVALID_PARAMETER); - peers_info[p_peer].spawn_nodes.erase(p_id); - return OK; -} - -const HashSet<ObjectID> SceneReplicationState::get_peer_spawn_nodes(int p_peer) { - ERR_FAIL_COND_V(!peers_info.has(p_peer), HashSet<ObjectID>()); - return peers_info[p_peer].spawn_nodes; -} - -bool SceneReplicationState::is_peer_spawn(int p_peer, const ObjectID &p_id) const { - ERR_FAIL_COND_V(!peers_info.has(p_peer), false); - return peers_info[p_peer].spawn_nodes.has(p_id); -} - -Node *SceneReplicationState::peer_get_remote(int p_peer, uint32_t p_net_id) { - PeerInfo *info = peers_info.getptr(p_peer); - return info && info->recv_nodes.has(p_net_id) ? Object::cast_to<Node>(ObjectDB::get_instance(info->recv_nodes[p_net_id])) : nullptr; -} - -Error SceneReplicationState::peer_add_remote(int p_peer, uint32_t p_net_id, Node *p_node, MultiplayerSpawner *p_spawner) { - ERR_FAIL_COND_V(!p_node || !p_spawner, ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V(!peers_info.has(p_peer), ERR_UNAVAILABLE); - PeerInfo &pinfo = peers_info[p_peer]; - ObjectID oid = p_node->get_instance_id(); - TrackedNode &tobj = _track(oid); - tobj.spawner = p_spawner->get_instance_id(); - tobj.net_id = p_net_id; - tobj.remote_peer = p_peer; - tobj.last_sync = pinfo.last_recv_sync; - // Also track as a remote. - ERR_FAIL_COND_V(pinfo.recv_nodes.has(p_net_id), ERR_ALREADY_IN_USE); - pinfo.recv_nodes[p_net_id] = oid; - return OK; -} - -Error SceneReplicationState::peer_del_remote(int p_peer, uint32_t p_net_id, Node **r_node) { - ERR_FAIL_COND_V(!peers_info.has(p_peer), ERR_UNAUTHORIZED); - PeerInfo &info = peers_info[p_peer]; - ERR_FAIL_COND_V(!info.recv_nodes.has(p_net_id), ERR_UNAUTHORIZED); - *r_node = Object::cast_to<Node>(ObjectDB::get_instance(info.recv_nodes[p_net_id])); - info.recv_nodes.erase(p_net_id); - return OK; -} - -uint16_t SceneReplicationState::peer_sync_next(int p_peer) { - ERR_FAIL_COND_V(!peers_info.has(p_peer), 0); - PeerInfo &info = peers_info[p_peer]; - return ++info.last_sent_sync; -} - -void SceneReplicationState::peer_sync_recv(int p_peer, uint16_t p_time) { - ERR_FAIL_COND(!peers_info.has(p_peer)); - peers_info[p_peer].last_recv_sync = p_time; -} diff --git a/modules/multiplayer/scene_replication_state.h b/modules/multiplayer/scene_replication_state.h deleted file mode 100644 index bdff6ae3b7..0000000000 --- a/modules/multiplayer/scene_replication_state.h +++ /dev/null @@ -1,135 +0,0 @@ -/*************************************************************************/ -/* scene_replication_state.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 SCENE_REPLICATION_STATE_H -#define SCENE_REPLICATION_STATE_H - -#include "core/object/ref_counted.h" - -#include "multiplayer_spawner.h" -#include "multiplayer_synchronizer.h" - -class MultiplayerSpawner; -class MultiplayerSynchronizer; -class Node; - -class SceneReplicationState : public RefCounted { -private: - struct TrackedNode { - ObjectID id; - uint32_t net_id = 0; - uint32_t remote_peer = 0; - ObjectID spawner; - ObjectID synchronizer; - uint16_t last_sync = 0; - uint64_t last_sync_msec = 0; - - bool operator==(const ObjectID &p_other) { return id == p_other; } - - Node *get_node() const { return id.is_valid() ? Object::cast_to<Node>(ObjectDB::get_instance(id)) : nullptr; } - MultiplayerSpawner *get_spawner() const { return spawner.is_valid() ? Object::cast_to<MultiplayerSpawner>(ObjectDB::get_instance(spawner)) : nullptr; } - MultiplayerSynchronizer *get_synchronizer() const { return synchronizer.is_valid() ? Object::cast_to<MultiplayerSynchronizer>(ObjectDB::get_instance(synchronizer)) : nullptr; } - TrackedNode() {} - TrackedNode(const ObjectID &p_id) { id = p_id; } - TrackedNode(const ObjectID &p_id, uint32_t p_net_id) { - id = p_id; - net_id = p_net_id; - } - }; - - struct PeerInfo { - HashSet<ObjectID> sync_nodes; - HashSet<ObjectID> spawn_nodes; - HashMap<uint32_t, ObjectID> recv_nodes; - uint16_t last_sent_sync = 0; - uint16_t last_recv_sync = 0; - }; - - HashSet<int> known_peers; - uint32_t last_net_id = 0; - HashMap<ObjectID, TrackedNode> tracked_nodes; - HashMap<int, PeerInfo> peers_info; - HashSet<ObjectID> spawned_nodes; - HashSet<ObjectID> synced_nodes; - - TrackedNode &_track(const ObjectID &p_id); - void _untrack(const ObjectID &p_id); - bool is_tracked(const ObjectID &p_id) const { return tracked_nodes.has(p_id); } - -public: - const HashSet<int> get_peers() const { return known_peers; } - const HashSet<ObjectID> &get_spawned_nodes() const { return spawned_nodes; } - bool is_spawned_node(const ObjectID &p_id) const { return spawned_nodes.has(p_id); } - const HashSet<ObjectID> &get_synced_nodes() const { return synced_nodes; } - bool is_synced_node(const ObjectID &p_id) const { return synced_nodes.has(p_id); } - - MultiplayerSynchronizer *get_synchronizer(const ObjectID &p_id) { return tracked_nodes.has(p_id) ? tracked_nodes[p_id].get_synchronizer() : nullptr; } - MultiplayerSpawner *get_spawner(const ObjectID &p_id) { return tracked_nodes.has(p_id) ? tracked_nodes[p_id].get_spawner() : nullptr; } - Node *get_node(const ObjectID &p_id) { return tracked_nodes.has(p_id) ? tracked_nodes[p_id].get_node() : nullptr; } - bool update_last_node_sync(const ObjectID &p_id, uint16_t p_time); - bool update_sync_time(const ObjectID &p_id, uint64_t p_msec); - - uint32_t get_net_id(const ObjectID &p_id) const; - void set_net_id(const ObjectID &p_id, uint32_t p_net_id); - uint32_t ensure_net_id(const ObjectID &p_id); - - void reset(); - void on_peer_change(int p_peer, bool p_connected); - - Error config_add_spawn(Node *p_node, MultiplayerSpawner *p_spawner); - Error config_del_spawn(Node *p_node, MultiplayerSpawner *p_spawner); - - Error config_add_sync(Node *p_node, MultiplayerSynchronizer *p_sync); - Error config_del_sync(Node *p_node, MultiplayerSynchronizer *p_sync); - - Error peer_add_sync(int p_peer, const ObjectID &p_id); - Error peer_del_sync(int p_peer, const ObjectID &p_id); - - const HashSet<ObjectID> get_peer_sync_nodes(int p_peer); - bool is_peer_sync(int p_peer, const ObjectID &p_id) const; - - Error peer_add_spawn(int p_peer, const ObjectID &p_id); - Error peer_del_spawn(int p_peer, const ObjectID &p_id); - - const HashSet<ObjectID> get_peer_spawn_nodes(int p_peer); - bool is_peer_spawn(int p_peer, const ObjectID &p_id) const; - - const HashMap<uint32_t, ObjectID> peer_get_remotes(int p_peer) const; - Node *peer_get_remote(int p_peer, uint32_t p_net_id); - Error peer_add_remote(int p_peer, uint32_t p_net_id, Node *p_node, MultiplayerSpawner *p_spawner); - Error peer_del_remote(int p_peer, uint32_t p_net_id, Node **r_node); - - uint16_t peer_sync_next(int p_peer); - void peer_sync_recv(int p_peer, uint16_t p_time); - - SceneReplicationState() {} -}; - -#endif // SCENE_REPLICATION_STATE_H diff --git a/modules/multiplayer/scene_rpc_interface.cpp b/modules/multiplayer/scene_rpc_interface.cpp index 65090b9316..acc113c901 100644 --- a/modules/multiplayer/scene_rpc_interface.cpp +++ b/modules/multiplayer/scene_rpc_interface.cpp @@ -412,8 +412,7 @@ void SceneRPCInterface::_send_rpc(Node *p_from, int p_to, uint16_t p_rpc_id, con if (has_all_peers) { // They all have verified paths, so send fast. - peer->set_target_peer(p_to); // To all of you. - peer->put_packet(packet_cache.ptr(), ofs); // A message with love. + multiplayer->send_command(p_to, packet_cache.ptr(), ofs); } else { // Unreachable because the node ID is never compressed if the peers doesn't know it. CRASH_COND(node_id_compression != NETWORK_NODE_ID_COMPRESSION_32); @@ -438,16 +437,14 @@ void SceneRPCInterface::_send_rpc(Node *p_from, int p_to, uint16_t p_rpc_id, con bool confirmed = multiplayer->get_path_cache()->is_cache_confirmed(from_path, P); - peer->set_target_peer(P); // To this one specifically. - if (confirmed) { // This one confirmed path, so use id. encode_uint32(psc_id, &(packet_cache.write[1])); - peer->put_packet(packet_cache.ptr(), ofs); + multiplayer->send_command(P, packet_cache.ptr(), ofs); } else { // This one did not confirm path yet, so use entire path (sorry!). encode_uint32(0x80000000 | ofs, &(packet_cache.write[1])); // Offset to path and flag. - peer->put_packet(packet_cache.ptr(), ofs + path_len); + multiplayer->send_command(P, packet_cache.ptr(), ofs + path_len); } } } diff --git a/modules/navigation/SCsub b/modules/navigation/SCsub index 24a6b12639..0b0822db2d 100644 --- a/modules/navigation/SCsub +++ b/modules/navigation/SCsub @@ -57,7 +57,7 @@ env.modules_sources += thirdparty_obj module_obj = [] env_navigation.add_source_files(module_obj, "*.cpp") -if env["tools"]: +if env.editor_build: env_navigation.add_source_files(module_obj, "editor/*.cpp") env.modules_sources += module_obj diff --git a/modules/navigation/editor/navigation_mesh_editor_plugin.h b/modules/navigation/editor/navigation_mesh_editor_plugin.h index bc9e4185b7..b7bde98131 100644 --- a/modules/navigation/editor/navigation_mesh_editor_plugin.h +++ b/modules/navigation/editor/navigation_mesh_editor_plugin.h @@ -35,6 +35,8 @@ #include "editor/editor_plugin.h" +class AcceptDialog; +class HBoxContainer; class NavigationRegion3D; class NavigationMeshEditor : public Control { diff --git a/modules/navigation/godot_navigation_server.cpp b/modules/navigation/godot_navigation_server.cpp index 9e5d666a51..8ca73a3adb 100644 --- a/modules/navigation/godot_navigation_server.cpp +++ b/modules/navigation/godot_navigation_server.cpp @@ -810,6 +810,32 @@ void GodotNavigationServer::process(real_t p_delta_time) { } } +NavigationUtilities::PathQueryResult GodotNavigationServer::_query_path(const NavigationUtilities::PathQueryParameters &p_parameters) const { + NavigationUtilities::PathQueryResult r_query_result; + + const NavMap *map = map_owner.get_or_null(p_parameters.map); + ERR_FAIL_COND_V(map == nullptr, r_query_result); + + // run the pathfinding + + if (p_parameters.pathfinding_algorithm == NavigationUtilities::PathfindingAlgorithm::PATHFINDING_ALGORITHM_ASTAR) { + // while postprocessing is still part of map.get_path() need to check and route it here for the correct "optimize" post-processing + if (p_parameters.path_postprocessing == NavigationUtilities::PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL) { + r_query_result.path = map->get_path(p_parameters.start_position, p_parameters.target_position, true, p_parameters.navigation_layers); + } else if (p_parameters.path_postprocessing == NavigationUtilities::PathPostProcessing::PATH_POSTPROCESSING_EDGECENTERED) { + r_query_result.path = map->get_path(p_parameters.start_position, p_parameters.target_position, false, p_parameters.navigation_layers); + } + } else { + return r_query_result; + } + + // add path postprocessing + + // add path stats + + return r_query_result; +} + #undef COMMAND_1 #undef COMMAND_2 #undef COMMAND_4 diff --git a/modules/navigation/godot_navigation_server.h b/modules/navigation/godot_navigation_server.h index e6ef7e3bb1..ab5e722d35 100644 --- a/modules/navigation/godot_navigation_server.h +++ b/modules/navigation/godot_navigation_server.h @@ -175,6 +175,8 @@ public: void flush_queries(); virtual void process(real_t p_delta_time) override; + + virtual NavigationUtilities::PathQueryResult _query_path(const NavigationUtilities::PathQueryParameters &p_parameters) const override; }; #undef COMMAND_1 diff --git a/modules/navigation/nav_map.cpp b/modules/navigation/nav_map.cpp index 100db9bc82..83862e1e34 100644 --- a/modules/navigation/nav_map.cpp +++ b/modules/navigation/nav_map.cpp @@ -140,20 +140,17 @@ Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p // This is an implementation of the A* algorithm. int least_cost_id = 0; + int prev_least_cost_id = -1; bool found_route = false; const gd::Polygon *reachable_end = nullptr; float reachable_d = 1e30; bool is_reachable = true; - gd::NavigationPoly *prev_least_cost_poly = nullptr; - while (true) { // Takes the current least_cost_poly neighbors (iterating over its edges) and compute the traveled_distance. for (size_t i = 0; i < navigation_polys[least_cost_id].poly->edges.size(); i++) { - gd::NavigationPoly *least_cost_poly = &navigation_polys[least_cost_id]; - - const gd::Edge &edge = least_cost_poly->poly->edges[i]; + const gd::Edge &edge = navigation_polys[least_cost_id].poly->edges[i]; // Iterate over connections in this edge, then compute the new optimized travel distance assigned to this polygon. for (int connection_index = 0; connection_index < edge.connections.size(); connection_index++) { @@ -164,17 +161,18 @@ Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p continue; } + const gd::NavigationPoly &least_cost_poly = navigation_polys[least_cost_id]; float poly_enter_cost = 0.0; - float poly_travel_cost = least_cost_poly->poly->owner->get_travel_cost(); + float poly_travel_cost = least_cost_poly.poly->owner->get_travel_cost(); - if (prev_least_cost_poly != nullptr && (prev_least_cost_poly->poly->owner->get_self() != least_cost_poly->poly->owner->get_self())) { - poly_enter_cost = least_cost_poly->poly->owner->get_enter_cost(); + if (prev_least_cost_id != -1 && (navigation_polys[prev_least_cost_id].poly->owner->get_self() != least_cost_poly.poly->owner->get_self())) { + poly_enter_cost = least_cost_poly.poly->owner->get_enter_cost(); } - prev_least_cost_poly = least_cost_poly; + prev_least_cost_id = least_cost_id; Vector3 pathway[2] = { connection.pathway_start, connection.pathway_end }; - const Vector3 new_entry = Geometry3D::get_closest_point_to_segment(least_cost_poly->entry, pathway); - const float new_distance = (least_cost_poly->entry.distance_to(new_entry) * poly_travel_cost) + poly_enter_cost + least_cost_poly->traveled_distance; + const Vector3 new_entry = Geometry3D::get_closest_point_to_segment(least_cost_poly.entry, pathway); + const float new_distance = (least_cost_poly.entry.distance_to(new_entry) * poly_travel_cost) + poly_enter_cost + least_cost_poly.traveled_distance; int64_t already_visited_polygon_index = navigation_polys.find(gd::NavigationPoly(connection.polygon)); @@ -240,6 +238,7 @@ Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p to_visit.clear(); to_visit.push_back(0); least_cost_id = 0; + prev_least_cost_id = -1; reachable_end = nullptr; diff --git a/modules/navigation/navigation_mesh_generator.cpp b/modules/navigation/navigation_mesh_generator.cpp index cfb8e0cd42..f0d3e329ce 100644 --- a/modules/navigation/navigation_mesh_generator.cpp +++ b/modules/navigation/navigation_mesh_generator.cpp @@ -209,6 +209,9 @@ void NavigationMeshGenerator::_parse_geometry(const Transform3D &p_navmesh_trans for (uint32_t shape_owner : shape_owners) { const int shape_count = static_body->shape_owner_get_shape_count(shape_owner); for (int i = 0; i < shape_count; i++) { + if (static_body->is_shape_owner_disabled(i)) { + continue; + } Ref<Shape3D> s = static_body->shape_owner_get_shape(shape_owner, i); if (s.is_null()) { continue; @@ -263,10 +266,10 @@ void NavigationMeshGenerator::_parse_geometry(const Transform3D &p_navmesh_trans if (err == OK) { PackedVector3Array faces; - for (int j = 0; j < md.faces.size(); ++j) { - Geometry3D::MeshData::Face face = md.faces[j]; + for (uint32_t j = 0; j < md.faces.size(); ++j) { + const Geometry3D::MeshData::Face &face = md.faces[j]; - for (int k = 2; k < face.indices.size(); ++k) { + for (uint32_t k = 2; k < face.indices.size(); ++k) { faces.push_back(md.vertices[face.indices[0]]); faces.push_back(md.vertices[face.indices[k - 1]]); faces.push_back(md.vertices[face.indices[k]]); @@ -389,10 +392,10 @@ void NavigationMeshGenerator::_parse_geometry(const Transform3D &p_navmesh_trans if (err == OK) { PackedVector3Array faces; - for (int j = 0; j < md.faces.size(); ++j) { - Geometry3D::MeshData::Face face = md.faces[j]; + for (uint32_t j = 0; j < md.faces.size(); ++j) { + const Geometry3D::MeshData::Face &face = md.faces[j]; - for (int k = 2; k < face.indices.size(); ++k) { + for (uint32_t k = 2; k < face.indices.size(); ++k) { faces.push_back(md.vertices[face.indices[0]]); faces.push_back(md.vertices[face.indices[k - 1]]); faces.push_back(md.vertices[face.indices[k]]); diff --git a/modules/noise/doc_classes/NoiseTexture2D.xml b/modules/noise/doc_classes/NoiseTexture2D.xml index 9eea2738c5..0a800a143b 100644 --- a/modules/noise/doc_classes/NoiseTexture2D.xml +++ b/modules/noise/doc_classes/NoiseTexture2D.xml @@ -44,6 +44,7 @@ <member name="noise" type="Noise" setter="set_noise" getter="get_noise"> The instance of the [Noise] object. </member> + <member name="resource_local_to_scene" type="bool" setter="set_local_to_scene" getter="is_local_to_scene" overrides="Resource" default="false" /> <member name="seamless" type="bool" setter="set_seamless" getter="get_seamless" default="false"> If [code]true[/code], a seamless texture is requested from the [Noise] resource. [b]Note:[/b] Seamless noise textures may take longer to generate and/or can have a lower contrast compared to non-seamless noise depending on the used [Noise] resource. This is because some implementations use higher dimensions for generating seamless noise. diff --git a/modules/noise/editor/noise_editor_plugin.cpp b/modules/noise/editor/noise_editor_plugin.cpp index e8e73e4fd9..47f5f8f819 100644 --- a/modules/noise/editor/noise_editor_plugin.cpp +++ b/modules/noise/editor/noise_editor_plugin.cpp @@ -32,7 +32,9 @@ #ifdef TOOLS_ENABLED +#include "editor/editor_inspector.h" #include "editor/editor_scale.h" +#include "scene/gui/texture_rect.h" #include "modules/noise/noise.h" #include "modules/noise/noise_texture_2d.h" diff --git a/modules/noise/noise_texture_2d.cpp b/modules/noise/noise_texture_2d.cpp index 8d279f9dd3..8c785d7591 100644 --- a/modules/noise/noise_texture_2d.cpp +++ b/modules/noise/noise_texture_2d.cpp @@ -152,33 +152,31 @@ Ref<Image> NoiseTexture2D::_generate_texture() { return Ref<Image>(); } - Ref<Image> image; + Ref<Image> new_image; if (seamless) { - image = ref_noise->get_seamless_image(size.x, size.y, invert, in_3d_space, seamless_blend_skirt); + new_image = ref_noise->get_seamless_image(size.x, size.y, invert, in_3d_space, seamless_blend_skirt); } else { - image = ref_noise->get_image(size.x, size.y, invert, in_3d_space); + new_image = ref_noise->get_image(size.x, size.y, invert, in_3d_space); } if (color_ramp.is_valid()) { - image = _modulate_with_gradient(image, color_ramp); + new_image = _modulate_with_gradient(new_image, color_ramp); } if (as_normal_map) { - image->bump_map_to_normal_map(bump_strength); + new_image->bump_map_to_normal_map(bump_strength); } if (generate_mipmaps) { - image->generate_mipmaps(); + new_image->generate_mipmaps(); } - return image; + return new_image; } Ref<Image> NoiseTexture2D::_modulate_with_gradient(Ref<Image> p_image, Ref<Gradient> p_gradient) { int width = p_image->get_width(); int height = p_image->get_height(); - Ref<Image> new_image; - new_image.instantiate(); - new_image->create(width, height, false, Image::FORMAT_RGBA8); + Ref<Image> new_image = Image::create_empty(width, height, false, Image::FORMAT_RGBA8); for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { @@ -197,9 +195,6 @@ void NoiseTexture2D::_update_texture() { use_thread = false; first_time = false; } -#ifdef NO_THREADS - use_thread = false; -#endif if (use_thread) { if (!noise_thread.is_started()) { noise_thread.start(_thread_function, this); @@ -209,8 +204,8 @@ void NoiseTexture2D::_update_texture() { } } else { - Ref<Image> image = _generate_texture(); - _set_texture_image(image); + Ref<Image> new_image = _generate_texture(); + _set_texture_image(new_image); } update_queued = false; } diff --git a/modules/openxr/SCsub b/modules/openxr/SCsub index 593d1ff3c1..84542be3b9 100644 --- a/modules/openxr/SCsub +++ b/modules/openxr/SCsub @@ -18,38 +18,36 @@ env_openxr.Prepend( thirdparty_dir + "/src", thirdparty_dir + "/src/common", thirdparty_dir + "/src/external/jsoncpp/include", - thirdparty_dir + "/src/loader", ] ) -# may need to check and set: -# - XR_USE_TIMESPEC - -env_thirdparty = env_openxr.Clone() -env_thirdparty.disable_warnings() -env_thirdparty.AppendUnique(CPPDEFINES=["DISABLE_STD_FILESYSTEM"]) - if env["platform"] == "android": # may need to set OPENXR_ANDROID_VERSION_SUFFIX - env_thirdparty.AppendUnique(CPPDEFINES=["XR_OS_ANDROID", "XR_USE_PLATFORM_ANDROID"]) + env_openxr.AppendUnique(CPPDEFINES=["XR_OS_ANDROID", "XR_USE_PLATFORM_ANDROID"]) + env_openxr.AppendUnique(CPPDEFINES=["JSON_USE_EXCEPTION=0"]) # may need to include java parts of the openxr loader elif env["platform"] == "linuxbsd": - env_thirdparty.AppendUnique(CPPDEFINES=["XR_OS_LINUX"]) + env_openxr.AppendUnique(CPPDEFINES=["XR_OS_LINUX"]) if env["x11"]: - env_thirdparty.AppendUnique(CPPDEFINES=["XR_USE_PLATFORM_XLIB"]) + env_openxr.AppendUnique(CPPDEFINES=["XR_USE_PLATFORM_XLIB"]) # FIXME: Review what needs to be set for Android and macOS. - env_thirdparty.AppendUnique(CPPDEFINES=["HAVE_SECURE_GETENV"]) + env_openxr.AppendUnique(CPPDEFINES=["HAVE_SECURE_GETENV"]) elif env["platform"] == "windows": - env_thirdparty.AppendUnique(CPPDEFINES=["XR_OS_WINDOWS", "NOMINMAX", "XR_USE_PLATFORM_WIN32"]) + env_openxr.AppendUnique(CPPDEFINES=["XR_OS_WINDOWS", "NOMINMAX", "XR_USE_PLATFORM_WIN32"]) -env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/xr_generated_dispatch_table.c") +# may need to check and set: +# - XR_USE_TIMESPEC -# add in common files (hope these don't clash with us) -env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/common/filesystem_utils.cpp") -env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/common/object_info.cpp") +env_thirdparty = env_openxr.Clone() +env_thirdparty.disable_warnings() +env_thirdparty.AppendUnique(CPPDEFINES=["DISABLE_STD_FILESYSTEM"]) + +if "-fno-exceptions" in env_thirdparty["CXXFLAGS"]: + env_thirdparty["CXXFLAGS"].remove("-fno-exceptions") +env_thirdparty.Append(CPPPATH=[thirdparty_dir + "/src/loader"]) # add in external jsoncpp dependency env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/external/jsoncpp/src/lib_json/json_reader.cpp") @@ -57,17 +55,24 @@ env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/external/ env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/external/jsoncpp/src/lib_json/json_writer.cpp") # add in load -if env["platform"] == "android": - env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/loader/android_utilities.cpp") - -env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/loader/api_layer_interface.cpp") -env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/loader/loader_core.cpp") -env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/loader/loader_instance.cpp") -env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/loader/loader_logger_recorders.cpp") -env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/loader/loader_logger.cpp") -env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/loader/manifest_file.cpp") -env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/loader/runtime_interface.cpp") -env_thirdparty.add_source_files(thirdparty_obj, thirdparty_dir + "/src/loader/xr_generated_loader.cpp") +if env["platform"] != "android": + # On Android the openxr_loader is provided by separate plugins for each device + # Build the engine using object files + khrloader_obj = [] + env_thirdparty.add_source_files(khrloader_obj, thirdparty_dir + "/src/xr_generated_dispatch_table.c") + + env_thirdparty.add_source_files(khrloader_obj, thirdparty_dir + "/src/common/filesystem_utils.cpp") + env_thirdparty.add_source_files(khrloader_obj, thirdparty_dir + "/src/common/object_info.cpp") + + env_thirdparty.add_source_files(khrloader_obj, thirdparty_dir + "/src/loader/api_layer_interface.cpp") + env_thirdparty.add_source_files(khrloader_obj, thirdparty_dir + "/src/loader/loader_core.cpp") + env_thirdparty.add_source_files(khrloader_obj, thirdparty_dir + "/src/loader/loader_instance.cpp") + env_thirdparty.add_source_files(khrloader_obj, thirdparty_dir + "/src/loader/loader_logger_recorders.cpp") + env_thirdparty.add_source_files(khrloader_obj, thirdparty_dir + "/src/loader/loader_logger.cpp") + env_thirdparty.add_source_files(khrloader_obj, thirdparty_dir + "/src/loader/manifest_file.cpp") + env_thirdparty.add_source_files(khrloader_obj, thirdparty_dir + "/src/loader/runtime_interface.cpp") + env_thirdparty.add_source_files(khrloader_obj, thirdparty_dir + "/src/loader/xr_generated_loader.cpp") + env.modules_sources += khrloader_obj env.modules_sources += thirdparty_obj @@ -78,18 +83,26 @@ module_obj = [] env_openxr.add_source_files(module_obj, "*.cpp") env_openxr.add_source_files(module_obj, "action_map/*.cpp") +env_openxr.add_source_files(module_obj, "scene/*.cpp") # We're a little more targeted with our extensions if env["platform"] == "android": env_openxr.add_source_files(module_obj, "extensions/openxr_android_extension.cpp") if env["vulkan"]: env_openxr.add_source_files(module_obj, "extensions/openxr_vulkan_extension.cpp") +if env["opengl3"]: + env_openxr.add_source_files(module_obj, "extensions/openxr_opengl_extension.cpp") +env_openxr.add_source_files(module_obj, "extensions/openxr_palm_pose_extension.cpp") +env_openxr.add_source_files(module_obj, "extensions/openxr_composition_layer_depth_extension.cpp") env_openxr.add_source_files(module_obj, "extensions/openxr_htc_vive_tracker_extension.cpp") +env_openxr.add_source_files(module_obj, "extensions/openxr_hand_tracking_extension.cpp") +env_openxr.add_source_files(module_obj, "extensions/openxr_fb_passthrough_extension_wrapper.cpp") +env_openxr.add_source_files(module_obj, "extensions/openxr_fb_display_refresh_rate_extension.cpp") env.modules_sources += module_obj -if env["tools"]: +if env.editor_build: SConscript("editor/SCsub") # Needed to force rebuilding the module files when the thirdparty library is updated. diff --git a/modules/openxr/action_map/openxr_action.cpp b/modules/openxr/action_map/openxr_action.cpp index 359975a480..0fb4f0773f 100644 --- a/modules/openxr/action_map/openxr_action.cpp +++ b/modules/openxr/action_map/openxr_action.cpp @@ -64,13 +64,13 @@ Ref<OpenXRAction> OpenXRAction::new_action(const char *p_name, const char *p_loc } String OpenXRAction::get_name_with_set() const { - String name = get_name(); + String action_name = get_name(); if (action_set != nullptr) { - name = action_set->get_name() + "/" + name; + action_name = action_set->get_name() + "/" + action_name; } - return name; + return action_name; } void OpenXRAction::set_localized_name(const String p_localized_name) { diff --git a/modules/openxr/action_map/openxr_action_map.cpp b/modules/openxr/action_map/openxr_action_map.cpp index 0eb5302442..123f860ce9 100644 --- a/modules/openxr/action_map/openxr_action_map.cpp +++ b/modules/openxr/action_map/openxr_action_map.cpp @@ -157,7 +157,11 @@ void OpenXRActionMap::remove_interaction_profile(Ref<OpenXRInteractionProfile> p } void OpenXRActionMap::create_default_action_sets() { - // Note, if you make changes here make sure to delete your default_action_map.tres file of it will load an old version. + // Note: + // - if you make changes here make sure to delete your default_action_map.tres file of it will load an old version. + // - our palm pose is only available if the relevant extension is supported, + // we still want it to be part of our action map as we may deploy the same game to platforms that do and don't support it. + // - the same applies for interaction profiles that are only supported if the relevant extension is supported. // Create our Godot action set Ref<OpenXRActionSet> action_set = OpenXRActionSet::new_action_set("godot", "Godot action set"); @@ -200,6 +204,7 @@ void OpenXRActionMap::create_default_action_sets() { "/user/vive_tracker_htcx/role/keyboard"); Ref<OpenXRAction> aim_pose = action_set->add_new_action("aim_pose", "Aim pose", OpenXRAction::OPENXR_ACTION_POSE, "/user/hand/left,/user/hand/right"); Ref<OpenXRAction> grip_pose = action_set->add_new_action("grip_pose", "Grip pose", OpenXRAction::OPENXR_ACTION_POSE, "/user/hand/left,/user/hand/right"); + Ref<OpenXRAction> palm_pose = action_set->add_new_action("palm_pose", "Palm pose", OpenXRAction::OPENXR_ACTION_POSE, "/user/hand/left,/user/hand/right"); Ref<OpenXRAction> haptic = action_set->add_new_action("haptic", "Haptic", OpenXRAction::OPENXR_ACTION_HAPTIC, "/user/hand/left," "/user/hand/right," @@ -219,9 +224,10 @@ void OpenXRActionMap::create_default_action_sets() { // Create our interaction profiles Ref<OpenXRInteractionProfile> profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/khr/simple_controller"); - profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(default_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(palm_pose, "/user/hand/left/input/palm_ext/pose,/user/hand/right/input/palm_ext/pose"); profile->add_new_binding(menu_button, "/user/hand/left/input/menu/click,/user/hand/right/input/menu/click"); profile->add_new_binding(select_button, "/user/hand/left/input/select/click,/user/hand/right/input/select/click"); // generic has no support for triggers, grip, A/B buttons, nor joystick/trackpad inputs @@ -230,9 +236,10 @@ void OpenXRActionMap::create_default_action_sets() { // Create our Vive controller profile profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/htc/vive_controller"); - profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(default_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(palm_pose, "/user/hand/left/input/palm_ext/pose,/user/hand/right/input/palm_ext/pose"); profile->add_new_binding(menu_button, "/user/hand/left/input/menu/click,/user/hand/right/input/menu/click"); profile->add_new_binding(select_button, "/user/hand/left/input/system/click,/user/hand/right/input/system/click"); // wmr controller has no a/b/x/y buttons @@ -250,9 +257,10 @@ void OpenXRActionMap::create_default_action_sets() { // Create our WMR controller profile profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/microsoft/motion_controller"); - profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(default_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(palm_pose, "/user/hand/left/input/palm_ext/pose,/user/hand/right/input/palm_ext/pose"); // wmr controllers have no select button we can use profile->add_new_binding(menu_button, "/user/hand/left/input/menu/click,/user/hand/right/input/menu/click"); // wmr controller has no a/b/x/y buttons @@ -272,9 +280,10 @@ void OpenXRActionMap::create_default_action_sets() { // Create our Meta touch controller profile profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/oculus/touch_controller"); - profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(default_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(palm_pose, "/user/hand/left/input/palm_ext/pose,/user/hand/right/input/palm_ext/pose"); // touch controllers have no select button we can use profile->add_new_binding(menu_button, "/user/hand/left/input/menu/click,/user/hand/right/input/system/click"); // right hand system click may not be available profile->add_new_binding(ax_button, "/user/hand/left/input/x/click,/user/hand/right/input/a/click"); // x on left hand, a on right hand @@ -296,9 +305,10 @@ void OpenXRActionMap::create_default_action_sets() { // Create our Valve index controller profile profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/valve/index_controller"); - profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(default_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(palm_pose, "/user/hand/left/input/palm_ext/pose,/user/hand/right/input/palm_ext/pose"); // index controllers have no select button we can use profile->add_new_binding(menu_button, "/user/hand/left/input/system/click,/user/hand/right/input/system/click"); profile->add_new_binding(ax_button, "/user/hand/left/input/a/click,/user/hand/right/input/a/click"); // a on both controllers @@ -321,16 +331,12 @@ void OpenXRActionMap::create_default_action_sets() { profile->add_new_binding(haptic, "/user/hand/left/output/haptic,/user/hand/right/output/haptic"); add_interaction_profile(profile); - // Note, the following profiles are all part of extensions. - // We include these regardless of whether the extension is active. - // We want our action map to be as complete as possible so our game is as portable as possible. - // It is very possible these will in due time become core. - // Create our HP MR controller profile profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/hp/mixed_reality_controller"); - profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(default_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(palm_pose, "/user/hand/left/input/palm_ext/pose,/user/hand/right/input/palm_ext/pose"); // hpmr controllers have no select button we can use profile->add_new_binding(menu_button, "/user/hand/left/input/menu/click,/user/hand/right/input/menu/click"); // hpmr controllers only register click, not touch, on our a/b/x/y buttons @@ -350,9 +356,10 @@ void OpenXRActionMap::create_default_action_sets() { // Create our Samsung Odyssey controller profile, // Note that this controller is only identified specifically on WMR, on SteamVR this is identified as a normal WMR controller. profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/samsung/odyssey_controller"); - profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(default_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(palm_pose, "/user/hand/left/input/palm_ext/pose,/user/hand/right/input/palm_ext/pose"); // Odyssey controllers have no select button we can use profile->add_new_binding(menu_button, "/user/hand/left/input/menu/click,/user/hand/right/input/menu/click"); // Odyssey controller has no a/b/x/y buttons @@ -372,9 +379,10 @@ void OpenXRActionMap::create_default_action_sets() { // Create our Vive Cosmos controller profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/htc/vive_cosmos_controller"); - profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(default_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(palm_pose, "/user/hand/left/input/palm_ext/pose,/user/hand/right/input/palm_ext/pose"); profile->add_new_binding(menu_button, "/user/hand/left/input/menu/click"); profile->add_new_binding(select_button, "/user/hand/left/input/system/click"); // we'll map system to select profile->add_new_binding(ax_button, "/user/hand/left/input/x/click,/user/hand/right/input/a/click"); // x on left hand, a on right hand @@ -395,9 +403,10 @@ void OpenXRActionMap::create_default_action_sets() { // Note, Vive Focus 3 currently is not yet supported as a stand alone device // however HTC currently has a beta OpenXR runtime in testing we may support in the near future profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/htc/vive_focus3_controller"); - profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(default_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(palm_pose, "/user/hand/left/input/palm_ext/pose,/user/hand/right/input/palm_ext/pose"); profile->add_new_binding(menu_button, "/user/hand/left/input/menu/click"); profile->add_new_binding(select_button, "/user/hand/left/input/system/click"); // we'll map system to select profile->add_new_binding(ax_button, "/user/hand/left/input/x/click,/user/hand/right/input/a/click"); // x on left hand, a on right hand @@ -418,9 +427,10 @@ void OpenXRActionMap::create_default_action_sets() { // Create our Huawei controller profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/huawei/controller"); - profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(default_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(palm_pose, "/user/hand/left/input/palm_ext/pose,/user/hand/right/input/palm_ext/pose"); profile->add_new_binding(menu_button, "/user/hand/left/input/home/click,/user/hand/right/input/home/click"); profile->add_new_binding(trigger, "/user/hand/left/input/trigger/value,/user/hand/right/input/trigger/value"); profile->add_new_binding(trigger_click, "/user/hand/left/input/trigger/click,/user/hand/right/input/trigger/click"); diff --git a/modules/openxr/action_map/openxr_defs.cpp b/modules/openxr/action_map/openxr_defs.cpp index 89860199be..59ce829f1b 100644 --- a/modules/openxr/action_map/openxr_defs.cpp +++ b/modules/openxr/action_map/openxr_defs.cpp @@ -62,6 +62,8 @@ OpenXRDefs::IOPath OpenXRDefs::simple_io_paths[] = { { "Grip pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/grip/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Palm pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/palm_ext/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Palm pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/palm_ext/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Menu click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/menu/click", OpenXRAction::OPENXR_ACTION_BOOL }, { "Menu click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/menu/click", OpenXRAction::OPENXR_ACTION_BOOL }, @@ -78,6 +80,8 @@ OpenXRDefs::IOPath OpenXRDefs::vive_io_paths[] = { { "Grip pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/grip/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Palm pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/palm_ext/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Palm pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/palm_ext/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Menu click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/menu/click", OpenXRAction::OPENXR_ACTION_BOOL }, { "Menu click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/menu/click", OpenXRAction::OPENXR_ACTION_BOOL }, @@ -109,6 +113,8 @@ OpenXRDefs::IOPath OpenXRDefs::motion_io_paths[] = { { "Grip pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/grip/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Palm pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/palm_ext/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Palm pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/palm_ext/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Menu click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/menu/click", OpenXRAction::OPENXR_ACTION_BOOL }, { "Menu click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/menu/click", OpenXRAction::OPENXR_ACTION_BOOL }, @@ -143,6 +149,8 @@ OpenXRDefs::IOPath OpenXRDefs::hpmr_io_paths[] = { { "Grip pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/grip/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Palm pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/palm_ext/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Palm pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/palm_ext/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Menu click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/menu/click", OpenXRAction::OPENXR_ACTION_BOOL }, { "Menu click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/menu/click", OpenXRAction::OPENXR_ACTION_BOOL }, @@ -175,6 +183,8 @@ OpenXRDefs::IOPath OpenXRDefs::touch_io_paths[] = { { "Grip pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/grip/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Palm pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/palm_ext/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Palm pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/palm_ext/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Menu click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/menu/click", OpenXRAction::OPENXR_ACTION_BOOL }, { "System click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/system/click", OpenXRAction::OPENXR_ACTION_BOOL }, @@ -213,6 +223,8 @@ OpenXRDefs::IOPath OpenXRDefs::index_io_paths[] = { { "Grip pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/grip/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Palm pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/palm_ext/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Palm pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/palm_ext/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "System click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/system/click", OpenXRAction::OPENXR_ACTION_BOOL }, { "System click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/system/click", OpenXRAction::OPENXR_ACTION_BOOL }, @@ -260,6 +272,8 @@ OpenXRDefs::IOPath OpenXRDefs::odyssey_io_paths[] = { { "Grip pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/grip/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Palm pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/palm_ext/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Palm pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/palm_ext/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Menu click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/menu/click", OpenXRAction::OPENXR_ACTION_BOOL }, { "Menu click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/menu/click", OpenXRAction::OPENXR_ACTION_BOOL }, @@ -294,6 +308,8 @@ OpenXRDefs::IOPath OpenXRDefs::vive_cosmos_paths[] = { { "Grip pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/grip/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Palm pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/palm_ext/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Palm pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/palm_ext/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Menu click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/menu/click", OpenXRAction::OPENXR_ACTION_BOOL }, { "System click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/system/click", OpenXRAction::OPENXR_ACTION_BOOL }, @@ -331,6 +347,8 @@ OpenXRDefs::IOPath OpenXRDefs::vive_focus3_paths[] = { { "Grip pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/grip/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Palm pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/palm_ext/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Palm pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/palm_ext/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Menu click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/menu/click", OpenXRAction::OPENXR_ACTION_BOOL }, { "System click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/system/click", OpenXRAction::OPENXR_ACTION_BOOL }, @@ -371,6 +389,8 @@ OpenXRDefs::IOPath OpenXRDefs::huawei_controller_paths[] = { { "Grip pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/grip/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Palm pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/palm_ext/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Palm pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/palm_ext/pose", OpenXRAction::OPENXR_ACTION_POSE }, { "Home click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/home/click", OpenXRAction::OPENXR_ACTION_BOOL }, { "Home click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/home/click", OpenXRAction::OPENXR_ACTION_BOOL }, diff --git a/modules/openxr/config.py b/modules/openxr/config.py index f91cb1359f..279168cc59 100644 --- a/modules/openxr/config.py +++ b/modules/openxr/config.py @@ -1,7 +1,5 @@ def can_build(env, platform): - if ( - platform == "linuxbsd" or platform == "windows" - ): # or platform == "android" -- temporarily disabled android support + if platform in ("linuxbsd", "windows", "android"): return env["openxr"] else: # not supported on these platforms @@ -20,6 +18,7 @@ def get_doc_classes(): "OpenXRActionMap", "OpenXRInteractionProfile", "OpenXRIPBinding", + "OpenXRHand", ] diff --git a/modules/openxr/doc_classes/OpenXRAction.xml b/modules/openxr/doc_classes/OpenXRAction.xml index d1a2ce2d2e..a3a45ebb4c 100644 --- a/modules/openxr/doc_classes/OpenXRAction.xml +++ b/modules/openxr/doc_classes/OpenXRAction.xml @@ -6,7 +6,7 @@ <description> This resource defines an OpenXR action. Actions can be used both for inputs (buttons/joystick/trigger/etc) and outputs (haptics). OpenXR performs automatic conversion between action type and input type whenever possible. An analogue trigger bound to a boolean action will thus return [code]false[/code] if the trigger is depressed and [code]true[/code] if pressed fully. - Actions are not directly bound to specific devices, instead OpenXR recognises a limited number of top level paths that identify devices by usage. We can restrict which devices an action can be bound to by these top level paths. For instance an action that should only be used for hand held controllers can have the top level paths "/user/hand/left" and "/user/hand/right" associated with them. See the [url=https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#semantic-path-reserved]reserved path section in the OpenXR specification[/url] for more info on the top level paths. + Actions are not directly bound to specific devices, instead OpenXR recognizes a limited number of top level paths that identify devices by usage. We can restrict which devices an action can be bound to by these top level paths. For instance an action that should only be used for hand held controllers can have the top level paths "/user/hand/left" and "/user/hand/right" associated with them. See the [url=https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#semantic-path-reserved]reserved path section in the OpenXR specification[/url] for more info on the top level paths. Note that the name of the resource is used to register the action with. </description> <tutorials> @@ -16,7 +16,7 @@ The type of action. </member> <member name="localized_name" type="String" setter="set_localized_name" getter="get_localized_name" default=""""> - The localised description of this action. + The localized description of this action. </member> <member name="toplevel_paths" type="PackedStringArray" setter="set_toplevel_paths" getter="get_toplevel_paths" default="PackedStringArray()"> A collections of toplevel paths to which this action can be bound. diff --git a/modules/openxr/doc_classes/OpenXRActionSet.xml b/modules/openxr/doc_classes/OpenXRActionSet.xml index db3259ec07..39e518750a 100644 --- a/modules/openxr/doc_classes/OpenXRActionSet.xml +++ b/modules/openxr/doc_classes/OpenXRActionSet.xml @@ -36,7 +36,7 @@ Collection of actions for this action set. </member> <member name="localized_name" type="String" setter="set_localized_name" getter="get_localized_name" default=""""> - The localised name of this action set. + The localized name of this action set. </member> <member name="priority" type="int" setter="set_priority" getter="get_priority" default="0"> The priority for this action set. diff --git a/modules/openxr/doc_classes/OpenXRHand.xml b/modules/openxr/doc_classes/OpenXRHand.xml new file mode 100644 index 0000000000..5d5f8a6126 --- /dev/null +++ b/modules/openxr/doc_classes/OpenXRHand.xml @@ -0,0 +1,42 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="OpenXRHand" inherits="Node3D" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> + <brief_description> + Node supporting finger tracking in OpenXR. + </brief_description> + <description> + This node enables OpenXR's hand tracking functionality. The node should be a child node of an [XROrigin3D] node, tracking will update its position to where the player's actual hand is positioned. This node also updates the skeleton of a properly skinned hand model. The hand mesh should be a child node of this node. + </description> + <tutorials> + </tutorials> + <members> + <member name="hand" type="int" setter="set_hand" getter="get_hand" enum="OpenXRHand.Hands" default="0"> + Specifies whether this node tracks the left or right hand of the player. + </member> + <member name="hand_skeleton" type="NodePath" setter="set_hand_skeleton" getter="get_hand_skeleton" default="NodePath("")"> + Set a [Skeleton3D] node for which the pose positions will be updated. + </member> + <member name="motion_range" type="int" setter="set_motion_range" getter="get_motion_range" enum="OpenXRHand.MotionRange" default="0"> + Set the motion range (if supported) limiting the hand motion. + </member> + </members> + <constants> + <constant name="HAND_LEFT" value="0" enum="Hands"> + Tracking the player's left hand. + </constant> + <constant name="HAND_RIGHT" value="1" enum="Hands"> + Tracking the player's right hand. + </constant> + <constant name="HAND_MAX" value="2" enum="Hands"> + Maximum supported hands. + </constant> + <constant name="MOTION_RANGE_UNOBSTRUCTED" value="0" enum="MotionRange"> + When player grips, hand skeleton will form a full fist. + </constant> + <constant name="MOTION_RANGE_CONFORM_TO_CONTROLLER" value="1" enum="MotionRange"> + When player grips, hand skeleton conforms to the controller the player is holding. + </constant> + <constant name="MOTION_RANGE_MAX" value="2" enum="MotionRange"> + Maximum supported motion ranges. + </constant> + </constants> +</class> diff --git a/modules/openxr/doc_classes/OpenXRInterface.xml b/modules/openxr/doc_classes/OpenXRInterface.xml index 25bf496de9..7251a4a9bd 100644 --- a/modules/openxr/doc_classes/OpenXRInterface.xml +++ b/modules/openxr/doc_classes/OpenXRInterface.xml @@ -5,11 +5,24 @@ </brief_description> <description> The OpenXR interface allows Godot to interact with OpenXR runtimes and make it possible to create XR experiences and games. - Due to the needs of OpenXR this interface works slightly different than other plugin based XR interfaces. It needs to be initialised when Godot starts. You need to enable OpenXR, settings for this can be found in your games project settings under the XR heading. You do need to mark a viewport for use with XR in order for Godot to know which render result should be output to the headset. + Due to the needs of OpenXR this interface works slightly different than other plugin based XR interfaces. It needs to be initialized when Godot starts. You need to enable OpenXR, settings for this can be found in your games project settings under the XR heading. You do need to mark a viewport for use with XR in order for Godot to know which render result should be output to the headset. </description> <tutorials> <link title="Setting up XR">$DOCS_URL/tutorials/xr/setting_up_xr.html</link> </tutorials> + <methods> + <method name="get_available_display_refresh_rates" qualifiers="const"> + <return type="Array" /> + <description> + Returns display refresh rates supported by the current HMD. Only returned if this feature is supported by the OpenXR runtime and after the interface has been initialized. + </description> + </method> + </methods> + <members> + <member name="display_refresh_rate" type="float" setter="set_display_refresh_rate" getter="get_display_refresh_rate" default="0.0"> + The display refresh rate for the current HMD. Only functional if this feature is supported by the OpenXR runtime and after the interface has been initialized. + </member> + </members> <signals> <signal name="pose_recentered"> <description> diff --git a/modules/openxr/editor/openxr_action_map_editor.cpp b/modules/openxr/editor/openxr_action_map_editor.cpp index 51c402d746..b5223e5903 100644 --- a/modules/openxr/editor/openxr_action_map_editor.cpp +++ b/modules/openxr/editor/openxr_action_map_editor.cpp @@ -128,7 +128,7 @@ void OpenXRActionMapEditor::_update_interaction_profiles() { interaction_profiles.remove_at(0); tabs->remove_child(interaction_profile); - interaction_profile->queue_delete(); + interaction_profile->queue_free(); } // in with the new... @@ -205,7 +205,7 @@ void OpenXRActionMapEditor::_on_remove_action_set(Object *p_action_set_editor) { action_map->remove_action_set(action_set); actionsets_vb->remove_child(action_set_editor); - action_set_editor->queue_delete(); + action_set_editor->queue_free(); } void OpenXRActionMapEditor::_on_action_removed() { @@ -290,7 +290,7 @@ void OpenXRActionMapEditor::_on_tab_button_pressed(int p_tab) { action_map->remove_interaction_profile(interaction_profile); tabs->remove_child(profile_editor); - profile_editor->queue_delete(); + profile_editor->queue_free(); } void OpenXRActionMapEditor::open_action_map(String p_path) { @@ -364,7 +364,7 @@ OpenXRActionMapEditor::OpenXRActionMapEditor() { select_interaction_profile_dialog->connect("interaction_profile_selected", callable_mp(this, &OpenXRActionMapEditor::_on_interaction_profile_selected)); add_child(select_interaction_profile_dialog); - _load_action_map(ProjectSettings::get_singleton()->get("xr/openxr/default_action_map")); + _load_action_map(GLOBAL_GET("xr/openxr/default_action_map")); } OpenXRActionMapEditor::~OpenXRActionMapEditor() { diff --git a/modules/openxr/editor/openxr_action_set_editor.cpp b/modules/openxr/editor/openxr_action_set_editor.cpp index 804808a6b9..3869146e8e 100644 --- a/modules/openxr/editor/openxr_action_set_editor.cpp +++ b/modules/openxr/editor/openxr_action_set_editor.cpp @@ -140,7 +140,7 @@ void OpenXRActionSetEditor::_on_remove_action(Object *p_action_editor) { // And remove it.... action_map->remove_action(action->get_name_with_set()); // remove it from the set and any interaction profile it relates to actions_vb->remove_child(action_editor); - action_editor->queue_delete(); + action_editor->queue_free(); // Let action map editor know so we can update our interaction profiles emit_signal("action_removed"); diff --git a/modules/openxr/extensions/openxr_android_extension.cpp b/modules/openxr/extensions/openxr_android_extension.cpp index 3bd4db169c..8f6d5c28db 100644 --- a/modules/openxr/extensions/openxr_android_extension.cpp +++ b/modules/openxr/extensions/openxr_android_extension.cpp @@ -29,7 +29,12 @@ /*************************************************************************/ #include "openxr_android_extension.h" +#include "java_godot_wrapper.h" +#include "os_android.h" +#include "thread_jandroid.h" +#include <jni.h> +#include <modules/openxr/openxr_api.h> #include <openxr/openxr.h> #include <openxr/openxr_platform.h> @@ -42,19 +47,16 @@ OpenXRAndroidExtension *OpenXRAndroidExtension::get_singleton() { OpenXRAndroidExtension::OpenXRAndroidExtension(OpenXRAPI *p_openxr_api) : OpenXRExtensionWrapper(p_openxr_api) { singleton = this; - request_extensions[XR_KHR_ANDROID_THREAD_SETTINGS_EXTENSION_NAME] = nullptr; // must be available +} - // Initialize the loader - PFN_xrInitializeLoaderKHR xrInitializeLoaderKHR; - result = xrGetInstanceProcAddr(XR_NULL_HANDLE, "xrInitializeLoaderKHR", (PFN_xrVoidFunction *)(&xrInitializeLoaderKHR)); - ERR_FAIL_COND_MSG(XR_FAILED(result), "Failed to retrieve pointer to xrInitializeLoaderKHR"); +void OpenXRAndroidExtension::on_before_instance_created() { + EXT_INIT_XR_FUNC(xrInitializeLoaderKHR); - // TODO fix this code, this is still code from GDNative! - JNIEnv *env = android_api->godot_android_get_env(); + JNIEnv *env = get_jni_env(); JavaVM *vm; env->GetJavaVM(&vm); - jobject activity_object = env->NewGlobalRef(android_api->godot_android_get_activity()); + jobject activity_object = env->NewGlobalRef(static_cast<OS_Android *>(OS::get_singleton())->get_godot_java()->get_activity()); XrLoaderInitInfoAndroidKHR loader_init_info_android = { .type = XR_TYPE_LOADER_INIT_INFO_ANDROID_KHR, @@ -62,7 +64,7 @@ OpenXRAndroidExtension::OpenXRAndroidExtension(OpenXRAPI *p_openxr_api) : .applicationVM = vm, .applicationContext = activity_object }; - xrInitializeLoaderKHR((const XrLoaderInitInfoBaseHeaderKHR *)&loader_init_info_android); + XrResult result = xrInitializeLoaderKHR((const XrLoaderInitInfoBaseHeaderKHR *)&loader_init_info_android); ERR_FAIL_COND_MSG(XR_FAILED(result), "Failed to call xrInitializeLoaderKHR"); } diff --git a/modules/openxr/extensions/openxr_android_extension.h b/modules/openxr/extensions/openxr_android_extension.h index 88b0e310e7..eda7022064 100644 --- a/modules/openxr/extensions/openxr_android_extension.h +++ b/modules/openxr/extensions/openxr_android_extension.h @@ -31,6 +31,7 @@ #ifndef OPENXR_ANDROID_EXTENSION_H #define OPENXR_ANDROID_EXTENSION_H +#include "../util.h" #include "openxr_extension_wrapper.h" class OpenXRAndroidExtension : public OpenXRExtensionWrapper { @@ -38,10 +39,16 @@ public: static OpenXRAndroidExtension *get_singleton(); OpenXRAndroidExtension(OpenXRAPI *p_openxr_api); + + virtual void on_before_instance_created() override; + virtual ~OpenXRAndroidExtension() override; private: static OpenXRAndroidExtension *singleton; + + // Initialize the loader + EXT_PROTO_XRRESULT_FUNC1(xrInitializeLoaderKHR, (const XrLoaderInitInfoBaseHeaderKHR *), loaderInitInfo) }; #endif // OPENXR_ANDROID_EXTENSION_H diff --git a/modules/openxr/extensions/openxr_composition_layer_depth_extension.cpp b/modules/openxr/extensions/openxr_composition_layer_depth_extension.cpp new file mode 100644 index 0000000000..0f6aaf8afb --- /dev/null +++ b/modules/openxr/extensions/openxr_composition_layer_depth_extension.cpp @@ -0,0 +1,58 @@ +/*************************************************************************/ +/* openxr_composition_layer_depth_extension.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 "openxr_composition_layer_depth_extension.h" + +OpenXRCompositionLayerDepthExtension *OpenXRCompositionLayerDepthExtension::singleton = nullptr; + +OpenXRCompositionLayerDepthExtension *OpenXRCompositionLayerDepthExtension::get_singleton() { + return singleton; +} + +OpenXRCompositionLayerDepthExtension::OpenXRCompositionLayerDepthExtension(OpenXRAPI *p_openxr_api) : + OpenXRExtensionWrapper(p_openxr_api) { + singleton = this; + + request_extensions[XR_KHR_COMPOSITION_LAYER_DEPTH_EXTENSION_NAME] = &available; +} + +OpenXRCompositionLayerDepthExtension::~OpenXRCompositionLayerDepthExtension() { + singleton = nullptr; +} + +bool OpenXRCompositionLayerDepthExtension::is_available() { + return available; +} + +XrCompositionLayerBaseHeader *OpenXRCompositionLayerDepthExtension::get_composition_layer() { + // Seems this is all done in our base layer... Just in case this changes... + + return nullptr; +} diff --git a/modules/websocket/websocket_macros.h b/modules/openxr/extensions/openxr_composition_layer_depth_extension.h index a01ae65c56..9533783d83 100644 --- a/modules/websocket/websocket_macros.h +++ b/modules/openxr/extensions/openxr_composition_layer_depth_extension.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* websocket_macros.h */ +/* openxr_composition_layer_depth_extension.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,41 +28,26 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef WEBSOCKET_MACROS_H -#define WEBSOCKET_MACROS_H +#ifndef OPENXR_COMPOSITION_LAYER_DEPTH_EXTENSION_H +#define OPENXR_COMPOSITION_LAYER_DEPTH_EXTENSION_H -// Defaults per peer buffers, 1024 packets with a shared 65536 bytes payload. -#define DEF_PKT_SHIFT 10 -#define DEF_BUF_SHIFT 16 +#include "openxr_composition_layer_provider.h" +#include "openxr_extension_wrapper.h" -/* clang-format off */ -#define GDCICLASS(CNAME) \ -public:\ - static CNAME *(*_create)();\ -\ - static Ref<CNAME > create_ref() {\ -\ - if (!_create)\ - return Ref<CNAME >();\ - return Ref<CNAME >(_create());\ - }\ -\ - static CNAME *create() {\ -\ - if (!_create)\ - return nullptr;\ - return _create();\ - }\ -protected:\ +class OpenXRCompositionLayerDepthExtension : public OpenXRExtensionWrapper, public OpenXRCompositionLayerProvider { +public: + static OpenXRCompositionLayerDepthExtension *get_singleton(); -#define GDCINULL(CNAME) \ -CNAME *(*CNAME::_create)() = nullptr; + OpenXRCompositionLayerDepthExtension(OpenXRAPI *p_openxr_api); + virtual ~OpenXRCompositionLayerDepthExtension() override; -#define GDCIIMPL(IMPNAME, CNAME) \ -public:\ - static CNAME *_create() { return memnew(IMPNAME); }\ - static void make_default() { CNAME::_create = IMPNAME::_create; }\ -protected:\ -/* clang-format on */ + bool is_available(); + virtual XrCompositionLayerBaseHeader *get_composition_layer() override; -#endif // WEBSOCKET_MACROS_H +private: + static OpenXRCompositionLayerDepthExtension *singleton; + + bool available = false; +}; + +#endif // OPENXR_COMPOSITION_LAYER_DEPTH_EXTENSION_H diff --git a/modules/openxr/extensions/openxr_composition_layer_provider.h b/modules/openxr/extensions/openxr_composition_layer_provider.h index 019dffa2a8..a4c4cbe0c6 100644 --- a/modules/openxr/extensions/openxr_composition_layer_provider.h +++ b/modules/openxr/extensions/openxr_composition_layer_provider.h @@ -31,15 +31,15 @@ #ifndef OPENXR_COMPOSITION_LAYER_PROVIDER_H #define OPENXR_COMPOSITION_LAYER_PROVIDER_H +#include "openxr_extension_wrapper.h" #include <openxr/openxr.h> // Interface for OpenXR extensions that provide a composition layer. class OpenXRCompositionLayerProvider { public: - // TODO changed to normal method definition for now - // CI complains until we implement this, haven't ported it yet from plugin - // virtual XrCompositionLayerBaseHeader *get_composition_layer() = 0; - XrCompositionLayerBaseHeader *get_composition_layer() { return nullptr; }; + virtual XrCompositionLayerBaseHeader *get_composition_layer() = 0; + + virtual ~OpenXRCompositionLayerProvider() {} }; #endif // OPENXR_COMPOSITION_LAYER_PROVIDER_H diff --git a/modules/openxr/extensions/openxr_extension_wrapper.h b/modules/openxr/extensions/openxr_extension_wrapper.h index ecc6e0dd4e..c417c90d11 100644 --- a/modules/openxr/extensions/openxr_extension_wrapper.h +++ b/modules/openxr/extensions/openxr_extension_wrapper.h @@ -66,6 +66,7 @@ public: virtual void *set_session_create_and_get_next_pointer(void *p_next_pointer) { return p_next_pointer; } virtual void *set_swapchain_create_info_and_get_next_pointer(void *p_next_pointer) { return p_next_pointer; } + virtual void on_before_instance_created() {} virtual void on_instance_created(const XrInstance p_instance) {} virtual void on_instance_destroyed() {} virtual void on_session_created(const XrSession p_instance) {} @@ -87,6 +88,11 @@ public: return false; } + // Return false if this extension is responsible for this path but the path is not enabled + virtual bool is_path_supported(const String &p_path) { + return true; + } + OpenXRExtensionWrapper(OpenXRAPI *p_openxr_api) { openxr_api = p_openxr_api; }; virtual ~OpenXRExtensionWrapper() = default; }; @@ -94,11 +100,12 @@ public: class OpenXRGraphicsExtensionWrapper : public OpenXRExtensionWrapper { public: virtual void get_usable_swapchain_formats(Vector<int64_t> &p_usable_swap_chains) = 0; + virtual void get_usable_depth_formats(Vector<int64_t> &p_usable_swap_chains) = 0; virtual String get_swapchain_format_name(int64_t p_swapchain_format) const = 0; virtual bool get_swapchain_image_data(XrSwapchain p_swapchain, int64_t p_swapchain_format, uint32_t p_width, uint32_t p_height, uint32_t p_sample_count, uint32_t p_array_size, void **r_swapchain_graphics_data) = 0; virtual void cleanup_swapchain_graphics_data(void **p_swapchain_graphics_data) = 0; virtual bool create_projection_fov(const XrFovf p_fov, double p_z_near, double p_z_far, Projection &r_camera_matrix) = 0; - virtual bool copy_render_target_to_image(RID p_from_render_target, void *p_swapchain_graphics_data, int p_image_index) = 0; + virtual RID get_texture(void *p_swapchain_graphics_data, int p_image_index) = 0; OpenXRGraphicsExtensionWrapper(OpenXRAPI *p_openxr_api) : OpenXRExtensionWrapper(p_openxr_api){}; diff --git a/modules/openxr/extensions/openxr_fb_display_refresh_rate_extension.cpp b/modules/openxr/extensions/openxr_fb_display_refresh_rate_extension.cpp new file mode 100644 index 0000000000..c0bbaea5b4 --- /dev/null +++ b/modules/openxr/extensions/openxr_fb_display_refresh_rate_extension.cpp @@ -0,0 +1,123 @@ +/*************************************************************************/ +/* openxr_fb_display_refresh_rate_extension.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 "openxr_fb_display_refresh_rate_extension.h" + +OpenXRDisplayRefreshRateExtension *OpenXRDisplayRefreshRateExtension::singleton = nullptr; + +OpenXRDisplayRefreshRateExtension *OpenXRDisplayRefreshRateExtension::get_singleton() { + return singleton; +} + +OpenXRDisplayRefreshRateExtension::OpenXRDisplayRefreshRateExtension(OpenXRAPI *p_openxr_api) : + OpenXRExtensionWrapper(p_openxr_api) { + singleton = this; + + // Extensions we use for our hand tracking. + request_extensions[XR_FB_DISPLAY_REFRESH_RATE_EXTENSION_NAME] = &display_refresh_rate_ext; +} + +OpenXRDisplayRefreshRateExtension::~OpenXRDisplayRefreshRateExtension() { + display_refresh_rate_ext = false; +} + +void OpenXRDisplayRefreshRateExtension::on_instance_created(const XrInstance p_instance) { + if (display_refresh_rate_ext) { + EXT_INIT_XR_FUNC(xrEnumerateDisplayRefreshRatesFB); + EXT_INIT_XR_FUNC(xrGetDisplayRefreshRateFB); + EXT_INIT_XR_FUNC(xrRequestDisplayRefreshRateFB); + } +} + +void OpenXRDisplayRefreshRateExtension::on_instance_destroyed() { + display_refresh_rate_ext = false; +} + +float OpenXRDisplayRefreshRateExtension::get_refresh_rate() const { + float refresh_rate = 0.0; + + if (display_refresh_rate_ext) { + float rate; + XrResult result = xrGetDisplayRefreshRateFB(openxr_api->get_session(), &rate); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to obtain refresh rate [", openxr_api->get_error_string(result), "]"); + } else { + refresh_rate = rate; + } + } + + return refresh_rate; +} + +void OpenXRDisplayRefreshRateExtension::set_refresh_rate(float p_refresh_rate) { + if (display_refresh_rate_ext) { + XrResult result = xrRequestDisplayRefreshRateFB(openxr_api->get_session(), p_refresh_rate); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to set refresh rate [", openxr_api->get_error_string(result), "]"); + } + } +} + +Array OpenXRDisplayRefreshRateExtension::get_available_refresh_rates() const { + Array arr; + XrResult result; + + if (display_refresh_rate_ext) { + uint32_t display_refresh_rate_count = 0; + result = xrEnumerateDisplayRefreshRatesFB(openxr_api->get_session(), 0, &display_refresh_rate_count, nullptr); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to obtain refresh rates count [", openxr_api->get_error_string(result), "]"); + } + + if (display_refresh_rate_count > 0) { + float *display_refresh_rates = (float *)memalloc(sizeof(float) * display_refresh_rate_count); + if (display_refresh_rates == nullptr) { + print_line("OpenXR: Failed to obtain refresh rates memory buffer [", openxr_api->get_error_string(result), "]"); + return arr; + } + + result = xrEnumerateDisplayRefreshRatesFB(openxr_api->get_session(), display_refresh_rate_count, &display_refresh_rate_count, display_refresh_rates); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to obtain refresh rates count [", openxr_api->get_error_string(result), "]"); + memfree(display_refresh_rates); + return arr; + } + + for (uint32_t i = 0; i < display_refresh_rate_count; i++) { + float refresh_rate = display_refresh_rates[i]; + arr.push_back(Variant(refresh_rate)); + } + + memfree(display_refresh_rates); + } + } + + return arr; +} diff --git a/modules/openxr/extensions/openxr_fb_display_refresh_rate_extension.h b/modules/openxr/extensions/openxr_fb_display_refresh_rate_extension.h new file mode 100644 index 0000000000..dcd52fe4d1 --- /dev/null +++ b/modules/openxr/extensions/openxr_fb_display_refresh_rate_extension.h @@ -0,0 +1,70 @@ +/*************************************************************************/ +/* openxr_fb_display_refresh_rate_extension.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 OPENXR_FB_DISPLAY_REFRESH_RATE_EXTENSION_H +#define OPENXR_FB_DISPLAY_REFRESH_RATE_EXTENSION_H + +// This extension gives us access to the possible display refresh rates +// supported by the HMD. +// While this is an FB extension it has been adopted by most runtimes and +// will likely become core in the near future. + +#include "../openxr_api.h" +#include "../util.h" + +#include "openxr_extension_wrapper.h" + +class OpenXRDisplayRefreshRateExtension : public OpenXRExtensionWrapper { +public: + static OpenXRDisplayRefreshRateExtension *get_singleton(); + + OpenXRDisplayRefreshRateExtension(OpenXRAPI *p_openxr_api); + virtual ~OpenXRDisplayRefreshRateExtension() override; + + virtual void on_instance_created(const XrInstance p_instance) override; + virtual void on_instance_destroyed() override; + + float get_refresh_rate() const; + void set_refresh_rate(float p_refresh_rate); + + Array get_available_refresh_rates() const; + +private: + static OpenXRDisplayRefreshRateExtension *singleton; + + bool display_refresh_rate_ext = false; + + // OpenXR API call wrappers + EXT_PROTO_XRRESULT_FUNC4(xrEnumerateDisplayRefreshRatesFB, (XrSession), session, (uint32_t), displayRefreshRateCapacityInput, (uint32_t *), displayRefreshRateCountOutput, (float *), displayRefreshRates); + EXT_PROTO_XRRESULT_FUNC2(xrGetDisplayRefreshRateFB, (XrSession), session, (float *), display_refresh_rate); + EXT_PROTO_XRRESULT_FUNC2(xrRequestDisplayRefreshRateFB, (XrSession), session, (float), display_refresh_rate); +}; + +#endif // OPENXR_FB_DISPLAY_REFRESH_RATE_EXTENSION_H diff --git a/modules/openxr/extensions/openxr_fb_passthrough_extension_wrapper.cpp b/modules/openxr/extensions/openxr_fb_passthrough_extension_wrapper.cpp new file mode 100644 index 0000000000..259b1236a3 --- /dev/null +++ b/modules/openxr/extensions/openxr_fb_passthrough_extension_wrapper.cpp @@ -0,0 +1,234 @@ +/*************************************************************************/ +/* openxr_fb_passthrough_extension_wrapper.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 "openxr_fb_passthrough_extension_wrapper.h" + +#include "core/os/os.h" +#include "scene/main/viewport.h" +#include "scene/main/window.h" + +using namespace godot; + +OpenXRFbPassthroughExtensionWrapper *OpenXRFbPassthroughExtensionWrapper::singleton = nullptr; + +OpenXRFbPassthroughExtensionWrapper *OpenXRFbPassthroughExtensionWrapper::get_singleton() { + return singleton; +} + +OpenXRFbPassthroughExtensionWrapper::OpenXRFbPassthroughExtensionWrapper(OpenXRAPI *p_openxr_api) : + OpenXRExtensionWrapper(p_openxr_api) { + request_extensions[XR_FB_PASSTHROUGH_EXTENSION_NAME] = &fb_passthrough_ext; + request_extensions[XR_FB_TRIANGLE_MESH_EXTENSION_NAME] = &fb_triangle_mesh_ext; + singleton = this; +} + +OpenXRFbPassthroughExtensionWrapper::~OpenXRFbPassthroughExtensionWrapper() { + cleanup(); +} + +void OpenXRFbPassthroughExtensionWrapper::cleanup() { + fb_passthrough_ext = false; + fb_triangle_mesh_ext = false; +} + +Viewport *OpenXRFbPassthroughExtensionWrapper::get_main_viewport() { + MainLoop *main_loop = OS::get_singleton()->get_main_loop(); + if (!main_loop) { + print_error("Unable to retrieve main loop"); + return nullptr; + } + + auto *scene_tree = Object::cast_to<SceneTree>(main_loop); + if (!scene_tree) { + print_error("Unable to retrieve scene tree"); + return nullptr; + } + + Viewport *viewport = scene_tree->get_root()->get_viewport(); + return viewport; +} + +void OpenXRFbPassthroughExtensionWrapper::on_instance_created(const XrInstance instance) { + if (fb_passthrough_ext) { + bool result = initialize_fb_passthrough_extension(instance); + if (!result) { + print_error("Failed to initialize fb_passthrough extension"); + fb_passthrough_ext = false; + } + } + + if (fb_triangle_mesh_ext) { + bool result = initialize_fb_triangle_mesh_extension(instance); + if (!result) { + print_error("Failed to initialize fb_triangle_mesh extension"); + fb_triangle_mesh_ext = false; + } + } + + if (fb_passthrough_ext) { + openxr_api->register_composition_layer_provider(this); + } +} + +bool OpenXRFbPassthroughExtensionWrapper::is_passthrough_enabled() { + return fb_passthrough_ext && passthrough_handle != XR_NULL_HANDLE && passthrough_layer != XR_NULL_HANDLE; +} + +bool OpenXRFbPassthroughExtensionWrapper::is_composition_passthrough_layer_ready() { + return fb_passthrough_ext && passthrough_handle != XR_NULL_HANDLE && composition_passthrough_layer.layerHandle != XR_NULL_HANDLE; +} + +bool OpenXRFbPassthroughExtensionWrapper::start_passthrough() { + if (passthrough_handle == XR_NULL_HANDLE) { + return false; + } + + if (is_passthrough_enabled()) { + return true; + } + + // Start the passthrough feature + XrResult result = xrPassthroughStartFB(passthrough_handle); + if (!is_valid_passthrough_result(result, "Failed to start passthrough")) { + stop_passthrough(); + return false; + } + + // Create the passthrough layer + result = xrCreatePassthroughLayerFB(openxr_api->get_session(), &passthrough_layer_config, &passthrough_layer); + if (!is_valid_passthrough_result(result, "Failed to create the passthrough layer")) { + stop_passthrough(); + return false; + } + + // Check if the the viewport has transparent background + Viewport *viewport = get_main_viewport(); + if (viewport && !viewport->has_transparent_background()) { + print_error("Main viewport doesn't have transparent background! Passthrough may not properly render."); + } + + composition_passthrough_layer.layerHandle = passthrough_layer; + + return true; +} + +void OpenXRFbPassthroughExtensionWrapper::on_session_created(const XrSession session) { + if (fb_passthrough_ext) { + // Create the passthrough feature and start it. + XrResult result = xrCreatePassthroughFB(openxr_api->get_session(), &passthrough_create_info, &passthrough_handle); + if (!openxr_api->xr_result(result, "Failed to create passthrough")) { + passthrough_handle = XR_NULL_HANDLE; + return; + } + } +} + +XrCompositionLayerBaseHeader *OpenXRFbPassthroughExtensionWrapper::get_composition_layer() { + if (is_composition_passthrough_layer_ready()) { + return (XrCompositionLayerBaseHeader *)&composition_passthrough_layer; + } else { + return nullptr; + } +} + +void OpenXRFbPassthroughExtensionWrapper::stop_passthrough() { + if (!fb_passthrough_ext) { + return; + } + + composition_passthrough_layer.layerHandle = XR_NULL_HANDLE; + + XrResult result; + if (passthrough_layer != XR_NULL_HANDLE) { + // Destroy the layer + result = xrDestroyPassthroughLayerFB(passthrough_layer); + openxr_api->xr_result(result, "Unable to destroy passthrough layer"); + passthrough_layer = XR_NULL_HANDLE; + } + + if (passthrough_handle != XR_NULL_HANDLE) { + result = xrPassthroughPauseFB(passthrough_handle); + openxr_api->xr_result(result, "Unable to stop passthrough feature"); + } +} + +void OpenXRFbPassthroughExtensionWrapper::on_session_destroyed() { + if (fb_passthrough_ext) { + stop_passthrough(); + + XrResult result; + if (passthrough_handle != XR_NULL_HANDLE) { + result = xrDestroyPassthroughFB(passthrough_handle); + openxr_api->xr_result(result, "Unable to destroy passthrough feature"); + passthrough_handle = XR_NULL_HANDLE; + } + } +} + +void OpenXRFbPassthroughExtensionWrapper::on_instance_destroyed() { + if (fb_passthrough_ext) { + openxr_api->unregister_composition_layer_provider(this); + } + cleanup(); +} + +bool OpenXRFbPassthroughExtensionWrapper::initialize_fb_passthrough_extension(const XrInstance p_instance) { + ERR_FAIL_NULL_V(openxr_api, false); + + EXT_INIT_XR_FUNC_V(xrCreatePassthroughFB); + EXT_INIT_XR_FUNC_V(xrDestroyPassthroughFB); + EXT_INIT_XR_FUNC_V(xrPassthroughStartFB); + EXT_INIT_XR_FUNC_V(xrPassthroughPauseFB); + EXT_INIT_XR_FUNC_V(xrCreatePassthroughLayerFB); + EXT_INIT_XR_FUNC_V(xrDestroyPassthroughLayerFB); + EXT_INIT_XR_FUNC_V(xrPassthroughLayerPauseFB); + EXT_INIT_XR_FUNC_V(xrPassthroughLayerResumeFB); + EXT_INIT_XR_FUNC_V(xrPassthroughLayerSetStyleFB); + EXT_INIT_XR_FUNC_V(xrCreateGeometryInstanceFB); + EXT_INIT_XR_FUNC_V(xrDestroyGeometryInstanceFB); + EXT_INIT_XR_FUNC_V(xrGeometryInstanceSetTransformFB); + + return true; +} + +bool OpenXRFbPassthroughExtensionWrapper::initialize_fb_triangle_mesh_extension(const XrInstance p_instance) { + ERR_FAIL_NULL_V(openxr_api, false); + + EXT_INIT_XR_FUNC_V(xrCreateTriangleMeshFB); + EXT_INIT_XR_FUNC_V(xrDestroyTriangleMeshFB); + EXT_INIT_XR_FUNC_V(xrTriangleMeshGetVertexBufferFB); + EXT_INIT_XR_FUNC_V(xrTriangleMeshGetIndexBufferFB); + EXT_INIT_XR_FUNC_V(xrTriangleMeshBeginUpdateFB); + EXT_INIT_XR_FUNC_V(xrTriangleMeshEndUpdateFB); + EXT_INIT_XR_FUNC_V(xrTriangleMeshBeginVertexBufferUpdateFB); + EXT_INIT_XR_FUNC_V(xrTriangleMeshEndVertexBufferUpdateFB); + + return true; +} diff --git a/modules/openxr/extensions/openxr_fb_passthrough_extension_wrapper.h b/modules/openxr/extensions/openxr_fb_passthrough_extension_wrapper.h new file mode 100644 index 0000000000..1959f3fdc4 --- /dev/null +++ b/modules/openxr/extensions/openxr_fb_passthrough_extension_wrapper.h @@ -0,0 +1,254 @@ +/*************************************************************************/ +/* openxr_fb_passthrough_extension_wrapper.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 OPENXR_FB_PASSTHROUGH_EXTENSION_WRAPPER_H +#define OPENXR_FB_PASSTHROUGH_EXTENSION_WRAPPER_H + +#include "../openxr_api.h" +#include "../util.h" + +#include "openxr_composition_layer_provider.h" +#include "openxr_extension_wrapper.h" + +#include <map> + +class Viewport; + +// Wrapper for the set of Facebook XR passthrough extensions. +class OpenXRFbPassthroughExtensionWrapper : public OpenXRExtensionWrapper, public OpenXRCompositionLayerProvider { + friend class OpenXRAPI; + +public: + void on_instance_created(const XrInstance instance) override; + + void on_session_created(const XrSession session) override; + + void on_session_destroyed() override; + + void on_instance_destroyed() override; + + XrCompositionLayerBaseHeader *get_composition_layer() override; + + bool is_passthrough_supported() { + return fb_passthrough_ext; + } + + bool is_passthrough_enabled(); + + bool start_passthrough(); + + void stop_passthrough(); + + static OpenXRFbPassthroughExtensionWrapper *get_singleton(); + +protected: + OpenXRFbPassthroughExtensionWrapper(OpenXRAPI *p_openxr_api); + ~OpenXRFbPassthroughExtensionWrapper(); + +private: + // Create a passthrough feature + EXT_PROTO_XRRESULT_FUNC3(xrCreatePassthroughFB, + (XrSession), session, + (const XrPassthroughCreateInfoFB *), create_info, + (XrPassthroughFB *), feature_out) + + // Destroy a previously created passthrough feature + EXT_PROTO_XRRESULT_FUNC1(xrDestroyPassthroughFB, (XrPassthroughFB), feature) + + //*** Passthrough feature state management functions ********* + // Start the passthrough feature + EXT_PROTO_XRRESULT_FUNC1(xrPassthroughStartFB, (XrPassthroughFB), passthrough) + // Pause the passthrough feature + EXT_PROTO_XRRESULT_FUNC1(xrPassthroughPauseFB, (XrPassthroughFB), passthrough) + + EXT_PROTO_XRRESULT_FUNC3(xrCreatePassthroughLayerFB, (XrSession), session, + (const XrPassthroughLayerCreateInfoFB *), config, + (XrPassthroughLayerFB *), layer_out) + + EXT_PROTO_XRRESULT_FUNC1(xrDestroyPassthroughLayerFB, (XrPassthroughLayerFB), layer) + + EXT_PROTO_XRRESULT_FUNC1(xrPassthroughLayerPauseFB, (XrPassthroughLayerFB), layer) + EXT_PROTO_XRRESULT_FUNC1(xrPassthroughLayerResumeFB, (XrPassthroughLayerFB), layer) + + // Set the style of an existing passthrough layer. If the enabled feature set + // doesn’t change, this is a lightweight operation that can be called in every + // frame to animate the style. Changes that may incur a bigger cost: + // - Enabling/disabling the color mapping, or changing the type of mapping + // (monochromatic to RGBA or back). + // - Changing `textureOpacityFactor` from 0 to non-zero or vice versa + // - Changing `edgeColor[3]` from 0 to non-zero or vice versa + // NOTE: For XR_FB_passthrough, all color values are treated as linear. + EXT_PROTO_XRRESULT_FUNC2(xrPassthroughLayerSetStyleFB, + (XrPassthroughLayerFB), layer, + (const XrPassthroughStyleFB *), style) + + // Create a geometry instance to be used as a projection surface for passthrough. + // A geometry instance assigns a triangle mesh as part of the specified layer's + // projection surface. + // The operation is only valid if the passthrough layer's purpose has been set to + // `XR_PASSTHROUGH_LAYER_PURPOSE_PROJECTED_FB`. Otherwise, the call this function will + // result in an error. In the specified layer, Passthrough will be visible where the view + // is covered by the user-specified geometries. + // + // A triangle mesh object can be instantiated multiple times - in the same or different layers' + // projection surface. Each instantiation has its own transformation, which + // can be updated using `xrGeometryInstanceSetTransformFB`. + EXT_PROTO_XRRESULT_FUNC3(xrCreateGeometryInstanceFB, + (XrSession), session, + (const XrGeometryInstanceCreateInfoFB *), create_info, + (XrGeometryInstanceFB *), out_geometry_instance) + + // Destroys a previously created geometry instance from passthrough rendering. + // This removes the geometry instance from passthrough rendering. + // The operation has no effect on other instances or the underlying mesh. + EXT_PROTO_XRRESULT_FUNC1(xrDestroyGeometryInstanceFB, (XrGeometryInstanceFB), instance) + + // Update the transformation of a passthrough geometry instance. + EXT_PROTO_XRRESULT_FUNC2(xrGeometryInstanceSetTransformFB, + (XrGeometryInstanceFB), instance, + (const XrGeometryInstanceTransformFB *), transformation) + + // Create a triangle mesh geometry object. + // Depending on the behavior flags, the mesh could be created immutable (data is assigned + // at creation and cannot be changed) or mutable (the mesh is created empty and can be updated + // by calling begin/end update functions). + EXT_PROTO_XRRESULT_FUNC3(xrCreateTriangleMeshFB, + (XrSession), session, + (const XrTriangleMeshCreateInfoFB *), create_info, + (XrTriangleMeshFB *), out_triangle_mesh) + + // Destroy an `XrTriangleMeshFB` object along with its data. The mesh buffers must not be + // accessed anymore after their parent mesh object has been destroyed. + EXT_PROTO_XRRESULT_FUNC1(xrDestroyTriangleMeshFB, (XrTriangleMeshFB), mesh) + + // Retrieve a pointer to the vertex buffer. The vertex buffer is structured as an array of 3 floats + // per vertex representing x, y, and z: `[x0, y0, z0, x1, y1, z1, ...]`. The size of the buffer is + // `maxVertexCount * 3` floats. The application must call `xrTriangleMeshBeginUpdateFB` or + // `xrTriangleMeshBeginVertexBufferUpdateFB` before making modifications to the vertex + // buffer. The buffer location is guaranteed to remain constant over the lifecycle of the mesh + // object. + EXT_PROTO_XRRESULT_FUNC2(xrTriangleMeshGetVertexBufferFB, + (XrTriangleMeshFB), mesh, + (XrVector3f **), out_vertex_buffer) + + // Retrieve the index buffer that defines the topology of the triangle mesh. Each triplet of + // consecutive elements point to three vertices in the vertex buffer and thus form a triangle. The + // size of each element is `indexElementSize` bytes, and thus the size of the buffer is + // `maxTriangleCount * 3 * indexElementSize` bytes. The application must call + // `xrTriangleMeshBeginUpdateFB` before making modifications to the index buffer. The buffer + // location is guaranteed to remain constant over the lifecycle of the mesh object. + EXT_PROTO_XRRESULT_FUNC2(xrTriangleMeshGetIndexBufferFB, + (XrTriangleMeshFB), mesh, + (uint32_t **), out_index_buffer) + + // Begin updating the mesh buffer data. The application must call this function before it makes any + // modifications to the buffers retrieved by `xrTriangleMeshGetVertexBufferFB` and + // `xrTriangleMeshGetIndexBufferFB`. If only the vertex buffer needs to be updated, + // `xrTriangleMeshBeginVertexBufferUpdateFB` can be used instead. To commit the + // modifications, the application must call `xrTriangleMeshEndUpdateFB`. + EXT_PROTO_XRRESULT_FUNC1(xrTriangleMeshBeginUpdateFB, (XrTriangleMeshFB), mesh) + + // Signal the API that the application has finished updating the mesh buffers after a call to + // `xrTriangleMeshBeginUpdateFB`. `vertexCount` and `triangleCount` specify the actual + // number of primitives that make up the mesh after the update. They must be larger than zero but + // smaller or equal to the maximum counts defined at create time. Buffer data beyond these counts + // is ignored. + EXT_PROTO_XRRESULT_FUNC3(xrTriangleMeshEndUpdateFB, + (XrTriangleMeshFB), mesh, + (uint32_t), vertexCount, + (uint32_t), triangle_count) + + // Update the vertex positions of a triangle mesh. Can only be called once the mesh topology has + // been set using `xrTriangleMeshBeginUpdateFB`/`xrTriangleMeshEndUpdateFB`. The + // vertex count is defined by the last invocation to `xrTriangleMeshEndUpdateFB`. Once the + // modification is done, `xrTriangleMeshEndVertexBufferUpdateFB` must be called. + EXT_PROTO_XRRESULT_FUNC2(xrTriangleMeshBeginVertexBufferUpdateFB, + (XrTriangleMeshFB), mesh, + (uint32_t *), out_vertex_count) + + // Signal the API that the contents of the vertex buffer data has been updated + // after a call to `xrTriangleMeshBeginVertexBufferUpdateFB`. + EXT_PROTO_XRRESULT_FUNC1(xrTriangleMeshEndVertexBufferUpdateFB, (XrTriangleMeshFB), mesh) + + bool initialize_fb_passthrough_extension(const XrInstance instance); + + bool initialize_fb_triangle_mesh_extension(const XrInstance instance); + + void cleanup(); + + // TODO: Temporary workaround (https://github.com/GodotVR/godot_openxr/issues/138) + // Address a bug in the passthrough api where XR_ERROR_UNEXPECTED_STATE_PASSTHROUGH_FB is + // returned even when the operation is valid on Meta Quest devices. + // The issue should be addressed on that platform in OS release v37. + inline bool is_valid_passthrough_result(XrResult result, const char *format) { + return openxr_api->xr_result(result, format) || result == XR_ERROR_UNEXPECTED_STATE_PASSTHROUGH_FB; + } + + Viewport *get_main_viewport(); + + bool is_composition_passthrough_layer_ready(); + + static OpenXRFbPassthroughExtensionWrapper *singleton; + + bool fb_passthrough_ext = false; // required for any passthrough functionality + bool fb_triangle_mesh_ext = false; // only use for projected passthrough + + XrPassthroughCreateInfoFB passthrough_create_info = { + XR_TYPE_PASSTHROUGH_CREATE_INFO_FB, + nullptr, + 0, + }; + XrPassthroughFB passthrough_handle = XR_NULL_HANDLE; + + XrPassthroughLayerCreateInfoFB passthrough_layer_config = { + XR_TYPE_PASSTHROUGH_LAYER_CREATE_INFO_FB, + nullptr, + passthrough_handle, + XR_PASSTHROUGH_IS_RUNNING_AT_CREATION_BIT_FB, + XR_PASSTHROUGH_LAYER_PURPOSE_RECONSTRUCTION_FB, + }; + XrPassthroughStyleFB passthrough_layer_style = { + XR_TYPE_PASSTHROUGH_STYLE_FB, + nullptr, + 1, + { 0, 0, 0, 0 }, + }; + XrPassthroughLayerFB passthrough_layer = XR_NULL_HANDLE; + + XrCompositionLayerPassthroughFB composition_passthrough_layer = { + XR_TYPE_COMPOSITION_LAYER_PASSTHROUGH_FB, + nullptr, + XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT, + XR_NULL_HANDLE, + XR_NULL_HANDLE, + }; +}; + +#endif // OPENXR_FB_PASSTHROUGH_EXTENSION_WRAPPER_H diff --git a/modules/openxr/extensions/openxr_hand_tracking_extension.cpp b/modules/openxr/extensions/openxr_hand_tracking_extension.cpp new file mode 100644 index 0000000000..85e2ee4903 --- /dev/null +++ b/modules/openxr/extensions/openxr_hand_tracking_extension.cpp @@ -0,0 +1,268 @@ +/*************************************************************************/ +/* openxr_hand_tracking_extension.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 "openxr_hand_tracking_extension.h" +#include "../openxr_api.h" +#include "core/string/print_string.h" +#include "servers/xr_server.h" + +#include <openxr/openxr.h> + +OpenXRHandTrackingExtension *OpenXRHandTrackingExtension::singleton = nullptr; + +OpenXRHandTrackingExtension *OpenXRHandTrackingExtension::get_singleton() { + return singleton; +} + +OpenXRHandTrackingExtension::OpenXRHandTrackingExtension(OpenXRAPI *p_openxr_api) : + OpenXRExtensionWrapper(p_openxr_api) { + singleton = this; + + // Extensions we use for our hand tracking. + request_extensions[XR_EXT_HAND_TRACKING_EXTENSION_NAME] = &hand_tracking_ext; + request_extensions[XR_EXT_HAND_JOINTS_MOTION_RANGE_EXTENSION_NAME] = &hand_motion_range_ext; + request_extensions[XR_FB_HAND_TRACKING_AIM_EXTENSION_NAME] = &hand_tracking_aim_state_ext; + + // Make sure this is cleared until we actually request it + handTrackingSystemProperties.supportsHandTracking = false; +} + +OpenXRHandTrackingExtension::~OpenXRHandTrackingExtension() { + singleton = nullptr; +} + +void OpenXRHandTrackingExtension::on_instance_created(const XrInstance p_instance) { + if (hand_tracking_ext) { + EXT_INIT_XR_FUNC(xrCreateHandTrackerEXT); + EXT_INIT_XR_FUNC(xrDestroyHandTrackerEXT); + EXT_INIT_XR_FUNC(xrLocateHandJointsEXT); + + hand_tracking_ext = xrCreateHandTrackerEXT_ptr && xrDestroyHandTrackerEXT_ptr && xrLocateHandJointsEXT_ptr; + } +} + +void OpenXRHandTrackingExtension::on_session_destroyed() { + cleanup_hand_tracking(); +} + +void OpenXRHandTrackingExtension::on_instance_destroyed() { + xrCreateHandTrackerEXT_ptr = nullptr; + xrDestroyHandTrackerEXT_ptr = nullptr; + xrLocateHandJointsEXT_ptr = nullptr; +} + +void *OpenXRHandTrackingExtension::set_system_properties_and_get_next_pointer(void *p_next_pointer) { + if (!hand_tracking_ext) { + // not supported... + return p_next_pointer; + } + + handTrackingSystemProperties = { + XR_TYPE_SYSTEM_HAND_TRACKING_PROPERTIES_EXT, // type + p_next_pointer, // next + false, // supportsHandTracking + }; + + return &handTrackingSystemProperties; +} + +void OpenXRHandTrackingExtension::on_state_ready() { + if (!handTrackingSystemProperties.supportsHandTracking) { + // not supported... + return; + } + + // Setup our hands and reset data + for (int i = 0; i < MAX_OPENXR_TRACKED_HANDS; i++) { + // we'll do this later + hand_trackers[i].is_initialized = false; + hand_trackers[i].hand_tracker = XR_NULL_HANDLE; + + hand_trackers[i].aimState.aimPose = { { 0.0, 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0 } }; + hand_trackers[i].aimState.pinchStrengthIndex = 0.0; + hand_trackers[i].aimState.pinchStrengthMiddle = 0.0; + hand_trackers[i].aimState.pinchStrengthRing = 0.0; + hand_trackers[i].aimState.pinchStrengthLittle = 0.0; + + hand_trackers[i].locations.isActive = false; + + for (int j = 0; j < XR_HAND_JOINT_COUNT_EXT; j++) { + hand_trackers[i].joint_locations[j] = { 0, { { 0.0, 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0 } }, 0.0 }; + hand_trackers[i].joint_velocities[j] = { 0, { 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0 } }; + } + } +} + +void OpenXRHandTrackingExtension::on_process() { + if (!handTrackingSystemProperties.supportsHandTracking) { + // not supported... + return; + } + + // process our hands + const XrTime time = openxr_api->get_next_frame_time(); // This data will be used for the next frame we render + + XrResult result; + + for (int i = 0; i < MAX_OPENXR_TRACKED_HANDS; i++) { + if (hand_trackers[i].hand_tracker == XR_NULL_HANDLE) { + XrHandTrackerCreateInfoEXT createInfo = { + XR_TYPE_HAND_TRACKER_CREATE_INFO_EXT, // type + nullptr, // next + i == 0 ? XR_HAND_LEFT_EXT : XR_HAND_RIGHT_EXT, // hand + XR_HAND_JOINT_SET_DEFAULT_EXT, // handJointSet + }; + + result = xrCreateHandTrackerEXT(openxr_api->get_session(), &createInfo, &hand_trackers[i].hand_tracker); + if (XR_FAILED(result)) { + // not successful? then we do nothing. + print_line("OpenXR: Failed to obtain hand tracking information [", openxr_api->get_error_string(result), "]"); + hand_trackers[i].is_initialized = false; + } else { + void *next_pointer = nullptr; + if (hand_tracking_aim_state_ext) { + hand_trackers[i].aimState.type = XR_TYPE_HAND_TRACKING_AIM_STATE_FB; + hand_trackers[i].aimState.next = next_pointer; + hand_trackers[i].aimState.status = 0; + hand_trackers[i].aimState.aimPose = { { 0.0, 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0 } }; + hand_trackers[i].aimState.pinchStrengthIndex = 0.0; + hand_trackers[i].aimState.pinchStrengthMiddle = 0.0; + hand_trackers[i].aimState.pinchStrengthRing = 0.0; + hand_trackers[i].aimState.pinchStrengthLittle = 0.0; + + next_pointer = &hand_trackers[i].aimState; + } + + hand_trackers[i].velocities.type = XR_TYPE_HAND_JOINT_VELOCITIES_EXT; + hand_trackers[i].velocities.next = next_pointer; + hand_trackers[i].velocities.jointCount = XR_HAND_JOINT_COUNT_EXT; + hand_trackers[i].velocities.jointVelocities = hand_trackers[i].joint_velocities; + next_pointer = &hand_trackers[i].velocities; + + hand_trackers[i].locations.type = XR_TYPE_HAND_JOINT_LOCATIONS_EXT; + hand_trackers[i].locations.next = next_pointer; + hand_trackers[i].locations.isActive = false; + hand_trackers[i].locations.jointCount = XR_HAND_JOINT_COUNT_EXT; + hand_trackers[i].locations.jointLocations = hand_trackers[i].joint_locations; + + hand_trackers[i].is_initialized = true; + } + } + + if (hand_trackers[i].is_initialized) { + void *next_pointer = nullptr; + + XrHandJointsMotionRangeInfoEXT motionRangeInfo; + + if (hand_motion_range_ext) { + motionRangeInfo.type = XR_TYPE_HAND_JOINTS_MOTION_RANGE_INFO_EXT; + motionRangeInfo.next = next_pointer; + motionRangeInfo.handJointsMotionRange = hand_trackers[i].motion_range; + + next_pointer = &motionRangeInfo; + } + + XrHandJointsLocateInfoEXT locateInfo = { + XR_TYPE_HAND_JOINTS_LOCATE_INFO_EXT, // type + next_pointer, // next + openxr_api->get_play_space(), // baseSpace + time, // time + }; + + result = xrLocateHandJointsEXT(hand_trackers[i].hand_tracker, &locateInfo, &hand_trackers[i].locations); + if (XR_FAILED(result)) { + // not successful? then we do nothing. + print_line("OpenXR: Failed to get tracking for hand", i, "[", openxr_api->get_error_string(result), "]"); + continue; + } + + // For some reason an inactive controller isn't coming back as inactive but has coordinates either as NAN or very large + const XrPosef &palm = hand_trackers[i].joint_locations[XR_HAND_JOINT_PALM_EXT].pose; + if ( + !hand_trackers[i].locations.isActive || isnan(palm.position.x) || palm.position.x < -1000000.00 || palm.position.x > 1000000.00) { + hand_trackers[i].locations.isActive = false; // workaround, make sure its inactive + } + + /* TODO change this to managing the controller from openxr_interface + if (hand_tracking_aim_state_ext && hand_trackers[i].locations.isActive && check_bit(XR_HAND_TRACKING_AIM_VALID_BIT_FB, hand_trackers[i].aimState.status)) { + // Controllers are updated based on the aim state's pose and pinches' strength + if (hand_trackers[i].aim_state_godot_controller == -1) { + hand_trackers[i].aim_state_godot_controller = + arvr_api->godot_arvr_add_controller( + const_cast<char *>(hand_controller_names[i]), + i + HAND_CONTROLLER_ID_OFFSET, + true, + true); + } + } + */ + } + } +} + +void OpenXRHandTrackingExtension::on_state_stopping() { + // cleanup + cleanup_hand_tracking(); +} + +void OpenXRHandTrackingExtension::cleanup_hand_tracking() { + XRServer *xr_server = XRServer::get_singleton(); + ERR_FAIL_NULL(xr_server); + + for (int i = 0; i < MAX_OPENXR_TRACKED_HANDS; i++) { + if (hand_trackers[i].hand_tracker != XR_NULL_HANDLE) { + xrDestroyHandTrackerEXT(hand_trackers[i].hand_tracker); + + hand_trackers[i].is_initialized = false; + hand_trackers[i].hand_tracker = XR_NULL_HANDLE; + } + } +} + +bool OpenXRHandTrackingExtension::get_active() { + return handTrackingSystemProperties.supportsHandTracking; +} + +const OpenXRHandTrackingExtension::HandTracker *OpenXRHandTrackingExtension::get_hand_tracker(uint32_t p_hand) const { + ERR_FAIL_UNSIGNED_INDEX_V(p_hand, MAX_OPENXR_TRACKED_HANDS, nullptr); + + return &hand_trackers[p_hand]; +} + +XrHandJointsMotionRangeEXT OpenXRHandTrackingExtension::get_motion_range(uint32_t p_hand) const { + ERR_FAIL_UNSIGNED_INDEX_V(p_hand, MAX_OPENXR_TRACKED_HANDS, XR_HAND_JOINTS_MOTION_RANGE_MAX_ENUM_EXT); + + return hand_trackers[p_hand].motion_range; +} + +void OpenXRHandTrackingExtension::set_motion_range(uint32_t p_hand, XrHandJointsMotionRangeEXT p_motion_range) { + ERR_FAIL_UNSIGNED_INDEX(p_hand, MAX_OPENXR_TRACKED_HANDS); + hand_trackers[p_hand].motion_range = p_motion_range; +} diff --git a/modules/openxr/extensions/openxr_hand_tracking_extension.h b/modules/openxr/extensions/openxr_hand_tracking_extension.h new file mode 100644 index 0000000000..0eca80bcfb --- /dev/null +++ b/modules/openxr/extensions/openxr_hand_tracking_extension.h @@ -0,0 +1,96 @@ +/*************************************************************************/ +/* openxr_hand_tracking_extension.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 OPENXR_HAND_TRACKING_EXTENSION_H +#define OPENXR_HAND_TRACKING_EXTENSION_H + +#include "openxr_extension_wrapper.h" + +#include "../util.h" + +#define MAX_OPENXR_TRACKED_HANDS 2 + +class OpenXRHandTrackingExtension : public OpenXRExtensionWrapper { +public: + struct HandTracker { + bool is_initialized = false; + XrHandJointsMotionRangeEXT motion_range = XR_HAND_JOINTS_MOTION_RANGE_UNOBSTRUCTED_EXT; + + XrHandTrackerEXT hand_tracker = XR_NULL_HANDLE; + XrHandJointLocationEXT joint_locations[XR_HAND_JOINT_COUNT_EXT]; + XrHandJointVelocityEXT joint_velocities[XR_HAND_JOINT_COUNT_EXT]; + + XrHandTrackingAimStateFB aimState; + XrHandJointVelocitiesEXT velocities; + XrHandJointLocationsEXT locations; + }; + + static OpenXRHandTrackingExtension *get_singleton(); + + OpenXRHandTrackingExtension(OpenXRAPI *p_openxr_api); + virtual ~OpenXRHandTrackingExtension() override; + + virtual void on_instance_created(const XrInstance p_instance) override; + virtual void on_instance_destroyed() override; + virtual void on_session_destroyed() override; + + virtual void *set_system_properties_and_get_next_pointer(void *p_next_pointer) override; + virtual void on_state_ready() override; + virtual void on_process() override; + virtual void on_state_stopping() override; + + bool get_active(); + const HandTracker *get_hand_tracker(uint32_t p_hand) const; + + XrHandJointsMotionRangeEXT get_motion_range(uint32_t p_hand) const; + void set_motion_range(uint32_t p_hand, XrHandJointsMotionRangeEXT p_motion_range); + +private: + static OpenXRHandTrackingExtension *singleton; + + // state + XrSystemHandTrackingPropertiesEXT handTrackingSystemProperties; + HandTracker hand_trackers[MAX_OPENXR_TRACKED_HANDS]; // Fixed for left and right hand + + // related extensions + bool hand_tracking_ext = false; + bool hand_motion_range_ext = false; + bool hand_tracking_aim_state_ext = false; + + // functions + void cleanup_hand_tracking(); + + // OpenXR API call wrappers + EXT_PROTO_XRRESULT_FUNC3(xrCreateHandTrackerEXT, (XrSession), p_session, (const XrHandTrackerCreateInfoEXT *), p_createInfo, (XrHandTrackerEXT *), p_handTracker) + EXT_PROTO_XRRESULT_FUNC1(xrDestroyHandTrackerEXT, (XrHandTrackerEXT), p_handTracker) + EXT_PROTO_XRRESULT_FUNC3(xrLocateHandJointsEXT, (XrHandTrackerEXT), p_handTracker, (const XrHandJointsLocateInfoEXT *), p_locateInfo, (XrHandJointLocationsEXT *), p_locations) +}; + +#endif // OPENXR_HAND_TRACKING_EXTENSION_H diff --git a/modules/openxr/extensions/openxr_htc_vive_tracker_extension.cpp b/modules/openxr/extensions/openxr_htc_vive_tracker_extension.cpp index 302acf4e30..4d996e6283 100644 --- a/modules/openxr/extensions/openxr_htc_vive_tracker_extension.cpp +++ b/modules/openxr/extensions/openxr_htc_vive_tracker_extension.cpp @@ -65,3 +65,40 @@ bool OpenXRHTCViveTrackerExtension::on_event_polled(const XrEventDataBuffer &eve } break; } } + +bool OpenXRHTCViveTrackerExtension::is_path_supported(const String &p_path) { + if (p_path == "/interaction_profiles/htc/vive_tracker_htcx") { + return available; + } else if (p_path == "/user/vive_tracker_htcx/role/handheld_object") { + return available; + } else if (p_path == "/user/vive_tracker_htcx/role/left_foot") { + return available; + } else if (p_path == "/user/vive_tracker_htcx/role/right_foot") { + return available; + } else if (p_path == "/user/vive_tracker_htcx/role/left_shoulder") { + return available; + } else if (p_path == "/user/vive_tracker_htcx/role/right_shoulder") { + return available; + } else if (p_path == "/user/vive_tracker_htcx/role/left_elbow") { + return available; + } else if (p_path == "/user/vive_tracker_htcx/role/right_elbow") { + return available; + } else if (p_path == "/user/vive_tracker_htcx/role/left_knee") { + return available; + } else if (p_path == "/user/vive_tracker_htcx/role/right_knee") { + return available; + } else if (p_path == "/user/vive_tracker_htcx/role/waist") { + return available; + } else if (p_path == "/user/vive_tracker_htcx/role/chest") { + return available; + } else if (p_path == "/user/vive_tracker_htcx/role/chest") { + return available; + } else if (p_path == "/user/vive_tracker_htcx/role/camera") { + return available; + } else if (p_path == "/user/vive_tracker_htcx/role/keyboard") { + return available; + } + + // Not a path under this extensions control, so we return true; + return true; +} diff --git a/modules/openxr/extensions/openxr_htc_vive_tracker_extension.h b/modules/openxr/extensions/openxr_htc_vive_tracker_extension.h index 7f37351f27..ab8e8535f1 100644 --- a/modules/openxr/extensions/openxr_htc_vive_tracker_extension.h +++ b/modules/openxr/extensions/openxr_htc_vive_tracker_extension.h @@ -41,7 +41,9 @@ public: virtual ~OpenXRHTCViveTrackerExtension() override; bool is_available(); + virtual bool on_event_polled(const XrEventDataBuffer &event) override; + virtual bool is_path_supported(const String &p_path) override; private: static OpenXRHTCViveTrackerExtension *singleton; diff --git a/modules/openxr/extensions/openxr_opengl_extension.cpp b/modules/openxr/extensions/openxr_opengl_extension.cpp new file mode 100644 index 0000000000..ee69144123 --- /dev/null +++ b/modules/openxr/extensions/openxr_opengl_extension.cpp @@ -0,0 +1,466 @@ +/*************************************************************************/ +/* openxr_opengl_extension.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 GLES3_ENABLED + +#include "../extensions/openxr_opengl_extension.h" +#include "../openxr_util.h" +#include "drivers/gles3/effects/copy_effects.h" +#include "drivers/gles3/storage/texture_storage.h" +#include "servers/rendering/rendering_server_globals.h" +#include "servers/rendering_server.h" + +OpenXROpenGLExtension::OpenXROpenGLExtension(OpenXRAPI *p_openxr_api) : + OpenXRGraphicsExtensionWrapper(p_openxr_api) { +#ifdef ANDROID_ENABLED + request_extensions[XR_KHR_OPENGL_ES_ENABLE_EXTENSION_NAME] = nullptr; +#else + request_extensions[XR_KHR_OPENGL_ENABLE_EXTENSION_NAME] = nullptr; +#endif + + ERR_FAIL_NULL(openxr_api); +} + +OpenXROpenGLExtension::~OpenXROpenGLExtension() { +} + +void OpenXROpenGLExtension::on_instance_created(const XrInstance p_instance) { + ERR_FAIL_NULL(openxr_api); + + // Obtain pointers to functions we're accessing here. + +#ifdef ANDROID_ENABLED + EXT_INIT_XR_FUNC(xrGetOpenGLESGraphicsRequirementsKHR); +#else + EXT_INIT_XR_FUNC(xrGetOpenGLGraphicsRequirementsKHR); +#endif + EXT_INIT_XR_FUNC(xrEnumerateSwapchainImages); +} + +bool OpenXROpenGLExtension::check_graphics_api_support(XrVersion p_desired_version) { + ERR_FAIL_NULL_V(openxr_api, false); + + XrSystemId system_id = openxr_api->get_system_id(); + XrInstance instance = openxr_api->get_instance(); + +#ifdef ANDROID_ENABLED + XrGraphicsRequirementsOpenGLESKHR opengl_requirements; + opengl_requirements.type = XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_ES_KHR; + opengl_requirements.next = nullptr; + + XrResult result = xrGetOpenGLESGraphicsRequirementsKHR(instance, system_id, &opengl_requirements); + if (!openxr_api->xr_result(result, "Failed to get OpenGL graphics requirements!")) { + return false; + } +#else + XrGraphicsRequirementsOpenGLKHR opengl_requirements; + opengl_requirements.type = XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_KHR; + opengl_requirements.next = nullptr; + + XrResult result = xrGetOpenGLGraphicsRequirementsKHR(instance, system_id, &opengl_requirements); + if (!openxr_api->xr_result(result, "Failed to get OpenGL graphics requirements!")) { + return false; + } +#endif + + if (p_desired_version < opengl_requirements.minApiVersionSupported) { + print_line("OpenXR: Requested OpenGL version does not meet the minimum version this runtime supports."); + print_line("- desired_version ", OpenXRUtil::make_xr_version_string(p_desired_version)); + print_line("- minApiVersionSupported ", OpenXRUtil::make_xr_version_string(opengl_requirements.minApiVersionSupported)); + print_line("- maxApiVersionSupported ", OpenXRUtil::make_xr_version_string(opengl_requirements.maxApiVersionSupported)); + return false; + } + + if (p_desired_version > opengl_requirements.maxApiVersionSupported) { + print_line("OpenXR: Requested OpenGL version exceeds the maximum version this runtime has been tested on and is known to support."); + print_line("- desired_version ", OpenXRUtil::make_xr_version_string(p_desired_version)); + print_line("- minApiVersionSupported ", OpenXRUtil::make_xr_version_string(opengl_requirements.minApiVersionSupported)); + print_line("- maxApiVersionSupported ", OpenXRUtil::make_xr_version_string(opengl_requirements.maxApiVersionSupported)); + } + + return true; +} + +#ifdef WIN32 +XrGraphicsBindingOpenGLWin32KHR OpenXROpenGLExtension::graphics_binding_gl; +#elif ANDROID_ENABLED +XrGraphicsBindingOpenGLESAndroidKHR OpenXROpenGLExtension::graphics_binding_gl; +#else +XrGraphicsBindingOpenGLXlibKHR OpenXROpenGLExtension::graphics_binding_gl; +#endif + +void *OpenXROpenGLExtension::set_session_create_and_get_next_pointer(void *p_next_pointer) { + XrVersion desired_version = XR_MAKE_VERSION(3, 3, 0); + + if (!check_graphics_api_support(desired_version)) { + print_line("OpenXR: Trying to initialize with OpenGL anyway..."); + //return p_next_pointer; + } + + DisplayServer *display_server = DisplayServer::get_singleton(); + +#ifdef WIN32 + graphics_binding_gl.type = XR_TYPE_GRAPHICS_BINDING_OPENGL_WIN32_KHR, + graphics_binding_gl.next = p_next_pointer; + + graphics_binding_gl.hDC = (HDC)display_server->window_get_native_handle(DisplayServer::WINDOW_VIEW); + graphics_binding_gl.hGLRC = (HGLRC)display_server->window_get_native_handle(DisplayServer::OPENGL_CONTEXT); +#elif ANDROID_ENABLED + graphics_binding_gl.type = XR_TYPE_GRAPHICS_BINDING_OPENGL_ES_ANDROID_KHR; + graphics_binding_gl.next = p_next_pointer; + + graphics_binding_gl.display = eglGetCurrentDisplay(); + graphics_binding_gl.config = (EGLConfig)0; // https://github.com/KhronosGroup/OpenXR-SDK-Source/blob/master/src/tests/hello_xr/graphicsplugin_opengles.cpp#L122 + graphics_binding_gl.context = eglGetCurrentContext(); +#else + graphics_binding_gl.type = XR_TYPE_GRAPHICS_BINDING_OPENGL_XLIB_KHR; + graphics_binding_gl.next = p_next_pointer; + + void *display_handle = (void *)display_server->window_get_native_handle(DisplayServer::DISPLAY_HANDLE); + void *glxcontext_handle = (void *)display_server->window_get_native_handle(DisplayServer::OPENGL_CONTEXT); + void *glxdrawable_handle = (void *)display_server->window_get_native_handle(DisplayServer::WINDOW_HANDLE); + + graphics_binding_gl.xDisplay = (Display *)display_handle; + graphics_binding_gl.glxContext = (GLXContext)glxcontext_handle; + graphics_binding_gl.glxDrawable = (GLXDrawable)glxdrawable_handle; + + // spec says to use proper values but runtimes don't care + graphics_binding_gl.visualid = 0; + graphics_binding_gl.glxFBConfig = 0; +#endif + + return &graphics_binding_gl; +} + +void OpenXROpenGLExtension::get_usable_swapchain_formats(Vector<int64_t> &p_usable_swap_chains) { +#ifdef WIN32 + p_usable_swap_chains.push_back(GL_SRGB8_ALPHA8); + p_usable_swap_chains.push_back(GL_RGBA8); +#elif ANDROID_ENABLED + p_usable_swap_chains.push_back(GL_SRGB8_ALPHA8); + p_usable_swap_chains.push_back(GL_RGBA8); +#else + p_usable_swap_chains.push_back(GL_SRGB8_ALPHA8_EXT); + p_usable_swap_chains.push_back(GL_RGBA8_EXT); +#endif +} + +void OpenXROpenGLExtension::get_usable_depth_formats(Vector<int64_t> &p_usable_depth_formats) { + p_usable_depth_formats.push_back(GL_DEPTH_COMPONENT32F); + p_usable_depth_formats.push_back(GL_DEPTH24_STENCIL8); + p_usable_depth_formats.push_back(GL_DEPTH32F_STENCIL8); +} + +bool OpenXROpenGLExtension::get_swapchain_image_data(XrSwapchain p_swapchain, int64_t p_swapchain_format, uint32_t p_width, uint32_t p_height, uint32_t p_sample_count, uint32_t p_array_size, void **r_swapchain_graphics_data) { + GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton(); + ERR_FAIL_NULL_V(texture_storage, false); + + uint32_t swapchain_length; + XrResult result = xrEnumerateSwapchainImages(p_swapchain, 0, &swapchain_length, nullptr); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to get swapchaim image count [", openxr_api->get_error_string(result), "]"); + return false; + } + +#ifdef ANDROID_ENABLED + XrSwapchainImageOpenGLESKHR *images = (XrSwapchainImageOpenGLESKHR *)memalloc(sizeof(XrSwapchainImageOpenGLESKHR) * swapchain_length); +#else + XrSwapchainImageOpenGLKHR *images = (XrSwapchainImageOpenGLKHR *)memalloc(sizeof(XrSwapchainImageOpenGLKHR) * swapchain_length); +#endif + ERR_FAIL_NULL_V_MSG(images, false, "OpenXR Couldn't allocate memory for swap chain image"); + + for (uint64_t i = 0; i < swapchain_length; i++) { +#ifdef ANDROID_ENABLED + images[i].type = XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_ES_KHR; +#else + images[i].type = XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_KHR; +#endif + images[i].next = nullptr; + images[i].image = 0; + } + + result = xrEnumerateSwapchainImages(p_swapchain, swapchain_length, &swapchain_length, (XrSwapchainImageBaseHeader *)images); + if (XR_FAILED(result)) { + print_line("OpenXR: Failed to get swapchaim images [", openxr_api->get_error_string(result), "]"); + memfree(images); + return false; + } + + SwapchainGraphicsData *data = memnew(SwapchainGraphicsData); + if (data == nullptr) { + print_line("OpenXR: Failed to allocate memory for swapchain data"); + memfree(images); + return false; + } + *r_swapchain_graphics_data = data; + data->is_multiview = (p_array_size > 1); + + Image::Format format = Image::FORMAT_RGBA8; + + Vector<RID> texture_rids; + + for (uint64_t i = 0; i < swapchain_length; i++) { + RID texture_rid = texture_storage->texture_create_external( + p_array_size == 1 ? GLES3::Texture::TYPE_2D : GLES3::Texture::TYPE_LAYERED, + format, + images[i].image, + p_width, + p_height, + 1, + p_array_size); + + texture_rids.push_back(texture_rid); + } + + data->texture_rids = texture_rids; + + memfree(images); + + return true; +} + +bool OpenXROpenGLExtension::create_projection_fov(const XrFovf p_fov, double p_z_near, double p_z_far, Projection &r_camera_matrix) { + XrMatrix4x4f matrix; + XrMatrix4x4f_CreateProjectionFov(&matrix, GRAPHICS_OPENGL, p_fov, (float)p_z_near, (float)p_z_far); + + for (int j = 0; j < 4; j++) { + for (int i = 0; i < 4; i++) { + r_camera_matrix.columns[j][i] = matrix.m[j * 4 + i]; + } + } + + return true; +} + +RID OpenXROpenGLExtension::get_texture(void *p_swapchain_graphics_data, int p_image_index) { + SwapchainGraphicsData *data = (SwapchainGraphicsData *)p_swapchain_graphics_data; + ERR_FAIL_NULL_V(data, RID()); + + ERR_FAIL_INDEX_V(p_image_index, data->texture_rids.size(), RID()); + return data->texture_rids[p_image_index]; +} + +void OpenXROpenGLExtension::cleanup_swapchain_graphics_data(void **p_swapchain_graphics_data) { + if (*p_swapchain_graphics_data == nullptr) { + return; + } + + GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton(); + ERR_FAIL_NULL(texture_storage); + + SwapchainGraphicsData *data = (SwapchainGraphicsData *)*p_swapchain_graphics_data; + + for (int i = 0; i < data->texture_rids.size(); i++) { + texture_storage->texture_free(data->texture_rids[i]); + } + data->texture_rids.clear(); + + memdelete(data); + *p_swapchain_graphics_data = nullptr; +} + +#define ENUM_TO_STRING_CASE(e) \ + case e: { \ + return String(#e); \ + } break; + +String OpenXROpenGLExtension::get_swapchain_format_name(int64_t p_swapchain_format) const { + // These are somewhat different per platform, will need to weed some stuff out... + switch (p_swapchain_format) { +#ifdef WIN32 + // using definitions from GLAD + ENUM_TO_STRING_CASE(GL_R8_SNORM) + ENUM_TO_STRING_CASE(GL_RG8_SNORM) + ENUM_TO_STRING_CASE(GL_RGB8_SNORM) + ENUM_TO_STRING_CASE(GL_RGBA8_SNORM) + ENUM_TO_STRING_CASE(GL_R16_SNORM) + ENUM_TO_STRING_CASE(GL_RG16_SNORM) + ENUM_TO_STRING_CASE(GL_RGB16_SNORM) + ENUM_TO_STRING_CASE(GL_RGBA16_SNORM) + ENUM_TO_STRING_CASE(GL_RGB4) + ENUM_TO_STRING_CASE(GL_RGB5) + ENUM_TO_STRING_CASE(GL_RGB8) + ENUM_TO_STRING_CASE(GL_RGB10) + ENUM_TO_STRING_CASE(GL_RGB12) + ENUM_TO_STRING_CASE(GL_RGB16) + ENUM_TO_STRING_CASE(GL_RGBA2) + ENUM_TO_STRING_CASE(GL_RGBA4) + ENUM_TO_STRING_CASE(GL_RGB5_A1) + ENUM_TO_STRING_CASE(GL_RGBA8) + ENUM_TO_STRING_CASE(GL_RGB10_A2) + ENUM_TO_STRING_CASE(GL_RGBA12) + ENUM_TO_STRING_CASE(GL_RGBA16) + ENUM_TO_STRING_CASE(GL_RGBA32F) + ENUM_TO_STRING_CASE(GL_RGB32F) + ENUM_TO_STRING_CASE(GL_RGBA16F) + ENUM_TO_STRING_CASE(GL_RGB16F) + ENUM_TO_STRING_CASE(GL_RGBA32UI) + ENUM_TO_STRING_CASE(GL_RGB32UI) + ENUM_TO_STRING_CASE(GL_RGBA16UI) + ENUM_TO_STRING_CASE(GL_RGB16UI) + ENUM_TO_STRING_CASE(GL_RGBA8UI) + ENUM_TO_STRING_CASE(GL_RGB8UI) + ENUM_TO_STRING_CASE(GL_RGBA32I) + ENUM_TO_STRING_CASE(GL_RGB32I) + ENUM_TO_STRING_CASE(GL_RGBA16I) + ENUM_TO_STRING_CASE(GL_RGB16I) + ENUM_TO_STRING_CASE(GL_RGBA8I) + ENUM_TO_STRING_CASE(GL_RGB8I) + ENUM_TO_STRING_CASE(GL_RGB10_A2UI) + ENUM_TO_STRING_CASE(GL_SRGB) + ENUM_TO_STRING_CASE(GL_SRGB8) + ENUM_TO_STRING_CASE(GL_SRGB_ALPHA) + ENUM_TO_STRING_CASE(GL_SRGB8_ALPHA8) + ENUM_TO_STRING_CASE(GL_DEPTH_COMPONENT16) + ENUM_TO_STRING_CASE(GL_DEPTH_COMPONENT24) + ENUM_TO_STRING_CASE(GL_DEPTH_COMPONENT32) + ENUM_TO_STRING_CASE(GL_DEPTH24_STENCIL8) + ENUM_TO_STRING_CASE(GL_R11F_G11F_B10F) + ENUM_TO_STRING_CASE(GL_DEPTH_COMPONENT32F) + ENUM_TO_STRING_CASE(GL_DEPTH32F_STENCIL8) + +#elif ANDROID_ENABLED + // using definitions from GLES3/gl3.h + + ENUM_TO_STRING_CASE(GL_RGBA4) + ENUM_TO_STRING_CASE(GL_RGB5_A1) + ENUM_TO_STRING_CASE(GL_RGB565) + ENUM_TO_STRING_CASE(GL_RGB8) + ENUM_TO_STRING_CASE(GL_RGBA8) + ENUM_TO_STRING_CASE(GL_RGB10_A2) + ENUM_TO_STRING_CASE(GL_RGBA32F) + ENUM_TO_STRING_CASE(GL_RGB32F) + ENUM_TO_STRING_CASE(GL_RGBA16F) + ENUM_TO_STRING_CASE(GL_RGB16F) + ENUM_TO_STRING_CASE(GL_R11F_G11F_B10F) + ENUM_TO_STRING_CASE(GL_UNSIGNED_INT_10F_11F_11F_REV) + ENUM_TO_STRING_CASE(GL_RGB9_E5) + ENUM_TO_STRING_CASE(GL_UNSIGNED_INT_5_9_9_9_REV) + ENUM_TO_STRING_CASE(GL_RGBA32UI) + ENUM_TO_STRING_CASE(GL_RGB32UI) + ENUM_TO_STRING_CASE(GL_RGBA16UI) + ENUM_TO_STRING_CASE(GL_RGB16UI) + ENUM_TO_STRING_CASE(GL_RGBA8UI) + ENUM_TO_STRING_CASE(GL_RGB8UI) + ENUM_TO_STRING_CASE(GL_RGBA32I) + ENUM_TO_STRING_CASE(GL_RGB32I) + ENUM_TO_STRING_CASE(GL_RGBA16I) + ENUM_TO_STRING_CASE(GL_RGB16I) + ENUM_TO_STRING_CASE(GL_RGBA8I) + ENUM_TO_STRING_CASE(GL_RGB8I) + ENUM_TO_STRING_CASE(GL_RG) + ENUM_TO_STRING_CASE(GL_RG_INTEGER) + ENUM_TO_STRING_CASE(GL_R8) + ENUM_TO_STRING_CASE(GL_RG8) + ENUM_TO_STRING_CASE(GL_R16F) + ENUM_TO_STRING_CASE(GL_R32F) + ENUM_TO_STRING_CASE(GL_RG16F) + ENUM_TO_STRING_CASE(GL_RG32F) + ENUM_TO_STRING_CASE(GL_R8I) + ENUM_TO_STRING_CASE(GL_R8UI) + ENUM_TO_STRING_CASE(GL_R16I) + ENUM_TO_STRING_CASE(GL_R16UI) + ENUM_TO_STRING_CASE(GL_R32I) + ENUM_TO_STRING_CASE(GL_R32UI) + ENUM_TO_STRING_CASE(GL_RG8I) + ENUM_TO_STRING_CASE(GL_RG8UI) + ENUM_TO_STRING_CASE(GL_RG16I) + ENUM_TO_STRING_CASE(GL_RG16UI) + ENUM_TO_STRING_CASE(GL_RG32I) + ENUM_TO_STRING_CASE(GL_RG32UI) + ENUM_TO_STRING_CASE(GL_R8_SNORM) + ENUM_TO_STRING_CASE(GL_RG8_SNORM) + ENUM_TO_STRING_CASE(GL_RGB8_SNORM) + ENUM_TO_STRING_CASE(GL_RGBA8_SNORM) + ENUM_TO_STRING_CASE(GL_RGB10_A2UI) + ENUM_TO_STRING_CASE(GL_SRGB) + ENUM_TO_STRING_CASE(GL_SRGB8) + ENUM_TO_STRING_CASE(GL_SRGB8_ALPHA8) + ENUM_TO_STRING_CASE(GL_COMPRESSED_R11_EAC) + ENUM_TO_STRING_CASE(GL_COMPRESSED_SIGNED_R11_EAC) + ENUM_TO_STRING_CASE(GL_COMPRESSED_RG11_EAC) + ENUM_TO_STRING_CASE(GL_COMPRESSED_SIGNED_RG11_EAC) + ENUM_TO_STRING_CASE(GL_COMPRESSED_RGB8_ETC2) + ENUM_TO_STRING_CASE(GL_COMPRESSED_SRGB8_ETC2) + ENUM_TO_STRING_CASE(GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2) + ENUM_TO_STRING_CASE(GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2) + ENUM_TO_STRING_CASE(GL_COMPRESSED_RGBA8_ETC2_EAC) + ENUM_TO_STRING_CASE(GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC) + ENUM_TO_STRING_CASE(GL_DEPTH_COMPONENT16) + ENUM_TO_STRING_CASE(GL_DEPTH_COMPONENT24) + ENUM_TO_STRING_CASE(GL_DEPTH24_STENCIL8) + +#else + // using definitions from GL/gl.h + ENUM_TO_STRING_CASE(GL_ALPHA4_EXT) + ENUM_TO_STRING_CASE(GL_ALPHA8_EXT) + ENUM_TO_STRING_CASE(GL_ALPHA12_EXT) + ENUM_TO_STRING_CASE(GL_ALPHA16_EXT) + ENUM_TO_STRING_CASE(GL_LUMINANCE4_EXT) + ENUM_TO_STRING_CASE(GL_LUMINANCE8_EXT) + ENUM_TO_STRING_CASE(GL_LUMINANCE12_EXT) + ENUM_TO_STRING_CASE(GL_LUMINANCE16_EXT) + ENUM_TO_STRING_CASE(GL_LUMINANCE4_ALPHA4_EXT) + ENUM_TO_STRING_CASE(GL_LUMINANCE6_ALPHA2_EXT) + ENUM_TO_STRING_CASE(GL_LUMINANCE8_ALPHA8_EXT) + ENUM_TO_STRING_CASE(GL_LUMINANCE12_ALPHA4_EXT) + ENUM_TO_STRING_CASE(GL_LUMINANCE12_ALPHA12_EXT) + ENUM_TO_STRING_CASE(GL_LUMINANCE16_ALPHA16_EXT) + ENUM_TO_STRING_CASE(GL_INTENSITY_EXT) + ENUM_TO_STRING_CASE(GL_INTENSITY4_EXT) + ENUM_TO_STRING_CASE(GL_INTENSITY8_EXT) + ENUM_TO_STRING_CASE(GL_INTENSITY12_EXT) + ENUM_TO_STRING_CASE(GL_INTENSITY16_EXT) + ENUM_TO_STRING_CASE(GL_RGB2_EXT) + ENUM_TO_STRING_CASE(GL_RGB4_EXT) + ENUM_TO_STRING_CASE(GL_RGB5_EXT) + ENUM_TO_STRING_CASE(GL_RGB8_EXT) + ENUM_TO_STRING_CASE(GL_RGB10_EXT) + ENUM_TO_STRING_CASE(GL_RGB12_EXT) + ENUM_TO_STRING_CASE(GL_RGB16_EXT) + ENUM_TO_STRING_CASE(GL_RGBA2_EXT) + ENUM_TO_STRING_CASE(GL_RGBA4_EXT) + ENUM_TO_STRING_CASE(GL_RGB5_A1_EXT) + ENUM_TO_STRING_CASE(GL_RGBA8_EXT) + ENUM_TO_STRING_CASE(GL_RGB10_A2_EXT) + ENUM_TO_STRING_CASE(GL_RGBA12_EXT) + ENUM_TO_STRING_CASE(GL_RGBA16_EXT) + ENUM_TO_STRING_CASE(GL_SRGB_EXT) + ENUM_TO_STRING_CASE(GL_SRGB8_EXT) + ENUM_TO_STRING_CASE(GL_SRGB_ALPHA_EXT) + ENUM_TO_STRING_CASE(GL_SRGB8_ALPHA8_EXT) +#endif + default: { + return String("Swapchain format 0x") + String::num_int64(p_swapchain_format, 16); + } break; + } +} + +#endif // GLES3_ENABLED diff --git a/modules/openxr/extensions/openxr_opengl_extension.h b/modules/openxr/extensions/openxr_opengl_extension.h new file mode 100644 index 0000000000..b666653c8e --- /dev/null +++ b/modules/openxr/extensions/openxr_opengl_extension.h @@ -0,0 +1,120 @@ +/*************************************************************************/ +/* openxr_opengl_extension.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 OPENXR_OPENGL_EXTENSION_H +#define OPENXR_OPENGL_EXTENSION_H + +#ifdef GLES3_ENABLED + +#include "core/templates/vector.h" +#include "openxr_extension_wrapper.h" + +#include "../openxr_api.h" +#include "../util.h" + +#ifdef ANDROID_ENABLED +#define XR_USE_GRAPHICS_API_OPENGL_ES +#include <EGL/egl.h> +#include <EGL/eglext.h> +#include <GLES3/gl3.h> +#include <GLES3/gl3ext.h> +#else +#define XR_USE_GRAPHICS_API_OPENGL +#endif + +#ifdef WINDOWS_ENABLED +// Including windows.h here is absolutely evil, we shouldn't be doing this outside of platform +// however due to the way the openxr headers are put together, we have no choice. +#include <windows.h> +#endif + +#ifdef X11_ENABLED +#include OPENGL_INCLUDE_H +#define GL_GLEXT_PROTOTYPES 1 +#define GL3_PROTOTYPES 1 +#include <GL/gl.h> +#include <GL/glext.h> +#include <GL/glx.h> +#include <X11/Xlib.h> +#endif + +#ifdef ANDROID_ENABLED +// The jobject type from jni.h is used by openxr_platform.h on Android. +#include <jni.h> +#endif + +// include platform dependent structs +#include <openxr/openxr_platform.h> + +class OpenXROpenGLExtension : public OpenXRGraphicsExtensionWrapper { +public: + OpenXROpenGLExtension(OpenXRAPI *p_openxr_api); + virtual ~OpenXROpenGLExtension() override; + + virtual void on_instance_created(const XrInstance p_instance) override; + virtual void *set_session_create_and_get_next_pointer(void *p_next_pointer) override; + + virtual void get_usable_swapchain_formats(Vector<int64_t> &p_usable_swap_chains) override; + virtual void get_usable_depth_formats(Vector<int64_t> &p_usable_swap_chains) override; + virtual String get_swapchain_format_name(int64_t p_swapchain_format) const override; + virtual bool get_swapchain_image_data(XrSwapchain p_swapchain, int64_t p_swapchain_format, uint32_t p_width, uint32_t p_height, uint32_t p_sample_count, uint32_t p_array_size, void **r_swapchain_graphics_data) override; + virtual void cleanup_swapchain_graphics_data(void **p_swapchain_graphics_data) override; + virtual bool create_projection_fov(const XrFovf p_fov, double p_z_near, double p_z_far, Projection &r_camera_matrix) override; + virtual RID get_texture(void *p_swapchain_graphics_data, int p_image_index) override; + +private: + static OpenXROpenGLExtension *singleton; + +#ifdef WIN32 + static XrGraphicsBindingOpenGLWin32KHR graphics_binding_gl; +#elif ANDROID_ENABLED + static XrGraphicsBindingOpenGLESAndroidKHR graphics_binding_gl; +#else + static XrGraphicsBindingOpenGLXlibKHR graphics_binding_gl; +#endif + + struct SwapchainGraphicsData { + bool is_multiview; + Vector<RID> texture_rids; + }; + + bool check_graphics_api_support(XrVersion p_desired_version); + +#ifdef ANDROID_ENABLED + EXT_PROTO_XRRESULT_FUNC3(xrGetOpenGLESGraphicsRequirementsKHR, (XrInstance), p_instance, (XrSystemId), p_system_id, (XrGraphicsRequirementsOpenGLESKHR *), p_graphics_requirements) +#else + EXT_PROTO_XRRESULT_FUNC3(xrGetOpenGLGraphicsRequirementsKHR, (XrInstance), p_instance, (XrSystemId), p_system_id, (XrGraphicsRequirementsOpenGLKHR *), p_graphics_requirements) +#endif + EXT_PROTO_XRRESULT_FUNC4(xrEnumerateSwapchainImages, (XrSwapchain), p_swapchain, (uint32_t), p_image_capacity_input, (uint32_t *), p_image_count_output, (XrSwapchainImageBaseHeader *), p_images) +}; + +#endif // GLES3_ENABLED + +#endif // OPENXR_OPENGL_EXTENSION_H diff --git a/modules/openxr/extensions/openxr_palm_pose_extension.cpp b/modules/openxr/extensions/openxr_palm_pose_extension.cpp new file mode 100644 index 0000000000..fd3b8f50fe --- /dev/null +++ b/modules/openxr/extensions/openxr_palm_pose_extension.cpp @@ -0,0 +1,66 @@ +/*************************************************************************/ +/* openxr_palm_pose_extension.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 "openxr_palm_pose_extension.h" +#include "core/string/print_string.h" + +OpenXRPalmPoseExtension *OpenXRPalmPoseExtension::singleton = nullptr; + +OpenXRPalmPoseExtension *OpenXRPalmPoseExtension::get_singleton() { + return singleton; +} + +OpenXRPalmPoseExtension::OpenXRPalmPoseExtension(OpenXRAPI *p_openxr_api) : + OpenXRExtensionWrapper(p_openxr_api) { + singleton = this; + + request_extensions[XR_EXT_PALM_POSE_EXTENSION_NAME] = &available; +} + +OpenXRPalmPoseExtension::~OpenXRPalmPoseExtension() { + singleton = nullptr; +} + +bool OpenXRPalmPoseExtension::is_available() { + return available; +} + +bool OpenXRPalmPoseExtension::is_path_supported(const String &p_path) { + if (p_path == "/user/hand/left/input/palm_ext/pose") { + return available; + } + + if (p_path == "/user/hand/right/input/palm_ext/pose") { + return available; + } + + // Not a path under this extensions control, so we return true; + return true; +} diff --git a/modules/openxr/extensions/openxr_palm_pose_extension.h b/modules/openxr/extensions/openxr_palm_pose_extension.h new file mode 100644 index 0000000000..a7ef83c5d5 --- /dev/null +++ b/modules/openxr/extensions/openxr_palm_pose_extension.h @@ -0,0 +1,53 @@ +/*************************************************************************/ +/* openxr_palm_pose_extension.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 OPENXR_PALM_POSE_EXTENSION_H +#define OPENXR_PALM_POSE_EXTENSION_H + +#include "openxr_extension_wrapper.h" + +class OpenXRPalmPoseExtension : public OpenXRExtensionWrapper { +public: + static OpenXRPalmPoseExtension *get_singleton(); + + OpenXRPalmPoseExtension(OpenXRAPI *p_openxr_api); + virtual ~OpenXRPalmPoseExtension() override; + + bool is_available(); + + virtual bool is_path_supported(const String &p_path) override; + +private: + static OpenXRPalmPoseExtension *singleton; + + bool available = false; +}; + +#endif // OPENXR_PALM_POSE_EXTENSION_H diff --git a/modules/openxr/extensions/openxr_vulkan_extension.cpp b/modules/openxr/extensions/openxr_vulkan_extension.cpp index 2608c4ac17..ee5bda2881 100644 --- a/modules/openxr/extensions/openxr_vulkan_extension.cpp +++ b/modules/openxr/extensions/openxr_vulkan_extension.cpp @@ -31,30 +31,12 @@ #include "core/string/print_string.h" #include "../extensions/openxr_vulkan_extension.h" -#include "../openxr_api.h" #include "../openxr_util.h" #include "servers/rendering/renderer_rd/effects/copy_effects.h" #include "servers/rendering/renderer_rd/storage_rd/texture_storage.h" #include "servers/rendering/rendering_server_globals.h" #include "servers/rendering_server.h" -// need to include Vulkan so we know of type definitions -#define XR_USE_GRAPHICS_API_VULKAN - -#ifdef WINDOWS_ENABLED -// Including windows.h here is absolutely evil, we shouldn't be doing this outside of platform -// however due to the way the openxr headers are put together, we have no choice. -#include <windows.h> -#endif - -// include platform dependent structs -#include <openxr/openxr_platform.h> - -PFN_xrGetVulkanGraphicsRequirements2KHR xrGetVulkanGraphicsRequirements2KHR_ptr = nullptr; -PFN_xrCreateVulkanInstanceKHR xrCreateVulkanInstanceKHR_ptr = nullptr; -PFN_xrGetVulkanGraphicsDevice2KHR xrGetVulkanGraphicsDevice2KHR_ptr = nullptr; -PFN_xrCreateVulkanDeviceKHR xrCreateVulkanDeviceKHR_ptr = nullptr; - OpenXRVulkanExtension::OpenXRVulkanExtension(OpenXRAPI *p_openxr_api) : OpenXRGraphicsExtensionWrapper(p_openxr_api) { VulkanContext::set_vulkan_hooks(this); @@ -69,36 +51,15 @@ OpenXRVulkanExtension::~OpenXRVulkanExtension() { } void OpenXRVulkanExtension::on_instance_created(const XrInstance p_instance) { - XrResult result; - ERR_FAIL_NULL(openxr_api); // Obtain pointers to functions we're accessing here, they are (not yet) part of core. - result = xrGetInstanceProcAddr(p_instance, "xrGetVulkanGraphicsRequirements2KHR", (PFN_xrVoidFunction *)&xrGetVulkanGraphicsRequirements2KHR_ptr); - if (XR_FAILED(result)) { - print_line("OpenXR: Failed to xrGetVulkanGraphicsRequirements2KHR entry point [", openxr_api->get_error_string(result), "]"); - } - - result = xrGetInstanceProcAddr(p_instance, "xrCreateVulkanInstanceKHR", (PFN_xrVoidFunction *)&xrCreateVulkanInstanceKHR_ptr); - if (XR_FAILED(result)) { - print_line("OpenXR: Failed to xrCreateVulkanInstanceKHR entry point [", openxr_api->get_error_string(result), "]"); - } - - result = xrGetInstanceProcAddr(p_instance, "xrGetVulkanGraphicsDevice2KHR", (PFN_xrVoidFunction *)&xrGetVulkanGraphicsDevice2KHR_ptr); - if (XR_FAILED(result)) { - print_line("OpenXR: Failed to xrGetVulkanGraphicsDevice2KHR entry point [", openxr_api->get_error_string(result), "]"); - } - result = xrGetInstanceProcAddr(p_instance, "xrCreateVulkanDeviceKHR", (PFN_xrVoidFunction *)&xrCreateVulkanDeviceKHR_ptr); - if (XR_FAILED(result)) { - print_line("OpenXR: Failed to xrCreateVulkanDeviceKHR entry point [", openxr_api->get_error_string(result), "]"); - } -} - -XrResult OpenXRVulkanExtension::xrGetVulkanGraphicsRequirements2KHR(XrInstance p_instance, XrSystemId p_system_id, XrGraphicsRequirementsVulkanKHR *p_graphics_requirements) { - ERR_FAIL_NULL_V(xrGetVulkanGraphicsRequirements2KHR_ptr, XR_ERROR_HANDLE_INVALID); - - return (*xrGetVulkanGraphicsRequirements2KHR_ptr)(p_instance, p_system_id, p_graphics_requirements); + EXT_INIT_XR_FUNC(xrGetVulkanGraphicsRequirements2KHR); + EXT_INIT_XR_FUNC(xrCreateVulkanInstanceKHR); + EXT_INIT_XR_FUNC(xrGetVulkanGraphicsDevice2KHR); + EXT_INIT_XR_FUNC(xrCreateVulkanDeviceKHR); + EXT_INIT_XR_FUNC(xrEnumerateSwapchainImages); } bool OpenXRVulkanExtension::check_graphics_api_support(XrVersion p_desired_version) { @@ -141,12 +102,6 @@ bool OpenXRVulkanExtension::check_graphics_api_support(XrVersion p_desired_versi return true; } -XrResult OpenXRVulkanExtension::xrCreateVulkanInstanceKHR(XrInstance p_instance, const XrVulkanInstanceCreateInfoKHR *p_create_info, VkInstance *r_vulkan_instance, VkResult *r_vulkan_result) { - ERR_FAIL_NULL_V(xrCreateVulkanInstanceKHR_ptr, XR_ERROR_HANDLE_INVALID); - - return (*xrCreateVulkanInstanceKHR_ptr)(p_instance, p_create_info, r_vulkan_instance, r_vulkan_result); -} - bool OpenXRVulkanExtension::create_vulkan_instance(const VkInstanceCreateInfo *p_vulkan_create_info, VkInstance *r_instance) { // get the vulkan version we are creating uint32_t vulkan_version = p_vulkan_create_info->pApplicationInfo->apiVersion; @@ -195,12 +150,6 @@ bool OpenXRVulkanExtension::create_vulkan_instance(const VkInstanceCreateInfo *p return true; } -XrResult OpenXRVulkanExtension::xrGetVulkanGraphicsDevice2KHR(XrInstance p_instance, const XrVulkanGraphicsDeviceGetInfoKHR *p_get_info, VkPhysicalDevice *r_vulkan_physical_device) { - ERR_FAIL_NULL_V(xrGetVulkanGraphicsDevice2KHR_ptr, XR_ERROR_HANDLE_INVALID); - - return (*xrGetVulkanGraphicsDevice2KHR_ptr)(p_instance, p_get_info, r_vulkan_physical_device); -} - bool OpenXRVulkanExtension::get_physical_device(VkPhysicalDevice *r_device) { ERR_FAIL_NULL_V(openxr_api, false); @@ -222,12 +171,6 @@ bool OpenXRVulkanExtension::get_physical_device(VkPhysicalDevice *r_device) { return true; } -XrResult OpenXRVulkanExtension::xrCreateVulkanDeviceKHR(XrInstance p_instance, const XrVulkanDeviceCreateInfoKHR *p_create_info, VkDevice *r_device, VkResult *r_result) { - ERR_FAIL_NULL_V(xrCreateVulkanDeviceKHR_ptr, XR_ERROR_HANDLE_INVALID); - - return (*xrCreateVulkanDeviceKHR_ptr)(p_instance, p_create_info, r_device, r_result); -} - bool OpenXRVulkanExtension::create_vulkan_device(const VkDeviceCreateInfo *p_device_create_info, VkDevice *r_device) { ERR_FAIL_NULL_V(openxr_api, false); @@ -285,6 +228,12 @@ void OpenXRVulkanExtension::get_usable_swapchain_formats(Vector<int64_t> &p_usab p_usable_swap_chains.push_back(VK_FORMAT_B8G8R8A8_UINT); } +void OpenXRVulkanExtension::get_usable_depth_formats(Vector<int64_t> &p_usable_swap_chains) { + p_usable_swap_chains.push_back(VK_FORMAT_R32_SFLOAT); + p_usable_swap_chains.push_back(VK_FORMAT_D24_UNORM_S8_UINT); + p_usable_swap_chains.push_back(VK_FORMAT_D32_SFLOAT_S8_UINT); +} + bool OpenXRVulkanExtension::get_swapchain_image_data(XrSwapchain p_swapchain, int64_t p_swapchain_format, uint32_t p_width, uint32_t p_height, uint32_t p_sample_count, uint32_t p_array_size, void **r_swapchain_graphics_data) { XrSwapchainImageVulkanKHR *images = nullptr; @@ -328,7 +277,7 @@ bool OpenXRVulkanExtension::get_swapchain_image_data(XrSwapchain p_swapchain, in RenderingDevice::DataFormat format = RenderingDevice::DATA_FORMAT_R8G8B8A8_SRGB; RenderingDevice::TextureSamples samples = RenderingDevice::TEXTURE_SAMPLES_1; - uint64_t usage_flags = RenderingDevice::TEXTURE_USAGE_SAMPLING_BIT | RenderingDevice::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT; + uint64_t usage_flags = RenderingDevice::TEXTURE_USAGE_SAMPLING_BIT; switch (p_swapchain_format) { case VK_FORMAT_R8G8B8A8_SRGB: @@ -340,16 +289,32 @@ bool OpenXRVulkanExtension::get_swapchain_image_data(XrSwapchain p_swapchain, in // will thus do an sRGB -> Linear conversion as expected. // format = RenderingDevice::DATA_FORMAT_R8G8B8A8_SRGB; format = RenderingDevice::DATA_FORMAT_R8G8B8A8_UNORM; + usage_flags |= RenderingDevice::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT; break; case VK_FORMAT_B8G8R8A8_SRGB: // format = RenderingDevice::DATA_FORMAT_B8G8R8A8_SRGB; format = RenderingDevice::DATA_FORMAT_B8G8R8A8_UNORM; + usage_flags |= RenderingDevice::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT; break; case VK_FORMAT_R8G8B8A8_UINT: format = RenderingDevice::DATA_FORMAT_R8G8B8A8_UINT; + usage_flags |= RenderingDevice::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT; break; case VK_FORMAT_B8G8R8A8_UINT: format = RenderingDevice::DATA_FORMAT_B8G8R8A8_UINT; + usage_flags |= RenderingDevice::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT; + break; + case VK_FORMAT_R32_SFLOAT: + format = RenderingDevice::DATA_FORMAT_R32_SFLOAT; + usage_flags |= RenderingDevice::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; + break; + case VK_FORMAT_D24_UNORM_S8_UINT: + format = RenderingDevice::DATA_FORMAT_D24_UNORM_S8_UINT; + usage_flags |= RenderingDevice::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; + break; + case VK_FORMAT_D32_SFLOAT_S8_UINT: + format = RenderingDevice::DATA_FORMAT_D32_SFLOAT_S8_UINT; + usage_flags |= RenderingDevice::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; break; default: // continue with our default value @@ -385,8 +350,7 @@ bool OpenXRVulkanExtension::get_swapchain_image_data(XrSwapchain p_swapchain, in break; } - Vector<RID> image_rids; - Vector<RID> framebuffers; + Vector<RID> texture_rids; // create Godot texture objects for each entry in our swapchain for (uint64_t i = 0; i < swapchain_length; i++) { @@ -401,19 +365,10 @@ bool OpenXRVulkanExtension::get_swapchain_image_data(XrSwapchain p_swapchain, in 1, p_array_size); - image_rids.push_back(image_rid); - - { - Vector<RID> fb; - fb.push_back(image_rid); - - RID fb_rid = rendering_device->framebuffer_create(fb, RenderingDevice::INVALID_ID, p_array_size); - framebuffers.push_back(fb_rid); - } + texture_rids.push_back(image_rid); } - data->image_rids = image_rids; - data->framebuffers = framebuffers; + data->texture_rids = texture_rids; memfree(images); @@ -427,33 +382,19 @@ bool OpenXRVulkanExtension::create_projection_fov(const XrFovf p_fov, double p_z for (int j = 0; j < 4; j++) { for (int i = 0; i < 4; i++) { - r_camera_matrix.matrix[j][i] = matrix.m[j * 4 + i]; + r_camera_matrix.columns[j][i] = matrix.m[j * 4 + i]; } } return true; } -bool OpenXRVulkanExtension::copy_render_target_to_image(RID p_from_render_target, void *p_swapchain_graphics_data, int p_image_index) { +RID OpenXRVulkanExtension::get_texture(void *p_swapchain_graphics_data, int p_image_index) { SwapchainGraphicsData *data = (SwapchainGraphicsData *)p_swapchain_graphics_data; - ERR_FAIL_NULL_V(data, false); - ERR_FAIL_COND_V(p_from_render_target.is_null(), false); - - RID source_image = RendererRD::TextureStorage::get_singleton()->render_target_get_rd_texture(p_from_render_target); - ERR_FAIL_COND_V(source_image.is_null(), false); - - RID depth_image; // TODO implement - - ERR_FAIL_INDEX_V(p_image_index, data->framebuffers.size(), false); - RID fb = data->framebuffers[p_image_index]; - ERR_FAIL_COND_V(fb.is_null(), false); + ERR_FAIL_NULL_V(data, RID()); - // Our vulkan extension can only be used in conjunction with our vulkan renderer. - RendererRD::CopyEffects *copy_effects = RendererRD::CopyEffects::get_singleton(); - ERR_FAIL_NULL_V(copy_effects, false); - copy_effects->copy_to_fb_rect(source_image, fb, Rect2i(), false, false, false, false, depth_image, data->is_multiview); - - return true; + ERR_FAIL_INDEX_V(p_image_index, data->texture_rids.size(), RID()); + return data->texture_rids[p_image_index]; } void OpenXRVulkanExtension::cleanup_swapchain_graphics_data(void **p_swapchain_graphics_data) { @@ -468,17 +409,11 @@ void OpenXRVulkanExtension::cleanup_swapchain_graphics_data(void **p_swapchain_g RenderingDevice *rendering_device = rendering_server->get_rendering_device(); ERR_FAIL_NULL(rendering_device); - for (int i = 0; i < data->image_rids.size(); i++) { - // This should clean up our RIDs and associated texture objects but shouldn't destroy the images, they are owned by our XrSwapchain - rendering_device->free(data->image_rids[i]); - } - data->image_rids.clear(); - - for (int i = 0; i < data->framebuffers.size(); i++) { + for (int i = 0; i < data->texture_rids.size(); i++) { // This should clean up our RIDs and associated texture objects but shouldn't destroy the images, they are owned by our XrSwapchain - rendering_device->free(data->framebuffers[i]); + rendering_device->free(data->texture_rids[i]); } - data->framebuffers.clear(); + data->texture_rids.clear(); memdelete(data); *p_swapchain_graphics_data = nullptr; diff --git a/modules/openxr/extensions/openxr_vulkan_extension.h b/modules/openxr/extensions/openxr_vulkan_extension.h index 5dddc4b9c9..71abe3b166 100644 --- a/modules/openxr/extensions/openxr_vulkan_extension.h +++ b/modules/openxr/extensions/openxr_vulkan_extension.h @@ -36,16 +36,25 @@ #include "drivers/vulkan/vulkan_context.h" -// Forward declare these so we don't need OpenXR headers where-ever this is included -// Including OpenXR at this point gives loads and loads of compile issues especially -// on Windows because windows.h is EVIL and really shouldn't be included outside of platform -// but we really don't have a choice in the matter +#include "../openxr_api.h" +#include "../util.h" -struct XrGraphicsRequirementsVulkanKHR; -struct XrVulkanInstanceCreateInfoKHR; -struct XrVulkanGraphicsDeviceGetInfoKHR; -struct XrVulkanDeviceCreateInfoKHR; -struct XrGraphicsBindingVulkanKHR; +// need to include Vulkan so we know of type definitions +#define XR_USE_GRAPHICS_API_VULKAN + +#ifdef WINDOWS_ENABLED +// Including windows.h here is absolutely evil, we shouldn't be doing this outside of platform +// however due to the way the openxr headers are put together, we have no choice. +#include <windows.h> +#endif + +#ifdef ANDROID_ENABLED +// The jobject type from jni.h is used by openxr_platform.h on Android. +#include <jni.h> +#endif + +// include platform dependent structs +#include <openxr/openxr_platform.h> class OpenXRVulkanExtension : public OpenXRGraphicsExtensionWrapper, VulkanHooks { public: @@ -60,11 +69,12 @@ public: virtual bool create_vulkan_device(const VkDeviceCreateInfo *p_device_create_info, VkDevice *r_device) override; virtual void get_usable_swapchain_formats(Vector<int64_t> &p_usable_swap_chains) override; + virtual void get_usable_depth_formats(Vector<int64_t> &p_usable_swap_chains) override; virtual String get_swapchain_format_name(int64_t p_swapchain_format) const override; virtual bool get_swapchain_image_data(XrSwapchain p_swapchain, int64_t p_swapchain_format, uint32_t p_width, uint32_t p_height, uint32_t p_sample_count, uint32_t p_array_size, void **r_swapchain_graphics_data) override; virtual void cleanup_swapchain_graphics_data(void **p_swapchain_graphics_data) override; virtual bool create_projection_fov(const XrFovf p_fov, double p_z_near, double p_z_far, Projection &r_camera_matrix) override; - virtual bool copy_render_target_to_image(RID p_from_render_target, void *p_swapchain_graphics_data, int p_image_index) override; + virtual RID get_texture(void *p_swapchain_graphics_data, int p_image_index) override; private: static OpenXRVulkanExtension *singleton; @@ -72,8 +82,7 @@ private: struct SwapchainGraphicsData { bool is_multiview; - Vector<RID> image_rids; - Vector<RID> framebuffers; + Vector<RID> texture_rids; }; bool check_graphics_api_support(XrVersion p_desired_version); @@ -84,10 +93,11 @@ private: uint32_t vulkan_queue_family_index = 0; uint32_t vulkan_queue_index = 0; - XrResult xrGetVulkanGraphicsRequirements2KHR(XrInstance p_instance, XrSystemId p_system_id, XrGraphicsRequirementsVulkanKHR *p_graphics_requirements); - XrResult xrCreateVulkanInstanceKHR(XrInstance p_instance, const XrVulkanInstanceCreateInfoKHR *p_create_info, VkInstance *r_vulkan_instance, VkResult *r_vulkan_result); - XrResult xrGetVulkanGraphicsDevice2KHR(XrInstance p_instance, const XrVulkanGraphicsDeviceGetInfoKHR *p_get_info, VkPhysicalDevice *r_vulkan_physical_device); - XrResult xrCreateVulkanDeviceKHR(XrInstance p_instance, const XrVulkanDeviceCreateInfoKHR *p_create_info, VkDevice *r_device, VkResult *r_result); + EXT_PROTO_XRRESULT_FUNC3(xrGetVulkanGraphicsRequirements2KHR, (XrInstance), p_instance, (XrSystemId), p_system_id, (XrGraphicsRequirementsVulkanKHR *), p_graphics_requirements) + EXT_PROTO_XRRESULT_FUNC4(xrCreateVulkanInstanceKHR, (XrInstance), p_instance, (const XrVulkanInstanceCreateInfoKHR *), p_create_info, (VkInstance *), r_vulkan_instance, (VkResult *), r_vulkan_result) + EXT_PROTO_XRRESULT_FUNC3(xrGetVulkanGraphicsDevice2KHR, (XrInstance), p_instance, (const XrVulkanGraphicsDeviceGetInfoKHR *), p_get_info, (VkPhysicalDevice *), r_vulkan_physical_device) + EXT_PROTO_XRRESULT_FUNC4(xrCreateVulkanDeviceKHR, (XrInstance), p_instance, (const XrVulkanDeviceCreateInfoKHR *), p_create_info, (VkDevice *), r_device, (VkResult *), r_result) + EXT_PROTO_XRRESULT_FUNC4(xrEnumerateSwapchainImages, (XrSwapchain), p_swapchain, (uint32_t), p_image_capacity_input, (uint32_t *), p_image_count_output, (XrSwapchainImageBaseHeader *), p_images) }; #endif // OPENXR_VULKAN_EXTENSION_H diff --git a/modules/openxr/openxr_api.cpp b/modules/openxr/openxr_api.cpp index 92d074cb75..88111afede 100644 --- a/modules/openxr/openxr_api.cpp +++ b/modules/openxr/openxr_api.cpp @@ -41,14 +41,50 @@ #endif #ifdef ANDROID_ENABLED +#define OPENXR_LOADER_NAME "libopenxr_loader.so" #include "extensions/openxr_android_extension.h" #endif +// We need to have all the graphics API defines before the Vulkan or OpenGL +// extensions are included, otherwise we'll only get one graphics API. +#ifdef VULKAN_ENABLED +#define XR_USE_GRAPHICS_API_VULKAN +#endif +#ifdef GLES3_ENABLED +#ifdef ANDROID +#define XR_USE_GRAPHICS_API_OPENGL_ES +#include <EGL/egl.h> +#include <EGL/eglext.h> +#include <GLES3/gl3.h> +#include <GLES3/gl3ext.h> +#else +#define XR_USE_GRAPHICS_API_OPENGL +#endif // ANDROID +#ifdef X11_ENABLED +#include OPENGL_INCLUDE_H +#define GL_GLEXT_PROTOTYPES 1 +#define GL3_PROTOTYPES 1 +#include <GL/gl.h> +#include <GL/glext.h> +#include <GL/glx.h> +#include <X11/Xlib.h> +#endif // X11_ENABLED +#endif // GLES_ENABLED + #ifdef VULKAN_ENABLED #include "extensions/openxr_vulkan_extension.h" #endif +#ifdef GLES3_ENABLED +#include "extensions/openxr_opengl_extension.h" +#endif + +#include "extensions/openxr_composition_layer_depth_extension.h" +#include "extensions/openxr_fb_display_refresh_rate_extension.h" +#include "extensions/openxr_fb_passthrough_extension_wrapper.h" +#include "extensions/openxr_hand_tracking_extension.h" #include "extensions/openxr_htc_vive_tracker_extension.h" +#include "extensions/openxr_palm_pose_extension.h" #include "modules/openxr/openxr_interface.h" @@ -126,11 +162,9 @@ bool OpenXRAPI::load_layer_properties() { result = xrEnumerateApiLayerProperties(num_layer_properties, &num_layer_properties, layer_properties); ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate api layer properties"); -#ifdef DEBUG for (uint32_t i = 0; i < num_layer_properties; i++) { - print_line("OpenXR: Found OpenXR layer ", layer_properties[i].layerName); + print_verbose(String("OpenXR: Found OpenXR layer ") + layer_properties[i].layerName); } -#endif return true; } @@ -158,11 +192,9 @@ bool OpenXRAPI::load_supported_extensions() { result = xrEnumerateInstanceExtensionProperties(nullptr, num_supported_extensions, &num_supported_extensions, supported_extensions); ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate extension properties"); -#ifdef DEBUG for (uint32_t i = 0; i < num_supported_extensions; i++) { - print_line("OpenXR: Found OpenXR extension ", supported_extensions[i].extensionName); + print_verbose(String("OpenXR: Found OpenXR extension ") + supported_extensions[i].extensionName); } -#endif return true; } @@ -170,20 +202,27 @@ bool OpenXRAPI::load_supported_extensions() { bool OpenXRAPI::is_extension_supported(const String &p_extension) const { for (uint32_t i = 0; i < num_supported_extensions; i++) { if (supported_extensions[i].extensionName == p_extension) { -#ifdef DEBUG - print_line("OpenXR: requested extension", p_extension, "is supported"); -#endif return true; } } -#ifdef DEBUG - print_line("OpenXR: requested extension", p_extension, "is not supported"); -#endif - return false; } +bool OpenXRAPI::is_path_supported(const String &p_path) { + // This checks with extensions whether a path is *unsupported* and returns false if this is so. + // This allows us to filter out paths that are only available if related extensions are supported. + // WARNING: This method will return true for unknown/mistyped paths as we have no way to validate those. + + for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { + if (!wrapper->is_path_supported(p_path)) { + return false; + } + } + + return true; +} + void OpenXRAPI::copy_string_to_char_buffer(const String p_string, char *p_buffer, int p_buffer_len) { CharString char_string = p_string.utf8(); int len = char_string.length(); @@ -226,7 +265,7 @@ bool OpenXRAPI::create_instance() { if (!is_extension_supported(requested_extension.key)) { if (requested_extension.value == nullptr) { // nullptr means this is a manditory extension so we fail - ERR_FAIL_V_MSG(false, "OpenXR: OpenXR Runtime does not support OpenGL extension!"); + ERR_FAIL_V_MSG(false, String("OpenXR: OpenXR Runtime does not support ") + requested_extension.key + String(" extension!")); } else { // set this extension as not supported *requested_extension.value = false; @@ -284,6 +323,9 @@ bool OpenXRAPI::create_instance() { 0, // runtimeVersion, from here will be set by our get call "" // runtimeName }; + + OPENXR_API_INIT_XR_FUNC_V(xrGetInstanceProperties); + result = xrGetInstanceProperties(instance, &instanceProps); if (XR_FAILED(result)) { // not fatal probably @@ -379,11 +421,9 @@ bool OpenXRAPI::load_supported_view_configuration_types() { result = xrEnumerateViewConfigurations(instance, system_id, num_view_configuration_types, &num_view_configuration_types, supported_view_configuration_types); ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerateview configurations"); -#ifdef DEBUG for (uint32_t i = 0; i < num_view_configuration_types; i++) { - print_line("OpenXR: Found supported view configuration ", OpenXRUtil::get_view_configuration_name(supported_view_configuration_types[i])); + print_verbose(String("OpenXR: Found supported view configuration ") + OpenXRUtil::get_view_configuration_name(supported_view_configuration_types[i])); } -#endif return true; } @@ -432,17 +472,15 @@ bool OpenXRAPI::load_supported_view_configuration_views(XrViewConfigurationType result = xrEnumerateViewConfigurationViews(instance, system_id, p_configuration_type, view_count, &view_count, view_configuration_views); ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate view configurations"); -#ifdef DEBUG for (uint32_t i = 0; i < view_count; i++) { - print_line("OpenXR: Found supported view configuration view"); - print_line(" - width: ", view_configuration_views[i].maxImageRectWidth); - print_line(" - height: ", view_configuration_views[i].maxImageRectHeight); - print_line(" - sample count: ", view_configuration_views[i].maxSwapchainSampleCount); - print_line(" - recommended render width: ", view_configuration_views[i].recommendedImageRectWidth); - print_line(" - recommended render height: ", view_configuration_views[i].recommendedImageRectHeight); - print_line(" - recommended render sample count: ", view_configuration_views[i].recommendedSwapchainSampleCount); + print_verbose("OpenXR: Found supported view configuration view"); + print_verbose(String(" - width: ") + itos(view_configuration_views[i].maxImageRectWidth)); + print_verbose(String(" - height: ") + itos(view_configuration_views[i].maxImageRectHeight)); + print_verbose(String(" - sample count: ") + itos(view_configuration_views[i].maxSwapchainSampleCount)); + print_verbose(String(" - recommended render width: ") + itos(view_configuration_views[i].recommendedImageRectWidth)); + print_verbose(String(" - recommended render height: ") + itos(view_configuration_views[i].recommendedImageRectHeight)); + print_verbose(String(" - recommended render sample count: ") + itos(view_configuration_views[i].recommendedSwapchainSampleCount)); } -#endif return true; } @@ -524,11 +562,9 @@ bool OpenXRAPI::load_supported_reference_spaces() { result = xrEnumerateReferenceSpaces(session, num_reference_spaces, &num_reference_spaces, supported_reference_spaces); ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate reference spaces"); - // #ifdef DEBUG for (uint32_t i = 0; i < num_reference_spaces; i++) { - print_line("OpenXR: Found supported reference space ", OpenXRUtil::get_reference_space_name(supported_reference_spaces[i])); + print_verbose(String("OpenXR: Found supported reference space ") + OpenXRUtil::get_reference_space_name(supported_reference_spaces[i])); } - // #endif return true; } @@ -621,11 +657,9 @@ bool OpenXRAPI::load_supported_swapchain_formats() { result = xrEnumerateSwapchainFormats(session, num_swapchain_formats, &num_swapchain_formats, supported_swapchain_formats); ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate swapchain formats"); - // #ifdef DEBUG for (uint32_t i = 0; i < num_swapchain_formats; i++) { - print_line("OpenXR: Found supported swapchain format ", get_swapchain_format_name(supported_swapchain_formats[i])); + print_verbose(String("OpenXR: Found supported swapchain format ") + get_swapchain_format_name(supported_swapchain_formats[i])); } - // #endif return true; } @@ -642,7 +676,7 @@ bool OpenXRAPI::is_swapchain_format_supported(int64_t p_swapchain_format) { return false; } -bool OpenXRAPI::create_main_swapchain() { +bool OpenXRAPI::create_swapchains() { ERR_FAIL_NULL_V(graphics_extension, false); ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false); @@ -660,34 +694,36 @@ bool OpenXRAPI::create_main_swapchain() { already rendering the next frame. Finally an area we need to expand upon is that Foveated rendering is only enabled for the swap chain we create, - as we render 3D content into internal buffers that are copied into the swapchain, we don't get any of the performance gains - until such time as we implement VRS. + as we render 3D content into internal buffers that are copied into the swapchain, we do now have (basic) VRS support */ - // Build a vector with swapchain formats we want to use, from best fit to worst - Vector<int64_t> usable_swapchain_formats; - int64_t swapchain_format_to_use = 0; + Size2 recommended_size = get_recommended_target_size(); - graphics_extension->get_usable_swapchain_formats(usable_swapchain_formats); + // We start with our color swapchain... + { + // Build a vector with swapchain formats we want to use, from best fit to worst + Vector<int64_t> usable_swapchain_formats; + int64_t swapchain_format_to_use = 0; - // now find out which one is supported - for (int i = 0; i < usable_swapchain_formats.size() && swapchain_format_to_use == 0; i++) { - if (is_swapchain_format_supported(usable_swapchain_formats[i])) { - swapchain_format_to_use = usable_swapchain_formats[i]; - } - } + graphics_extension->get_usable_swapchain_formats(usable_swapchain_formats); - if (swapchain_format_to_use == 0) { - swapchain_format_to_use = usable_swapchain_formats[0]; // just use the first one and hope for the best... - print_line("Couldn't find usable swap chain format, using", get_swapchain_format_name(swapchain_format_to_use), "instead."); - } else { - print_line("Using swap chain format:", get_swapchain_format_name(swapchain_format_to_use)); - } + // now find out which one is supported + for (int i = 0; i < usable_swapchain_formats.size() && swapchain_format_to_use == 0; i++) { + if (is_swapchain_format_supported(usable_swapchain_formats[i])) { + swapchain_format_to_use = usable_swapchain_formats[i]; + } + } - Size2 recommended_size = get_recommended_target_size(); + if (swapchain_format_to_use == 0) { + swapchain_format_to_use = usable_swapchain_formats[0]; // just use the first one and hope for the best... + print_line("Couldn't find usable color swap chain format, using", get_swapchain_format_name(swapchain_format_to_use), "instead."); + } else { + print_verbose(String("Using color swap chain format:") + get_swapchain_format_name(swapchain_format_to_use)); + } - if (!create_swapchain(swapchain_format_to_use, recommended_size.width, recommended_size.height, view_configuration_views[0].recommendedSwapchainSampleCount, view_count, swapchain, &swapchain_graphics_data)) { - return false; + if (!create_swapchain(XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, swapchain_format_to_use, recommended_size.width, recommended_size.height, view_configuration_views[0].recommendedSwapchainSampleCount, view_count, swapchains[OPENXR_SWAPCHAIN_COLOR].swapchain, &swapchains[OPENXR_SWAPCHAIN_COLOR].swapchain_graphics_data)) { + return false; + } } views = (XrView *)memalloc(sizeof(XrView) * view_count); @@ -696,18 +732,73 @@ bool OpenXRAPI::create_main_swapchain() { projection_views = (XrCompositionLayerProjectionView *)memalloc(sizeof(XrCompositionLayerProjectionView) * view_count); ERR_FAIL_NULL_V_MSG(projection_views, false, "OpenXR Couldn't allocate memory for projection views"); + // We create our depth swapchain if: + // - we support our depth layer extension + // - we have our spacewarp extension (not yet implemented) + if (OpenXRCompositionLayerDepthExtension::get_singleton()->is_available()) { + // Build a vector with swapchain formats we want to use, from best fit to worst + Vector<int64_t> usable_swapchain_formats; + int64_t swapchain_format_to_use = 0; + + graphics_extension->get_usable_depth_formats(usable_swapchain_formats); + + // now find out which one is supported + for (int i = 0; i < usable_swapchain_formats.size() && swapchain_format_to_use == 0; i++) { + if (is_swapchain_format_supported(usable_swapchain_formats[i])) { + swapchain_format_to_use = usable_swapchain_formats[i]; + } + } + + if (swapchain_format_to_use == 0) { + swapchain_format_to_use = usable_swapchain_formats[0]; // just use the first one and hope for the best... + print_line("Couldn't find usable depth swap chain format, using", get_swapchain_format_name(swapchain_format_to_use), "instead."); + } else { + print_verbose(String("Using depth swap chain format:") + get_swapchain_format_name(swapchain_format_to_use)); + } + + if (!create_swapchain(XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, swapchain_format_to_use, recommended_size.width, recommended_size.height, view_configuration_views[0].recommendedSwapchainSampleCount, view_count, swapchains[OPENXR_SWAPCHAIN_DEPTH].swapchain, &swapchains[OPENXR_SWAPCHAIN_DEPTH].swapchain_graphics_data)) { + return false; + } + + depth_views = (XrCompositionLayerDepthInfoKHR *)memalloc(sizeof(XrCompositionLayerDepthInfoKHR) * view_count); + ERR_FAIL_NULL_V_MSG(depth_views, false, "OpenXR Couldn't allocate memory for depth views"); + } + + // We create our velocity swapchain if: + // - we have our spacewarp extension (not yet implemented) + { + // TBD + } + for (uint32_t i = 0; i < view_count; i++) { views[i].type = XR_TYPE_VIEW; views[i].next = nullptr; projection_views[i].type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW; projection_views[i].next = nullptr; - projection_views[i].subImage.swapchain = swapchain; + projection_views[i].subImage.swapchain = swapchains[OPENXR_SWAPCHAIN_COLOR].swapchain; projection_views[i].subImage.imageArrayIndex = i; projection_views[i].subImage.imageRect.offset.x = 0; projection_views[i].subImage.imageRect.offset.y = 0; projection_views[i].subImage.imageRect.extent.width = recommended_size.width; projection_views[i].subImage.imageRect.extent.height = recommended_size.height; + + if (OpenXRCompositionLayerDepthExtension::get_singleton()->is_available() && depth_views) { + projection_views[i].next = &depth_views[i]; + + depth_views[i].type = XR_TYPE_COMPOSITION_LAYER_DEPTH_INFO_KHR; + depth_views[i].next = nullptr; + depth_views[i].subImage.swapchain = swapchains[OPENXR_SWAPCHAIN_DEPTH].swapchain; + depth_views[i].subImage.imageArrayIndex = 0; + depth_views[i].subImage.imageRect.offset.x = 0; + depth_views[i].subImage.imageRect.offset.y = 0; + depth_views[i].subImage.imageRect.extent.width = recommended_size.width; + depth_views[i].subImage.imageRect.extent.height = recommended_size.height; + depth_views[i].minDepth = 0.0; + depth_views[i].maxDepth = 1.0; + depth_views[i].nearZ = 0.01; // Near and far Z will be set to the correct values in fill_projection_matrix + depth_views[i].farZ = 100.0; + } }; return true; @@ -719,7 +810,7 @@ void OpenXRAPI::destroy_session() { } if (graphics_extension) { - graphics_extension->cleanup_swapchain_graphics_data(&swapchain_graphics_data); + graphics_extension->cleanup_swapchain_graphics_data(&swapchains[OPENXR_SWAPCHAIN_COLOR].swapchain_graphics_data); } if (views != nullptr) { @@ -732,9 +823,16 @@ void OpenXRAPI::destroy_session() { projection_views = nullptr; } - if (swapchain != XR_NULL_HANDLE) { - xrDestroySwapchain(swapchain); - swapchain = XR_NULL_HANDLE; + if (depth_views != nullptr) { + memfree(depth_views); + depth_views = nullptr; + } + + for (int i = 0; i < OPENXR_SWAPCHAIN_MAX; i++) { + if (swapchains[i].swapchain != XR_NULL_HANDLE) { + xrDestroySwapchain(swapchains[i].swapchain); + swapchains[i].swapchain = XR_NULL_HANDLE; + } } if (supported_swapchain_formats != nullptr) { @@ -768,7 +866,7 @@ void OpenXRAPI::destroy_session() { } } -bool OpenXRAPI::create_swapchain(int64_t p_swapchain_format, uint32_t p_width, uint32_t p_height, uint32_t p_sample_count, uint32_t p_array_size, XrSwapchain &r_swapchain, void **r_swapchain_graphics_data) { +bool OpenXRAPI::create_swapchain(XrSwapchainUsageFlags p_usage_flags, int64_t p_swapchain_format, uint32_t p_width, uint32_t p_height, uint32_t p_sample_count, uint32_t p_array_size, XrSwapchain &r_swapchain, void **r_swapchain_graphics_data) { ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false); ERR_FAIL_NULL_V(graphics_extension, false); @@ -786,7 +884,7 @@ bool OpenXRAPI::create_swapchain(int64_t p_swapchain_format, uint32_t p_width, u XR_TYPE_SWAPCHAIN_CREATE_INFO, // type next_pointer, // next 0, // createFlags - XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT, // usageFlags + p_usage_flags, // usageFlags p_swapchain_format, // format p_sample_count, // sampleCount p_width, // width @@ -814,9 +912,7 @@ bool OpenXRAPI::create_swapchain(int64_t p_swapchain_format, uint32_t p_width, u } bool OpenXRAPI::on_state_idle() { -#ifdef DEBUG - print_line("On state idle"); -#endif + print_verbose("On state idle"); for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { wrapper->on_state_idle(); @@ -826,9 +922,7 @@ bool OpenXRAPI::on_state_idle() { } bool OpenXRAPI::on_state_ready() { -#ifdef DEBUG - print_line("On state ready"); -#endif + print_verbose("On state ready"); // begin session XrSessionBeginInfo session_begin_info = { @@ -850,7 +944,7 @@ bool OpenXRAPI::on_state_ready() { // That will be very very ugly // The other possibility is to create a separate OpenXRViewport type specifically for this goal as part of our OpenXR module - if (!create_main_swapchain()) { + if (!create_swapchains()) { return false; } @@ -871,9 +965,7 @@ bool OpenXRAPI::on_state_ready() { } bool OpenXRAPI::on_state_synchronized() { -#ifdef DEBUG - print_line("On state synchronized"); -#endif + print_verbose("On state synchronized"); // Just in case, see if we already have active trackers... List<RID> trackers; @@ -890,9 +982,7 @@ bool OpenXRAPI::on_state_synchronized() { } bool OpenXRAPI::on_state_visible() { -#ifdef DEBUG - print_line("On state visible"); -#endif + print_verbose("On state visible"); for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { wrapper->on_state_visible(); @@ -906,9 +996,7 @@ bool OpenXRAPI::on_state_visible() { } bool OpenXRAPI::on_state_focused() { -#ifdef DEBUG - print_line("On state focused"); -#endif + print_verbose("On state focused"); for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { wrapper->on_state_focused(); @@ -922,9 +1010,7 @@ bool OpenXRAPI::on_state_focused() { } bool OpenXRAPI::on_state_stopping() { -#ifdef DEBUG - print_line("On state stopping"); -#endif + print_verbose("On state stopping"); if (xr_interface) { xr_interface->on_state_stopping(); @@ -950,9 +1036,7 @@ bool OpenXRAPI::on_state_stopping() { } bool OpenXRAPI::on_state_loss_pending() { -#ifdef DEBUG - print_line("On state loss pending"); -#endif + print_verbose("On state loss pending"); for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { wrapper->on_state_loss_pending(); @@ -964,9 +1048,7 @@ bool OpenXRAPI::on_state_loss_pending() { } bool OpenXRAPI::on_state_exiting() { -#ifdef DEBUG - print_line("On state existing"); -#endif + print_verbose("On state existing"); for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { wrapper->on_state_exiting(); @@ -992,9 +1074,94 @@ bool OpenXRAPI::is_running() { return running; } +bool OpenXRAPI::openxr_loader_init() { +#ifdef ANDROID_ENABLED + ERR_FAIL_COND_V_MSG(openxr_loader_library_handle != nullptr, false, "OpenXR Loader library is already loaded."); + + { + Error error_code = OS::get_singleton()->open_dynamic_library(OPENXR_LOADER_NAME, openxr_loader_library_handle); + ERR_FAIL_COND_V_MSG(error_code != OK, false, "OpenXR loader not found."); + } + + { + Error error_code = OS::get_singleton()->get_dynamic_library_symbol_handle(openxr_loader_library_handle, "xrGetInstanceProcAddr", (void *&)xrGetInstanceProcAddr); + ERR_FAIL_COND_V_MSG(error_code != OK, false, "Symbol xrGetInstanceProcAddr not found in OpenXR Loader library."); + } +#endif + + // Resolve the symbols that don't require an instance + OPENXR_API_INIT_XR_FUNC_V(xrCreateInstance); + OPENXR_API_INIT_XR_FUNC_V(xrEnumerateApiLayerProperties); + OPENXR_API_INIT_XR_FUNC_V(xrEnumerateInstanceExtensionProperties); + + return true; +} + +bool OpenXRAPI::resolve_instance_openxr_symbols() { + ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false); + + OPENXR_API_INIT_XR_FUNC_V(xrAcquireSwapchainImage); + OPENXR_API_INIT_XR_FUNC_V(xrApplyHapticFeedback); + OPENXR_API_INIT_XR_FUNC_V(xrAttachSessionActionSets); + OPENXR_API_INIT_XR_FUNC_V(xrBeginFrame); + OPENXR_API_INIT_XR_FUNC_V(xrBeginSession); + OPENXR_API_INIT_XR_FUNC_V(xrCreateAction); + OPENXR_API_INIT_XR_FUNC_V(xrCreateActionSet); + OPENXR_API_INIT_XR_FUNC_V(xrCreateActionSpace); + OPENXR_API_INIT_XR_FUNC_V(xrCreateReferenceSpace); + OPENXR_API_INIT_XR_FUNC_V(xrCreateSession); + OPENXR_API_INIT_XR_FUNC_V(xrCreateSwapchain); + OPENXR_API_INIT_XR_FUNC_V(xrDestroyAction); + OPENXR_API_INIT_XR_FUNC_V(xrDestroyActionSet); + OPENXR_API_INIT_XR_FUNC_V(xrDestroyInstance); + OPENXR_API_INIT_XR_FUNC_V(xrDestroySession); + OPENXR_API_INIT_XR_FUNC_V(xrDestroySpace); + OPENXR_API_INIT_XR_FUNC_V(xrDestroySwapchain); + OPENXR_API_INIT_XR_FUNC_V(xrEndFrame); + OPENXR_API_INIT_XR_FUNC_V(xrEndSession); + OPENXR_API_INIT_XR_FUNC_V(xrEnumerateReferenceSpaces); + OPENXR_API_INIT_XR_FUNC_V(xrEnumerateSwapchainFormats); + OPENXR_API_INIT_XR_FUNC_V(xrEnumerateViewConfigurations); + OPENXR_API_INIT_XR_FUNC_V(xrEnumerateViewConfigurationViews); + OPENXR_API_INIT_XR_FUNC_V(xrGetActionStateBoolean); + OPENXR_API_INIT_XR_FUNC_V(xrGetActionStateFloat); + OPENXR_API_INIT_XR_FUNC_V(xrGetActionStateVector2f); + OPENXR_API_INIT_XR_FUNC_V(xrGetCurrentInteractionProfile); + OPENXR_API_INIT_XR_FUNC_V(xrGetSystem); + OPENXR_API_INIT_XR_FUNC_V(xrGetSystemProperties); + OPENXR_API_INIT_XR_FUNC_V(xrLocateViews); + OPENXR_API_INIT_XR_FUNC_V(xrLocateSpace); + OPENXR_API_INIT_XR_FUNC_V(xrPathToString); + OPENXR_API_INIT_XR_FUNC_V(xrPollEvent); + OPENXR_API_INIT_XR_FUNC_V(xrReleaseSwapchainImage); + OPENXR_API_INIT_XR_FUNC_V(xrResultToString); + OPENXR_API_INIT_XR_FUNC_V(xrStringToPath); + OPENXR_API_INIT_XR_FUNC_V(xrSuggestInteractionProfileBindings); + OPENXR_API_INIT_XR_FUNC_V(xrSyncActions); + OPENXR_API_INIT_XR_FUNC_V(xrWaitFrame); + OPENXR_API_INIT_XR_FUNC_V(xrWaitSwapchainImage); + + return true; +} + +XrResult OpenXRAPI::get_instance_proc_addr(const char *p_name, PFN_xrVoidFunction *p_addr) { + XrResult result = xrGetInstanceProcAddr(instance, p_name, p_addr); + + if (result != XR_SUCCESS) { + String error_message = String("Symbol ") + p_name + " not found in OpenXR instance."; + ERR_FAIL_COND_V_MSG(true, result, error_message.utf8().get_data()); + } + + return result; +} + bool OpenXRAPI::initialize(const String &p_rendering_driver) { ERR_FAIL_COND_V_MSG(instance != XR_NULL_HANDLE, false, "OpenXR instance was already created"); + if (!openxr_loader_init()) { + return false; + } + if (p_rendering_driver == "vulkan") { #ifdef VULKAN_ENABLED graphics_extension = memnew(OpenXRVulkanExtension(this)); @@ -1005,9 +1172,8 @@ bool OpenXRAPI::initialize(const String &p_rendering_driver) { #endif } else if (p_rendering_driver == "opengl3") { #ifdef GLES3_ENABLED - // graphics_extension = memnew(OpenXROpenGLExtension(this)); - // register_extension_wrapper(graphics_extension); - ERR_FAIL_V_MSG(false, "OpenXR: OpenGL is not supported at this time."); + graphics_extension = memnew(OpenXROpenGLExtension(this)); + register_extension_wrapper(graphics_extension); #else // shouldn't be possible... ERR_FAIL_V(false); @@ -1017,6 +1183,10 @@ bool OpenXRAPI::initialize(const String &p_rendering_driver) { } // initialize + for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) { + wrapper->on_before_instance_created(); + } + if (!load_layer_properties()) { destroy_instance(); return false; @@ -1032,6 +1202,11 @@ bool OpenXRAPI::initialize(const String &p_rendering_driver) { return false; } + if (!resolve_instance_openxr_symbols()) { + destroy_instance(); + return false; + } + if (!get_system_info()) { destroy_instance(); return false; @@ -1144,12 +1319,10 @@ XRPose::TrackingConfidence OpenXRAPI::get_head_center(Transform3D &r_transform, head_pose_confidence = confidence; if (head_pose_confidence == XRPose::XR_TRACKING_CONFIDENCE_NONE) { print_line("OpenXR head space location not valid (check tracking?)"); -#ifdef DEBUG } else if (head_pose_confidence == XRPose::XR_TRACKING_CONFIDENCE_LOW) { - print_line("OpenVR Head pose now tracking with low confidence"); + print_verbose("OpenVR Head pose now tracking with low confidence"); } else { - print_line("OpenVR Head pose now tracking with high confidence"); -#endif + print_verbose("OpenVR Head pose now tracking with high confidence"); } } @@ -1189,6 +1362,15 @@ bool OpenXRAPI::get_view_projection(uint32_t p_view, double p_z_near, double p_z return false; } + // if we're using depth views, make sure we update our near and far there... + if (depth_views != nullptr) { + for (uint32_t i = 0; i < view_count; i++) { + depth_views[i].nearZ = p_z_near; + depth_views[i].farZ = p_z_far; + } + } + + // now update our projection return graphics_extension->create_projection_fov(views[p_view].fov, p_z_near, p_z_far, p_camera_matrix); } @@ -1228,7 +1410,7 @@ bool OpenXRAPI::poll_events() { // TODO We get this event if we're about to loose our OpenXR instance. // We should queue exiting Godot at this point. - print_verbose("OpenXR EVENT: instance loss pending at " + itos(event->lossTime)); + print_verbose(String("OpenXR EVENT: instance loss pending at ") + itos(event->lossTime)); return false; } break; case XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED: { @@ -1236,9 +1418,9 @@ bool OpenXRAPI::poll_events() { session_state = event->state; if (session_state >= XR_SESSION_STATE_MAX_ENUM) { - print_verbose("OpenXR EVENT: session state changed to UNKNOWN - " + itos(session_state)); + print_verbose(String("OpenXR EVENT: session state changed to UNKNOWN - ") + itos(session_state)); } else { - print_verbose("OpenXR EVENT: session state changed to " + OpenXRUtil::get_session_state_name(session_state)); + print_verbose(String("OpenXR EVENT: session state changed to ") + OpenXRUtil::get_session_state_name(session_state)); switch (session_state) { case XR_SESSION_STATE_IDLE: @@ -1273,7 +1455,7 @@ bool OpenXRAPI::poll_events() { case XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING: { XrEventDataReferenceSpaceChangePending *event = (XrEventDataReferenceSpaceChangePending *)&runtimeEvent; - print_verbose("OpenXR EVENT: reference space type " + OpenXRUtil::get_reference_space_name(event->referenceSpaceType) + " change pending!"); + print_verbose(String("OpenXR EVENT: reference space type ") + OpenXRUtil::get_reference_space_name(event->referenceSpaceType) + " change pending!"); if (event->poseValid && xr_interface) { xr_interface->on_pose_recentered(); } @@ -1292,7 +1474,7 @@ bool OpenXRAPI::poll_events() { } break; default: if (!handled) { - print_verbose("OpenXR Unhandled event type " + OpenXRUtil::get_structure_type_name(runtimeEvent.type)); + print_verbose(String("OpenXR Unhandled event type ") + OpenXRUtil::get_structure_type_name(runtimeEvent.type)); } break; } @@ -1327,15 +1509,15 @@ bool OpenXRAPI::process() { return true; } -bool OpenXRAPI::acquire_image(XrSwapchain p_swapchain, uint32_t &r_image_index) { - ERR_FAIL_COND_V(image_acquired, true); // this was not released when it should be, error out and re-use... +bool OpenXRAPI::acquire_image(OpenXRSwapChainInfo &p_swapchain) { + ERR_FAIL_COND_V(p_swapchain.image_acquired, true); // this was not released when it should be, error out and re-use... XrResult result; XrSwapchainImageAcquireInfo swapchain_image_acquire_info = { XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO, // type nullptr // next }; - result = xrAcquireSwapchainImage(p_swapchain, &swapchain_image_acquire_info, &r_image_index); + result = xrAcquireSwapchainImage(p_swapchain.swapchain, &swapchain_image_acquire_info, &p_swapchain.image_index); if (XR_FAILED(result)) { print_line("OpenXR: failed to acquire swapchain image [", get_error_string(result), "]"); return false; @@ -1347,7 +1529,7 @@ bool OpenXRAPI::acquire_image(XrSwapchain p_swapchain, uint32_t &r_image_index) 17000000 // timeout in nanoseconds }; - result = xrWaitSwapchainImage(p_swapchain, &swapchain_image_wait_info); + result = xrWaitSwapchainImage(p_swapchain.swapchain, &swapchain_image_wait_info); if (XR_FAILED(result)) { print_line("OpenXR: failed to wait for swapchain image [", get_error_string(result), "]"); return false; @@ -1356,12 +1538,12 @@ bool OpenXRAPI::acquire_image(XrSwapchain p_swapchain, uint32_t &r_image_index) return true; } -bool OpenXRAPI::release_image(XrSwapchain p_swapchain) { +bool OpenXRAPI::release_image(OpenXRSwapChainInfo &p_swapchain) { XrSwapchainImageReleaseInfo swapchain_image_release_info = { XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO, // type nullptr // next }; - XrResult result = xrReleaseSwapchainImage(swapchain, &swapchain_image_release_info); + XrResult result = xrReleaseSwapchainImage(p_swapchain.swapchain, &swapchain_image_release_info); if (XR_FAILED(result)) { print_line("OpenXR: failed to release swapchain image! [", get_error_string(result), "]"); return false; @@ -1382,6 +1564,10 @@ void OpenXRAPI::pre_render() { // 2) It will use the previous timing to pause our thread so that rendering starts as close to displaying as possible // This must thus be called as close to when we start rendering as possible XrFrameWaitInfo frame_wait_info = { XR_TYPE_FRAME_WAIT_INFO, nullptr }; + frame_state.predictedDisplayTime = 0; + frame_state.predictedDisplayPeriod = 0; + frame_state.shouldRender = false; + XrResult result = xrWaitFrame(session, &frame_wait_info, &frame_state); if (XR_FAILED(result)) { print_line("OpenXR: xrWaitFrame() was not successful [", get_error_string(result), "]"); @@ -1396,7 +1582,7 @@ void OpenXRAPI::pre_render() { if (frame_state.predictedDisplayPeriod > 500000000) { // display period more then 0.5 seconds? must be wrong data - print_verbose("OpenXR resetting invalid display period " + rtos(frame_state.predictedDisplayPeriod)); + print_verbose(String("OpenXR resetting invalid display period ") + rtos(frame_state.predictedDisplayPeriod)); frame_state.predictedDisplayPeriod = 0; } @@ -1443,13 +1629,11 @@ void OpenXRAPI::pre_render() { } if (view_pose_valid != pose_valid) { view_pose_valid = pose_valid; -#ifdef DEBUG if (!view_pose_valid) { - print_line("OpenXR View pose became invalid"); + print_verbose("OpenXR View pose became invalid"); } else { - print_line("OpenXR View pose became valid"); + print_verbose("OpenXR View pose became valid"); } -#endif } // let's start our frame.. @@ -1471,28 +1655,41 @@ bool OpenXRAPI::pre_draw_viewport(RID p_render_target) { // TODO: at some point in time we may support multiple viewports in which case we need to handle that... + // Acquire our images + for (int i = 0; i < OPENXR_SWAPCHAIN_MAX; i++) { + if (!swapchains[i].image_acquired && swapchains[i].swapchain != XR_NULL_HANDLE) { + if (!acquire_image(swapchains[i])) { + return false; + } + swapchains[i].image_acquired = true; + } + } + return true; } +RID OpenXRAPI::get_color_texture() { + if (swapchains[OPENXR_SWAPCHAIN_COLOR].image_acquired) { + return graphics_extension->get_texture(swapchains[OPENXR_SWAPCHAIN_COLOR].swapchain_graphics_data, swapchains[OPENXR_SWAPCHAIN_COLOR].image_index); + } else { + return RID(); + } +} + +RID OpenXRAPI::get_depth_texture() { + if (swapchains[OPENXR_SWAPCHAIN_DEPTH].image_acquired) { + return graphics_extension->get_texture(swapchains[OPENXR_SWAPCHAIN_DEPTH].swapchain_graphics_data, swapchains[OPENXR_SWAPCHAIN_DEPTH].image_index); + } else { + return RID(); + } +} + void OpenXRAPI::post_draw_viewport(RID p_render_target) { if (!can_render()) { return; } - // TODO: at some point in time we may support multiple viewports in which case we need to handle that... - - // TODO: if we can get PR 51179 to work properly we can change away from this approach and move this into get_external_texture or something - if (!image_acquired) { - if (!acquire_image(swapchain, image_index)) { - return; - } - image_acquired = true; - - // print_line("OpenXR: acquired image " + itos(image_index) + ", copying..."); - - // Copy our buffer into our swap chain (remove once PR 51179 is done) - graphics_extension->copy_render_target_to_image(p_render_target, swapchain_graphics_data, image_index); - } + // Nothing to do here at this point in time... }; void OpenXRAPI::end_frame() { @@ -1504,7 +1701,7 @@ void OpenXRAPI::end_frame() { return; } - if (frame_state.shouldRender && view_pose_valid && !image_acquired) { + if (frame_state.shouldRender && view_pose_valid && !swapchains[OPENXR_SWAPCHAIN_COLOR].image_acquired) { print_line("OpenXR: No viewport was marked with use_xr, there is no rendered output!"); } @@ -1512,7 +1709,7 @@ void OpenXRAPI::end_frame() { // - shouldRender set to true // - a valid view pose for projection_views[eye].pose to submit layer // - an image to render - if (!frame_state.shouldRender || !view_pose_valid || !image_acquired) { + if (!frame_state.shouldRender || !view_pose_valid || !swapchains[OPENXR_SWAPCHAIN_COLOR].image_acquired) { // submit 0 layers when we shouldn't render XrFrameEndInfo frame_end_info = { XR_TYPE_FRAME_END_INFO, // type @@ -1533,10 +1730,12 @@ void OpenXRAPI::end_frame() { } // release our swapchain image if we acquired it - if (image_acquired) { - image_acquired = false; // whether we succeed or not, consider this released. + for (int i = 0; i < OPENXR_SWAPCHAIN_MAX; i++) { + if (swapchains[i].image_acquired) { + swapchains[i].image_acquired = false; // whether we succeed or not, consider this released. - release_image(swapchain); + release_image(swapchains[i]); + } } for (uint32_t eye = 0; eye < view_count; eye++) { @@ -1557,7 +1756,7 @@ void OpenXRAPI::end_frame() { XrCompositionLayerProjection projection_layer = { XR_TYPE_COMPOSITION_LAYER_PROJECTION, // type nullptr, // next - layers_list.size() > 1 ? XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT | XR_COMPOSITION_LAYER_CORRECT_CHROMATIC_ABERRATION_BIT : XR_COMPOSITION_LAYER_CORRECT_CHROMATIC_ABERRATION_BIT, // layerFlags + layers_list.size() > 0 ? XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT | XR_COMPOSITION_LAYER_CORRECT_CHROMATIC_ABERRATION_BIT : XR_COMPOSITION_LAYER_CORRECT_CHROMATIC_ABERRATION_BIT, // layerFlags play_space, // space view_count, // viewCount projection_views, // views @@ -1579,6 +1778,31 @@ void OpenXRAPI::end_frame() { } } +float OpenXRAPI::get_display_refresh_rate() const { + OpenXRDisplayRefreshRateExtension *drrext = OpenXRDisplayRefreshRateExtension::get_singleton(); + if (drrext) { + return drrext->get_refresh_rate(); + } + + return 0.0; +} + +void OpenXRAPI::set_display_refresh_rate(float p_refresh_rate) { + OpenXRDisplayRefreshRateExtension *drrext = OpenXRDisplayRefreshRateExtension::get_singleton(); + if (drrext != nullptr) { + drrext->set_refresh_rate(p_refresh_rate); + } +} + +Array OpenXRAPI::get_available_display_refresh_rates() const { + OpenXRDisplayRefreshRateExtension *drrext = OpenXRDisplayRefreshRateExtension::get_singleton(); + if (drrext != nullptr) { + return drrext->get_available_refresh_rates(); + } + + return Array(); +} + OpenXRAPI::OpenXRAPI() { // OpenXRAPI is only constructed if OpenXR is enabled. singleton = this; @@ -1643,7 +1867,12 @@ OpenXRAPI::OpenXRAPI() { #endif // register our other extensions + register_extension_wrapper(memnew(OpenXRPalmPoseExtension(this))); + register_extension_wrapper(memnew(OpenXRCompositionLayerDepthExtension(this))); register_extension_wrapper(memnew(OpenXRHTCViveTrackerExtension(this))); + register_extension_wrapper(memnew(OpenXRHandTrackingExtension(this))); + register_extension_wrapper(memnew(OpenXRFbPassthroughExtensionWrapper(this))); + register_extension_wrapper(memnew(OpenXRDisplayRefreshRateExtension(this))); } OpenXRAPI::~OpenXRAPI() { @@ -1669,6 +1898,13 @@ OpenXRAPI::~OpenXRAPI() { layer_properties = nullptr; } +#ifdef ANDROID_ENABLED + if (openxr_loader_library_handle) { + OS::get_singleton()->close_dynamic_library(openxr_loader_library_handle); + openxr_loader_library_handle = nullptr; + } +#endif + singleton = nullptr; } @@ -1745,6 +1981,18 @@ void OpenXRAPI::parse_velocities(const XrSpaceVelocity &p_velocity, Vector3 &r_l } } +bool OpenXRAPI::xr_result(XrResult result, const char *format, Array args) const { + if (XR_SUCCEEDED(result)) + return true; + + char resultString[XR_MAX_RESULT_STRING_SIZE]; + xrResultToString(instance, result, resultString); + + print_error(String("OpenXR ") + String(format).format(args) + String(" [") + String(resultString) + String("]")); + + return false; +} + RID OpenXRAPI::get_tracker_rid(XrPath p_path) { List<RID> current; tracker_owner.get_owned_list(¤t); @@ -1850,8 +2098,6 @@ RID OpenXRAPI::action_set_create(const String p_name, const String p_localized_n copy_string_to_char_buffer(p_name, action_set_info.actionSetName, XR_MAX_ACTION_SET_NAME_SIZE); copy_string_to_char_buffer(p_localized_name, action_set_info.localizedActionSetName, XR_MAX_LOCALIZED_ACTION_SET_NAME_SIZE); - // print_line("Creating action set ", action_set_info.actionSetName, " - ", action_set_info.localizedActionSetName, " (", itos(action_set_info.priority), ")"); - XrResult result = xrCreateActionSet(instance, &action_set_info, &action_set.handle); if (XR_FAILED(result)) { print_line("OpenXR: failed to create action set ", p_name, "! [", get_error_string(result), "]"); @@ -2005,8 +2251,6 @@ RID OpenXRAPI::action_create(RID p_action_set, const String p_name, const String copy_string_to_char_buffer(p_name, action_info.actionName, XR_MAX_ACTION_NAME_SIZE); copy_string_to_char_buffer(p_localized_name, action_info.localizedActionName, XR_MAX_LOCALIZED_ACTION_NAME_SIZE); - // print_line("Creating action ", action_info.actionName, action_info.localizedActionName, action_info.countSubactionPaths); - XrResult result = xrCreateAction(action_set->handle, &action_info, &action.handle); if (XR_FAILED(result)) { print_line("OpenXR: failed to create action ", p_name, "! [", get_error_string(result), "]"); @@ -2063,6 +2307,11 @@ XrPath OpenXRAPI::get_interaction_profile_path(RID p_interaction_profile) { } RID OpenXRAPI::interaction_profile_create(const String p_name) { + if (!is_path_supported(p_name)) { + // The extension enabling this path must not be active, we will silently skip this interaction profile + return RID(); + } + InteractionProfile new_interaction_profile; XrResult result = xrStringToPath(instance, p_name.utf8().get_data(), &new_interaction_profile.path); @@ -2099,6 +2348,11 @@ void OpenXRAPI::interaction_profile_clear_bindings(RID p_interaction_profile) { } bool OpenXRAPI::interaction_profile_add_binding(RID p_interaction_profile, RID p_action, const String p_path) { + if (!is_path_supported(p_path)) { + // The extension enabling this path must not be active, we will silently skip this binding + return false; + } + InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile); ERR_FAIL_NULL_V(ip, false); @@ -2426,3 +2680,11 @@ bool OpenXRAPI::trigger_haptic_pulse(RID p_action, RID p_tracker, float p_freque return true; } + +void OpenXRAPI::register_composition_layer_provider(OpenXRCompositionLayerProvider *provider) { + composition_layer_providers.append(provider); +} + +void OpenXRAPI::unregister_composition_layer_provider(OpenXRCompositionLayerProvider *provider) { + composition_layer_providers.erase(provider); +} diff --git a/modules/openxr/openxr_api.h b/modules/openxr/openxr_api.h index dc224c4237..5dce749351 100644 --- a/modules/openxr/openxr_api.h +++ b/modules/openxr/openxr_api.h @@ -36,6 +36,7 @@ #include "core/math/transform_3d.h" #include "core/math/vector2.h" #include "core/os/memory.h" +#include "core/string/print_string.h" #include "core/string/ustring.h" #include "core/templates/rb_map.h" #include "core/templates/rid_owner.h" @@ -50,6 +51,8 @@ #include "extensions/openxr_composition_layer_provider.h" #include "extensions/openxr_extension_wrapper.h" +#include "util.h" + // Note, OpenXR code that we wrote for our plugin makes use of C++20 notation for initialising structs which ensures zeroing out unspecified members. // Godot is currently restricted to C++17 which doesn't allow this notation. Make sure critical fields are set. @@ -100,7 +103,7 @@ private: XrFormFactor form_factor = XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY; XrViewConfigurationType view_configuration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO; XrReferenceSpaceType reference_space = XR_REFERENCE_SPACE_TYPE_STAGE; - XrEnvironmentBlendMode environment_blend_mode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE; + // XrEnvironmentBlendMode environment_blend_mode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE; // state XrInstance instance = XR_NULL_HANDLE; @@ -115,15 +118,28 @@ private: OpenXRGraphicsExtensionWrapper *graphics_extension = nullptr; XrSystemGraphicsProperties graphics_properties; - void *swapchain_graphics_data = nullptr; - uint32_t image_index = 0; - bool image_acquired = false; uint32_t view_count = 0; XrViewConfigurationView *view_configuration_views = nullptr; XrView *views = nullptr; XrCompositionLayerProjectionView *projection_views = nullptr; - XrSwapchain swapchain = XR_NULL_HANDLE; + XrCompositionLayerDepthInfoKHR *depth_views = nullptr; // Only used by Composition Layer Depth Extension if available + + enum OpenXRSwapChainTypes { + OPENXR_SWAPCHAIN_COLOR, + OPENXR_SWAPCHAIN_DEPTH, + // OPENXR_SWAPCHAIN_VELOCITY, + OPENXR_SWAPCHAIN_MAX + }; + + struct OpenXRSwapChainInfo { + XrSwapchain swapchain = XR_NULL_HANDLE; + void *swapchain_graphics_data = nullptr; + uint32_t image_index = 0; + bool image_acquired = false; + }; + + OpenXRSwapChainInfo swapchains[OPENXR_SWAPCHAIN_MAX]; XrSpace play_space = XR_NULL_HANDLE; XrSpace view_space = XR_NULL_HANDLE; @@ -134,6 +150,64 @@ private: bool load_supported_extensions(); bool is_extension_supported(const String &p_extension) const; + bool openxr_loader_init(); + bool resolve_instance_openxr_symbols(); + +#ifdef ANDROID_ENABLED + // On Android we keep tracker of our external OpenXR loader + void *openxr_loader_library_handle = nullptr; +#endif + + // function pointers +#ifdef ANDROID_ENABLED + // On non-Android platforms we use the OpenXR symbol linked into the engine binary. + PFN_xrGetInstanceProcAddr xrGetInstanceProcAddr = nullptr; +#endif + EXT_PROTO_XRRESULT_FUNC3(xrAcquireSwapchainImage, (XrSwapchain), swapchain, (const XrSwapchainImageAcquireInfo *), acquireInfo, (uint32_t *), index) + EXT_PROTO_XRRESULT_FUNC3(xrApplyHapticFeedback, (XrSession), session, (const XrHapticActionInfo *), hapticActionInfo, (const XrHapticBaseHeader *), hapticFeedback) + EXT_PROTO_XRRESULT_FUNC2(xrAttachSessionActionSets, (XrSession), session, (const XrSessionActionSetsAttachInfo *), attachInfo) + EXT_PROTO_XRRESULT_FUNC2(xrBeginFrame, (XrSession), session, (const XrFrameBeginInfo *), frameBeginInfo) + EXT_PROTO_XRRESULT_FUNC2(xrBeginSession, (XrSession), session, (const XrSessionBeginInfo *), beginInfo) + EXT_PROTO_XRRESULT_FUNC3(xrCreateAction, (XrActionSet), actionSet, (const XrActionCreateInfo *), createInfo, (XrAction *), action) + EXT_PROTO_XRRESULT_FUNC3(xrCreateActionSet, (XrInstance), instance, (const XrActionSetCreateInfo *), createInfo, (XrActionSet *), actionSet) + EXT_PROTO_XRRESULT_FUNC3(xrCreateActionSpace, (XrSession), session, (const XrActionSpaceCreateInfo *), createInfo, (XrSpace *), space) + EXT_PROTO_XRRESULT_FUNC2(xrCreateInstance, (const XrInstanceCreateInfo *), createInfo, (XrInstance *), instance) + EXT_PROTO_XRRESULT_FUNC3(xrCreateReferenceSpace, (XrSession), session, (const XrReferenceSpaceCreateInfo *), createInfo, (XrSpace *), space) + EXT_PROTO_XRRESULT_FUNC3(xrCreateSession, (XrInstance), instance, (const XrSessionCreateInfo *), createInfo, (XrSession *), session) + EXT_PROTO_XRRESULT_FUNC3(xrCreateSwapchain, (XrSession), session, (const XrSwapchainCreateInfo *), createInfo, (XrSwapchain *), swapchain) + EXT_PROTO_XRRESULT_FUNC1(xrDestroyAction, (XrAction), action) + EXT_PROTO_XRRESULT_FUNC1(xrDestroyActionSet, (XrActionSet), actionSet) + EXT_PROTO_XRRESULT_FUNC1(xrDestroyInstance, (XrInstance), instance) + EXT_PROTO_XRRESULT_FUNC1(xrDestroySession, (XrSession), session) + EXT_PROTO_XRRESULT_FUNC1(xrDestroySpace, (XrSpace), space) + EXT_PROTO_XRRESULT_FUNC1(xrDestroySwapchain, (XrSwapchain), swapchain) + EXT_PROTO_XRRESULT_FUNC2(xrEndFrame, (XrSession), session, (const XrFrameEndInfo *), frameEndInfo) + EXT_PROTO_XRRESULT_FUNC1(xrEndSession, (XrSession), session) + EXT_PROTO_XRRESULT_FUNC3(xrEnumerateApiLayerProperties, (uint32_t), propertyCapacityInput, (uint32_t *), propertyCountOutput, (XrApiLayerProperties *), properties) + EXT_PROTO_XRRESULT_FUNC4(xrEnumerateInstanceExtensionProperties, (const char *), layerName, (uint32_t), propertyCapacityInput, (uint32_t *), propertyCountOutput, (XrExtensionProperties *), properties) + EXT_PROTO_XRRESULT_FUNC4(xrEnumerateReferenceSpaces, (XrSession), session, (uint32_t), spaceCapacityInput, (uint32_t *), spaceCountOutput, (XrReferenceSpaceType *), spaces) + EXT_PROTO_XRRESULT_FUNC4(xrEnumerateSwapchainFormats, (XrSession), session, (uint32_t), formatCapacityInput, (uint32_t *), formatCountOutput, (int64_t *), formats) + EXT_PROTO_XRRESULT_FUNC5(xrEnumerateViewConfigurations, (XrInstance), instance, (XrSystemId), systemId, (uint32_t), viewConfigurationTypeCapacityInput, (uint32_t *), viewConfigurationTypeCountOutput, (XrViewConfigurationType *), viewConfigurationTypes) + EXT_PROTO_XRRESULT_FUNC6(xrEnumerateViewConfigurationViews, (XrInstance), instance, (XrSystemId), systemId, (XrViewConfigurationType), viewConfigurationType, (uint32_t), viewCapacityInput, (uint32_t *), viewCountOutput, (XrViewConfigurationView *), views) + EXT_PROTO_XRRESULT_FUNC3(xrGetActionStateBoolean, (XrSession), session, (const XrActionStateGetInfo *), getInfo, (XrActionStateBoolean *), state) + EXT_PROTO_XRRESULT_FUNC3(xrGetActionStateFloat, (XrSession), session, (const XrActionStateGetInfo *), getInfo, (XrActionStateFloat *), state) + EXT_PROTO_XRRESULT_FUNC3(xrGetActionStateVector2f, (XrSession), session, (const XrActionStateGetInfo *), getInfo, (XrActionStateVector2f *), state) + EXT_PROTO_XRRESULT_FUNC3(xrGetCurrentInteractionProfile, (XrSession), session, (XrPath), topLevelUserPath, (XrInteractionProfileState *), interactionProfile) + EXT_PROTO_XRRESULT_FUNC2(xrGetInstanceProperties, (XrInstance), instance, (XrInstanceProperties *), instanceProperties) + EXT_PROTO_XRRESULT_FUNC3(xrGetSystem, (XrInstance), instance, (const XrSystemGetInfo *), getInfo, (XrSystemId *), systemId) + EXT_PROTO_XRRESULT_FUNC3(xrGetSystemProperties, (XrInstance), instance, (XrSystemId), systemId, (XrSystemProperties *), properties) + EXT_PROTO_XRRESULT_FUNC4(xrLocateSpace, (XrSpace), space, (XrSpace), baseSpace, (XrTime), time, (XrSpaceLocation *), location) + EXT_PROTO_XRRESULT_FUNC6(xrLocateViews, (XrSession), session, (const XrViewLocateInfo *), viewLocateInfo, (XrViewState *), viewState, (uint32_t), viewCapacityInput, (uint32_t *), viewCountOutput, (XrView *), views) + EXT_PROTO_XRRESULT_FUNC5(xrPathToString, (XrInstance), instance, (XrPath), path, (uint32_t), bufferCapacityInput, (uint32_t *), bufferCountOutput, (char *), buffer) + EXT_PROTO_XRRESULT_FUNC2(xrPollEvent, (XrInstance), instance, (XrEventDataBuffer *), eventData) + EXT_PROTO_XRRESULT_FUNC2(xrReleaseSwapchainImage, (XrSwapchain), swapchain, (const XrSwapchainImageReleaseInfo *), releaseInfo) + EXT_PROTO_XRRESULT_FUNC3(xrResultToString, (XrInstance), instance, (XrResult), value, (char *), buffer) + EXT_PROTO_XRRESULT_FUNC3(xrStringToPath, (XrInstance), instance, (const char *), pathString, (XrPath *), path) + EXT_PROTO_XRRESULT_FUNC2(xrSuggestInteractionProfileBindings, (XrInstance), instance, (const XrInteractionProfileSuggestedBinding *), suggestedBindings) + EXT_PROTO_XRRESULT_FUNC2(xrSyncActions, (XrSession), session, (const XrActionsSyncInfo *), syncInfo) + EXT_PROTO_XRRESULT_FUNC3(xrWaitFrame, (XrSession), session, (const XrFrameWaitInfo *), frameWaitInfo, (XrFrameState *), frameState) + EXT_PROTO_XRRESULT_FUNC2(xrWaitSwapchainImage, (XrSwapchain), swapchain, (const XrSwapchainImageWaitInfo *), waitInfo) + // instance bool create_instance(); bool get_system_info(); @@ -149,13 +223,13 @@ private: bool setup_spaces(); bool load_supported_swapchain_formats(); bool is_swapchain_format_supported(int64_t p_swapchain_format); - bool create_main_swapchain(); + bool create_swapchains(); void destroy_session(); // swapchains - bool create_swapchain(int64_t p_swapchain_format, uint32_t p_width, uint32_t p_height, uint32_t p_sample_count, uint32_t p_array_size, XrSwapchain &r_swapchain, void **r_swapchain_graphics_data); - bool acquire_image(XrSwapchain p_swapchain, uint32_t &r_image_index); - bool release_image(XrSwapchain p_swapchain); + bool create_swapchain(XrSwapchainUsageFlags p_usage_flags, int64_t p_swapchain_format, uint32_t p_width, uint32_t p_height, uint32_t p_sample_count, uint32_t p_array_size, XrSwapchain &r_swapchain, void **r_swapchain_graphics_data); + bool acquire_image(OpenXRSwapChainInfo &p_swapchain); + bool release_image(OpenXRSwapChainInfo &p_swapchain); // action map struct Tracker { // Trackers represent tracked physical objects such as controllers, pucks, etc. @@ -212,9 +286,7 @@ private: // convencience void copy_string_to_char_buffer(const String p_string, char *p_buffer, int p_buffer_len); -protected: - friend class OpenXRVulkanExtension; - +public: XrInstance get_instance() const { return instance; }; XrSystemId get_system_id() const { return system_id; }; XrSession get_session() const { return session; }; @@ -227,10 +299,13 @@ protected: XRPose::TrackingConfidence transform_from_location(const XrHandJointLocationEXT &p_location, Transform3D &r_transform); void parse_velocities(const XrSpaceVelocity &p_velocity, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity); -public: + bool xr_result(XrResult result, const char *format, Array args = Array()) const; + bool is_path_supported(const String &p_path); + static bool openxr_is_enabled(bool p_check_run_in_editor = true); static OpenXRAPI *get_singleton(); + XrResult get_instance_proc_addr(const char *p_name, PFN_xrVoidFunction *p_addr); String get_error_string(XrResult result); String get_swapchain_format_name(int64_t p_swapchain_format) const; @@ -243,8 +318,9 @@ public: bool initialize_session(); void finish(); - XrTime get_next_frame_time() { return frame_state.predictedDisplayTime + frame_state.predictedDisplayPeriod; }; - bool can_render() { return instance != XR_NULL_HANDLE && session != XR_NULL_HANDLE && running && view_pose_valid && frame_state.shouldRender; }; + XrSpace get_play_space() const { return play_space; } + XrTime get_next_frame_time() { return frame_state.predictedDisplayTime + frame_state.predictedDisplayPeriod; } + bool can_render() { return instance != XR_NULL_HANDLE && session != XR_NULL_HANDLE && running && view_pose_valid && frame_state.shouldRender; } Size2 get_recommended_target_size(); XRPose::TrackingConfidence get_head_center(Transform3D &r_transform, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity); @@ -254,9 +330,16 @@ public: void pre_render(); bool pre_draw_viewport(RID p_render_target); + RID get_color_texture(); + RID get_depth_texture(); void post_draw_viewport(RID p_render_target); void end_frame(); + // Display refresh rate + float get_display_refresh_rate() const; + void set_display_refresh_rate(float p_refresh_rate); + Array get_available_display_refresh_rates() const; + // action map String get_default_action_map_resource_name(); @@ -288,6 +371,9 @@ public: XRPose::TrackingConfidence get_action_pose(RID p_action, RID p_tracker, Transform3D &r_transform, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity); bool trigger_haptic_pulse(RID p_action, RID p_tracker, float p_frequency, float p_amplitude, XrDuration p_duration_ns); + void register_composition_layer_provider(OpenXRCompositionLayerProvider *provider); + void unregister_composition_layer_provider(OpenXRCompositionLayerProvider *provider); + OpenXRAPI(); ~OpenXRAPI(); }; diff --git a/modules/openxr/openxr_interface.cpp b/modules/openxr/openxr_interface.cpp index 6c2f08e21d..77660eb6f0 100644 --- a/modules/openxr/openxr_interface.cpp +++ b/modules/openxr/openxr_interface.cpp @@ -41,6 +41,13 @@ void OpenXRInterface::_bind_methods() { ADD_SIGNAL(MethodInfo("session_focussed")); ADD_SIGNAL(MethodInfo("session_visible")); ADD_SIGNAL(MethodInfo("pose_recentered")); + + // Display refresh rate + ClassDB::bind_method(D_METHOD("get_display_refresh_rate"), &OpenXRInterface::get_display_refresh_rate); + ClassDB::bind_method(D_METHOD("set_display_refresh_rate", "refresh_rate"), &OpenXRInterface::set_display_refresh_rate); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "display_refresh_rate"), "set_display_refresh_rate", "get_display_refresh_rate"); + + ClassDB::bind_method(D_METHOD("get_available_display_refresh_rates"), &OpenXRInterface::get_available_display_refresh_rates); } StringName OpenXRInterface::get_name() const { @@ -89,7 +96,7 @@ void OpenXRInterface::_load_action_map() { // This may seem a bit duplicitous to a little bit of background info here. // OpenXRActionMap (with all its sub resource classes) is a class that allows us to configure and store an action map in. - // This gives the user the ability to edit the action map in a UI and customise the actions. + // This gives the user the ability to edit the action map in a UI and customize the actions. // OpenXR however requires us to submit an action map and it takes over from that point and we can no longer change it. // This system does that push and we store the info needed to then work with this action map going forward. @@ -132,10 +139,10 @@ void OpenXRInterface::_load_action_map() { if (action_map.is_valid()) { HashMap<Ref<OpenXRAction>, Action *> xr_actions; - Array action_sets = action_map->get_action_sets(); - for (int i = 0; i < action_sets.size(); i++) { + Array action_set_array = action_map->get_action_sets(); + for (int i = 0; i < action_set_array.size(); i++) { // Create our action set - Ref<OpenXRActionSet> xr_action_set = action_sets[i]; + Ref<OpenXRActionSet> xr_action_set = action_set_array[i]; ActionSet *action_set = create_action_set(xr_action_set->get_name(), xr_action_set->get_localized_name(), xr_action_set->get_priority()); if (!action_set) { continue; @@ -147,62 +154,65 @@ void OpenXRInterface::_load_action_map() { Ref<OpenXRAction> xr_action = actions[j]; PackedStringArray toplevel_paths = xr_action->get_toplevel_paths(); - Vector<Tracker *> trackers; + Vector<Tracker *> trackers_for_action; for (int k = 0; k < toplevel_paths.size(); k++) { - Tracker *tracker = find_tracker(toplevel_paths[k], true); - if (tracker) { - trackers.push_back(tracker); + // Only check for our tracker if our path is supported. + if (openxr_api->is_path_supported(toplevel_paths[k])) { + Tracker *tracker = find_tracker(toplevel_paths[k], true); + if (tracker) { + trackers_for_action.push_back(tracker); + } } } - Action *action = create_action(action_set, xr_action->get_name(), xr_action->get_localized_name(), xr_action->get_action_type(), trackers); - if (action) { - // we link our actions back to our trackers so we know which actions to check when we're processing our trackers - for (int t = 0; t < trackers.size(); t++) { - link_action_to_tracker(trackers[t], action); + // Only add our action if we have at least one valid toplevel path + if (trackers_for_action.size() > 0) { + Action *action = create_action(action_set, xr_action->get_name(), xr_action->get_localized_name(), xr_action->get_action_type(), trackers_for_action); + if (action) { + // add this to our map for creating our interaction profiles + xr_actions[xr_action] = action; } - - // add this to our map for creating our interaction profiles - xr_actions[xr_action] = action; } } } // now do our suggestions - Array interaction_profiles = action_map->get_interaction_profiles(); - for (int i = 0; i < interaction_profiles.size(); i++) { - Ref<OpenXRInteractionProfile> xr_interaction_profile = interaction_profiles[i]; + Array interaction_profile_array = action_map->get_interaction_profiles(); + for (int i = 0; i < interaction_profile_array.size(); i++) { + Ref<OpenXRInteractionProfile> xr_interaction_profile = interaction_profile_array[i]; // Note, we can only have one entry per interaction profile so if it already exists we clear it out RID ip = openxr_api->interaction_profile_create(xr_interaction_profile->get_interaction_profile_path()); - openxr_api->interaction_profile_clear_bindings(ip); - - Array xr_bindings = xr_interaction_profile->get_bindings(); - for (int j = 0; j < xr_bindings.size(); j++) { - Ref<OpenXRIPBinding> xr_binding = xr_bindings[j]; - Ref<OpenXRAction> xr_action = xr_binding->get_action(); - - Action *action = nullptr; - if (xr_actions.has(xr_action)) { - action = xr_actions[xr_action]; - } else { - print_line("Action ", xr_action->get_name(), " isn't part of an action set!"); - continue; - } + if (ip.is_valid()) { + openxr_api->interaction_profile_clear_bindings(ip); + + Array xr_bindings = xr_interaction_profile->get_bindings(); + for (int j = 0; j < xr_bindings.size(); j++) { + Ref<OpenXRIPBinding> xr_binding = xr_bindings[j]; + Ref<OpenXRAction> xr_action = xr_binding->get_action(); + + Action *action = nullptr; + if (xr_actions.has(xr_action)) { + action = xr_actions[xr_action]; + } else { + print_line("Action ", xr_action->get_name(), " isn't part of an action set!"); + continue; + } - PackedStringArray paths = xr_binding->get_paths(); - for (int k = 0; k < paths.size(); k++) { - openxr_api->interaction_profile_add_binding(ip, action->action_rid, paths[k]); + PackedStringArray paths = xr_binding->get_paths(); + for (int k = 0; k < paths.size(); k++) { + openxr_api->interaction_profile_add_binding(ip, action->action_rid, paths[k]); + } } - } - // Now submit our suggestions - openxr_api->interaction_profile_suggest_bindings(ip); + // Now submit our suggestions + openxr_api->interaction_profile_suggest_bindings(ip); - // And record it in our array so we can clean it up later on - if (interaction_profiles.has(ip)) { - interaction_profiles.push_back(ip); + // And record it in our array so we can clean it up later on + if (interaction_profile_array.has(ip)) { + interaction_profile_array.push_back(ip); + } } } } @@ -280,6 +290,13 @@ OpenXRInterface::Action *OpenXRInterface::create_action(ActionSet *p_action_set, action->action_rid = openxr_api->action_create(p_action_set->action_set_rid, p_action_name, p_localized_name, p_action_type, tracker_rids); p_action_set->actions.push_back(action); + // we link our actions back to our trackers so we know which actions to check when we're processing our trackers + for (int i = 0; i < p_trackers.size(); i++) { + if (p_trackers[i]->actions.find(action) == -1) { + p_trackers[i]->actions.push_back(action); + } + } + return action; } @@ -328,6 +345,8 @@ OpenXRInterface::Tracker *OpenXRInterface::find_tracker(const String &p_tracker_ return nullptr; } + ERR_FAIL_COND_V(!openxr_api->is_path_supported(p_tracker_name), nullptr); + // Create our RID RID tracker_rid = openxr_api->tracker_create(p_tracker_name); ERR_FAIL_COND_V(tracker_rid.is_null(), nullptr); @@ -336,7 +355,7 @@ OpenXRInterface::Tracker *OpenXRInterface::find_tracker(const String &p_tracker_ Ref<XRPositionalTracker> positional_tracker; positional_tracker.instantiate(); - // We have standardised some names to make things nicer to the user so lets recognise the toplevel paths related to these. + // We have standardized some names to make things nicer to the user so lets recognize the toplevel paths related to these. if (p_tracker_name == "/user/hand/left") { positional_tracker->set_tracker_type(XRServer::TRACKER_CONTROLLER); positional_tracker->set_tracker_name("left_hand"); @@ -387,12 +406,6 @@ void OpenXRInterface::tracker_profile_changed(RID p_tracker, RID p_interaction_p } } -void OpenXRInterface::link_action_to_tracker(Tracker *p_tracker, Action *p_action) { - if (p_tracker->actions.find(p_action) == -1) { - p_tracker->actions.push_back(p_action); - } -} - void OpenXRInterface::handle_tracker(Tracker *p_tracker) { ERR_FAIL_NULL(openxr_api); ERR_FAIL_COND(p_tracker->positional_tracker.is_null()); @@ -445,9 +458,18 @@ void OpenXRInterface::handle_tracker(Tracker *p_tracker) { void OpenXRInterface::trigger_haptic_pulse(const String &p_action_name, const StringName &p_tracker_name, double p_frequency, double p_amplitude, double p_duration_sec, double p_delay_sec) { ERR_FAIL_NULL(openxr_api); + Action *action = find_action(p_action_name); ERR_FAIL_NULL(action); - Tracker *tracker = find_tracker(p_tracker_name); + + // We need to map our tracker name to our OpenXR name for our inbuild names. + String tracker_name = p_tracker_name; + if (tracker_name == "left_hand") { + tracker_name = "/user/hand/left"; + } else if (tracker_name == "right_hand") { + tracker_name = "/user/hand/right"; + } + Tracker *tracker = find_tracker(tracker_name); ERR_FAIL_NULL(tracker); // TODO OpenXR does not support delay, so we may need to add support for that somehow... @@ -569,6 +591,36 @@ bool OpenXRInterface::set_play_area_mode(XRInterface::PlayAreaMode p_mode) { return false; } +float OpenXRInterface::get_display_refresh_rate() const { + if (openxr_api == nullptr) { + return 0.0; + } else if (!openxr_api->is_initialized()) { + return 0.0; + } else { + return openxr_api->get_display_refresh_rate(); + } +} + +void OpenXRInterface::set_display_refresh_rate(float p_refresh_rate) { + if (openxr_api == nullptr) { + return; + } else if (!openxr_api->is_initialized()) { + return; + } else { + openxr_api->set_display_refresh_rate(p_refresh_rate); + } +} + +Array OpenXRInterface::get_available_display_refresh_rates() const { + if (openxr_api == nullptr) { + return Array(); + } else if (!openxr_api->is_initialized()) { + return Array(); + } else { + return openxr_api->get_available_display_refresh_rates(); + } +} + Size2 OpenXRInterface::get_render_target_size() { if (openxr_api == nullptr) { return Size2(); @@ -614,6 +666,7 @@ Transform3D OpenXRInterface::get_camera_transform() { Transform3D OpenXRInterface::get_transform_for_view(uint32_t p_view, const Transform3D &p_cam_transform) { XRServer *xr_server = XRServer::get_singleton(); ERR_FAIL_NULL_V(xr_server, Transform3D()); + ERR_FAIL_UNSIGNED_INDEX_V_MSG(p_view, get_view_count(), Transform3D(), "View index outside bounds."); Transform3D t; if (openxr_api && openxr_api->get_view_transform(p_view, t)) { @@ -633,6 +686,7 @@ Transform3D OpenXRInterface::get_transform_for_view(uint32_t p_view, const Trans Projection OpenXRInterface::get_projection_for_view(uint32_t p_view, double p_aspect, double p_z_near, double p_z_far) { Projection cm; + ERR_FAIL_UNSIGNED_INDEX_V_MSG(p_view, get_view_count(), cm, "View index outside bounds."); if (openxr_api) { if (openxr_api->get_view_projection(p_view, p_z_near, p_z_far, cm)) { @@ -646,6 +700,22 @@ Projection OpenXRInterface::get_projection_for_view(uint32_t p_view, double p_as return cm; } +RID OpenXRInterface::get_color_texture() { + if (openxr_api) { + return openxr_api->get_color_texture(); + } else { + return RID(); + } +} + +RID OpenXRInterface::get_depth_texture() { + if (openxr_api) { + return openxr_api->get_depth_texture(); + } else { + return RID(); + } +} + void OpenXRInterface::process() { if (openxr_api) { // do our normal process @@ -705,6 +775,7 @@ bool OpenXRInterface::pre_draw_viewport(RID p_render_target) { Vector<BlitToScreen> OpenXRInterface::post_draw_viewport(RID p_render_target, const Rect2 &p_screen_rect) { Vector<BlitToScreen> blit_to_screen; +#ifndef ANDROID_ENABLED // If separate HMD we should output one eye to screen if (p_screen_rect != Rect2()) { BlitToScreen blit; @@ -730,6 +801,7 @@ Vector<BlitToScreen> OpenXRInterface::post_draw_viewport(RID p_render_target, co blit.dst_rect = dst_rect; blit_to_screen.push_back(blit); } +#endif if (openxr_api) { openxr_api->post_draw_viewport(p_render_target); @@ -744,6 +816,24 @@ void OpenXRInterface::end_frame() { } } +bool OpenXRInterface::is_passthrough_supported() { + return passthrough_wrapper != nullptr && passthrough_wrapper->is_passthrough_supported(); +} + +bool OpenXRInterface::is_passthrough_enabled() { + return passthrough_wrapper != nullptr && passthrough_wrapper->is_passthrough_enabled(); +} + +bool OpenXRInterface::start_passthrough() { + return passthrough_wrapper != nullptr && passthrough_wrapper->start_passthrough(); +} + +void OpenXRInterface::stop_passthrough() { + if (passthrough_wrapper) { + passthrough_wrapper->stop_passthrough(); + } +} + void OpenXRInterface::on_state_ready() { emit_signal(SNAME("session_begun")); } @@ -774,6 +864,8 @@ OpenXRInterface::OpenXRInterface() { _set_default_pos(head_transform, 1.0, 0); _set_default_pos(transform_for_view[0], 1.0, 1); _set_default_pos(transform_for_view[1], 1.0, 2); + + passthrough_wrapper = OpenXRFbPassthroughExtensionWrapper::get_singleton(); } OpenXRInterface::~OpenXRInterface() { diff --git a/modules/openxr/openxr_interface.h b/modules/openxr/openxr_interface.h index a99012fd1d..454612346f 100644 --- a/modules/openxr/openxr_interface.h +++ b/modules/openxr/openxr_interface.h @@ -37,6 +37,8 @@ #include "action_map/openxr_action_map.h" #include "openxr_api.h" +#include "extensions/openxr_fb_passthrough_extension_wrapper.h" + // declare some default strings #define INTERACTION_PROFILE_NONE "/interaction_profiles/none" @@ -47,6 +49,7 @@ private: OpenXRAPI *openxr_api = nullptr; bool initialized = false; XRInterface::TrackingStatus tracking_state; + OpenXRFbPassthroughExtensionWrapper *passthrough_wrapper = nullptr; // At a minimum we need a tracker for our head Ref<XRPositionalTracker> head; @@ -88,7 +91,6 @@ private: void free_actions(ActionSet *p_action_set); Tracker *find_tracker(const String &p_tracker_name, bool p_create = false); - void link_action_to_tracker(Tracker *p_tracker, Action *p_action); void handle_tracker(Tracker *p_tracker); void free_trackers(); @@ -117,18 +119,30 @@ public: virtual XRInterface::PlayAreaMode get_play_area_mode() const override; virtual bool set_play_area_mode(XRInterface::PlayAreaMode p_mode) override; + float get_display_refresh_rate() const; + void set_display_refresh_rate(float p_refresh_rate); + Array get_available_display_refresh_rates() const; + virtual Size2 get_render_target_size() override; virtual uint32_t get_view_count() override; virtual Transform3D get_camera_transform() override; virtual Transform3D get_transform_for_view(uint32_t p_view, const Transform3D &p_cam_transform) override; virtual Projection get_projection_for_view(uint32_t p_view, double p_aspect, double p_z_near, double p_z_far) override; + virtual RID get_color_texture() override; + virtual RID get_depth_texture() override; + virtual void process() override; virtual void pre_render() override; bool pre_draw_viewport(RID p_render_target) override; virtual Vector<BlitToScreen> post_draw_viewport(RID p_render_target, const Rect2 &p_screen_rect) override; virtual void end_frame() override; + virtual bool is_passthrough_supported() override; + virtual bool is_passthrough_enabled() override; + virtual bool start_passthrough() override; + virtual void stop_passthrough() override; + void on_state_ready(); void on_state_visible(); void on_state_focused(); diff --git a/modules/openxr/register_types.cpp b/modules/openxr/register_types.cpp index c765f169dc..5694fffe39 100644 --- a/modules/openxr/register_types.cpp +++ b/modules/openxr/register_types.cpp @@ -38,6 +38,8 @@ #include "action_map/openxr_action_set.h" #include "action_map/openxr_interaction_profile.h" +#include "scene/openxr_hand.h" + #ifdef TOOLS_ENABLED #include "editor/editor_node.h" @@ -82,6 +84,8 @@ void initialize_openxr_module(ModuleInitializationLevel p_level) { GDREGISTER_CLASS(OpenXRIPBinding); GDREGISTER_CLASS(OpenXRInteractionProfile); + GDREGISTER_CLASS(OpenXRHand); + XRServer *xr_server = XRServer::get_singleton(); if (xr_server) { openxr_interface.instantiate(); diff --git a/modules/openxr/scene/openxr_hand.cpp b/modules/openxr/scene/openxr_hand.cpp new file mode 100644 index 0000000000..588b818148 --- /dev/null +++ b/modules/openxr/scene/openxr_hand.cpp @@ -0,0 +1,307 @@ +/*************************************************************************/ +/* openxr_hand.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 "../extensions/openxr_hand_tracking_extension.h" +#include "../openxr_api.h" + +#include "openxr_hand.h" +#include "scene/3d/skeleton_3d.h" +#include "servers/xr_server.h" + +void OpenXRHand::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_hand", "hand"), &OpenXRHand::set_hand); + ClassDB::bind_method(D_METHOD("get_hand"), &OpenXRHand::get_hand); + + ClassDB::bind_method(D_METHOD("set_hand_skeleton", "hand_skeleton"), &OpenXRHand::set_hand_skeleton); + ClassDB::bind_method(D_METHOD("get_hand_skeleton"), &OpenXRHand::get_hand_skeleton); + + ClassDB::bind_method(D_METHOD("set_motion_range", "motion_range"), &OpenXRHand::set_motion_range); + ClassDB::bind_method(D_METHOD("get_motion_range"), &OpenXRHand::get_motion_range); + + ADD_PROPERTY(PropertyInfo(Variant::INT, "hand", PROPERTY_HINT_ENUM, "Left,Right"), "set_hand", "get_hand"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "motion_range", PROPERTY_HINT_ENUM, "Unobstructed,Conform to controller"), "set_motion_range", "get_motion_range"); + ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "hand_skeleton", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Skeleton3D"), "set_hand_skeleton", "get_hand_skeleton"); + + BIND_ENUM_CONSTANT(HAND_LEFT); + BIND_ENUM_CONSTANT(HAND_RIGHT); + BIND_ENUM_CONSTANT(HAND_MAX); + + BIND_ENUM_CONSTANT(MOTION_RANGE_UNOBSTRUCTED); + BIND_ENUM_CONSTANT(MOTION_RANGE_CONFORM_TO_CONTROLLER); + BIND_ENUM_CONSTANT(MOTION_RANGE_MAX); +} + +OpenXRHand::OpenXRHand() { + openxr_api = OpenXRAPI::get_singleton(); + hand_tracking_ext = OpenXRHandTrackingExtension::get_singleton(); +} + +void OpenXRHand::set_hand(const Hands p_hand) { + ERR_FAIL_INDEX(p_hand, HAND_MAX); + + hand = p_hand; +} + +OpenXRHand::Hands OpenXRHand::get_hand() const { + return hand; +} + +void OpenXRHand::set_hand_skeleton(const NodePath &p_hand_skeleton) { + hand_skeleton = p_hand_skeleton; + + // TODO if inside tree call _get_bones() +} + +void OpenXRHand::set_motion_range(const MotionRange p_motion_range) { + ERR_FAIL_INDEX(p_motion_range, MOTION_RANGE_MAX); + motion_range = p_motion_range; + + _set_motion_range(); +} + +OpenXRHand::MotionRange OpenXRHand::get_motion_range() const { + return motion_range; +} + +NodePath OpenXRHand::get_hand_skeleton() const { + return hand_skeleton; +} + +void OpenXRHand::_set_motion_range() { + if (!hand_tracking_ext) { + return; + } + + XrHandJointsMotionRangeEXT xr_motion_range; + switch (motion_range) { + case MOTION_RANGE_UNOBSTRUCTED: + xr_motion_range = XR_HAND_JOINTS_MOTION_RANGE_UNOBSTRUCTED_EXT; + break; + case MOTION_RANGE_CONFORM_TO_CONTROLLER: + xr_motion_range = XR_HAND_JOINTS_MOTION_RANGE_CONFORMING_TO_CONTROLLER_EXT; + break; + default: + xr_motion_range = XR_HAND_JOINTS_MOTION_RANGE_CONFORMING_TO_CONTROLLER_EXT; + break; + } + + hand_tracking_ext->set_motion_range(hand, xr_motion_range); +} + +Skeleton3D *OpenXRHand::get_skeleton() { + if (!has_node(hand_skeleton)) { + return nullptr; + } + + Node *node = get_node(hand_skeleton); + if (!node) { + return nullptr; + } + + Skeleton3D *skeleton = Object::cast_to<Skeleton3D>(node); + return skeleton; +} + +void OpenXRHand::_get_bones() { + const char *bone_names[XR_HAND_JOINT_COUNT_EXT] = { + "Palm", + "Wrist", + "Thumb_Metacarpal", + "Thumb_Proximal", + "Thumb_Distal", + "Thumb_Tip", + "Index_Metacarpal", + "Index_Proximal", + "Index_Intermediate", + "Index_Distal", + "Index_Tip", + "Middle_Metacarpal", + "Middle_Proximal", + "Middle_Intermediate", + "Middle_Distal", + "Middle_Tip", + "Ring_Metacarpal", + "Ring_Proximal", + "Ring_Intermediate", + "Ring_Distal", + "Ring_Tip", + "Little_Metacarpal", + "Little_Proximal", + "Little_Intermediate", + "Little_Distal", + "Little_Tip", + }; + + // reset JIC + for (int i = 0; i < XR_HAND_JOINT_COUNT_EXT; i++) { + bones[i] = -1; + } + + Skeleton3D *skeleton = get_skeleton(); + if (!skeleton) { + return; + } + + // We cast to spatials which should allow us to use any subclass of that. + for (int i = 0; i < XR_HAND_JOINT_COUNT_EXT; i++) { + String bone_name = bone_names[i]; + if (hand == 0) { + bone_name += String("_L"); + } else { + bone_name += String("_R"); + } + + bones[i] = skeleton->find_bone(bone_name); + if (bones[i] == -1) { + print_line("Couldn't obtain bone for", bone_name); + } + } +} + +void OpenXRHand::_update_skeleton() { + if (openxr_api == nullptr || !openxr_api->is_initialized()) { + return; + } else if (hand_tracking_ext == nullptr || !hand_tracking_ext->get_active()) { + return; + } + + Skeleton3D *skeleton = get_skeleton(); + if (!skeleton) { + return; + } + + // we cache our transforms so we can quickly calculate local transforms + XRPose::TrackingConfidence confidences[XR_HAND_JOINT_COUNT_EXT]; + Quaternion quaternions[XR_HAND_JOINT_COUNT_EXT]; + Quaternion inv_quaternions[XR_HAND_JOINT_COUNT_EXT]; + Vector3 positions[XR_HAND_JOINT_COUNT_EXT]; + + const OpenXRHandTrackingExtension::HandTracker *hand_tracker = hand_tracking_ext->get_hand_tracker(hand); + const float ws = XRServer::get_singleton()->get_world_scale(); + + if (hand_tracker->is_initialized && hand_tracker->locations.isActive) { + for (int i = 0; i < XR_HAND_JOINT_COUNT_EXT; i++) { + confidences[i] = XRPose::XR_TRACKING_CONFIDENCE_NONE; + quaternions[i] = Quaternion(); + positions[i] = Vector3(); + + const auto &location = hand_tracker->joint_locations[i]; + const auto &pose = location.pose; + + if (location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT) { + if (pose.orientation.x != 0 || pose.orientation.y != 0 || pose.orientation.y != 0 || pose.orientation.w != 0) { + quaternions[i] = Quaternion(pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w); + inv_quaternions[i] = quaternions[i].inverse(); + + if (location.locationFlags & XR_SPACE_LOCATION_POSITION_VALID_BIT) { + confidences[i] = XRPose::XR_TRACKING_CONFIDENCE_HIGH; + positions[i] = Vector3(pose.position.x * ws, pose.position.y * ws, pose.position.z * ws); + + // TODO get inverse of position, we'll do this later. For now we're ignoring bone positions which generally works better anyway + } else { + confidences[i] = XRPose::XR_TRACKING_CONFIDENCE_LOW; + } + } + } + } + + if (confidences[XR_HAND_JOINT_PALM_EXT] != XRPose::XR_TRACKING_CONFIDENCE_NONE) { + // now update our skeleton + for (int i = 0; i < XR_HAND_JOINT_COUNT_EXT; i++) { + if (bones[i] != -1) { + int bone = bones[i]; + int parent = skeleton->get_bone_parent(bone); + + // Get our target quaternion + Quaternion q = quaternions[i]; + + // get local translation, parent should already be processed + if (parent == -1) { + // use our palm location here, that is what we are tracking + q = inv_quaternions[XR_HAND_JOINT_PALM_EXT] * q; + } else { + int found = false; + for (int b = 0; b < XR_HAND_JOINT_COUNT_EXT && !found; b++) { + if (bones[b] == parent) { + q = inv_quaternions[b] * q; + found = true; + } + } + } + + // And get the movement from our rest position + // Transform3D rest = skeleton->get_bone_rest(bones[i]); + // q = rest.basis.get_quaternion().inverse() * q; + + // and set our pose + // skeleton->set_bone_pose_position(bones[i], v); + skeleton->set_bone_pose_rotation(bones[i], q); + } + } + + Transform3D t; + t.basis = Basis(quaternions[XR_HAND_JOINT_PALM_EXT]); + t.origin = positions[XR_HAND_JOINT_PALM_EXT]; + set_transform(t); + + // show it + set_visible(true); + } else { + // hide it + set_visible(false); + } + } else { + // hide it + set_visible(false); + } +} + +void OpenXRHand::_notification(int p_what) { + switch (p_what) { + case NOTIFICATION_ENTER_TREE: { + _get_bones(); + + set_process_internal(true); + } break; + case NOTIFICATION_EXIT_TREE: { + set_process_internal(false); + + // reset + for (int i = 0; i < XR_HAND_JOINT_COUNT_EXT; i++) { + bones[i] = -1; + } + } break; + case NOTIFICATION_INTERNAL_PROCESS: { + _update_skeleton(); + } break; + default: { + } break; + } +} diff --git a/modules/openxr/scene/openxr_hand.h b/modules/openxr/scene/openxr_hand.h new file mode 100644 index 0000000000..f8499cc172 --- /dev/null +++ b/modules/openxr/scene/openxr_hand.h @@ -0,0 +1,93 @@ +/*************************************************************************/ +/* openxr_hand.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 OPENXR_HAND_H +#define OPENXR_HAND_H + +#include "scene/3d/node_3d.h" +#include "scene/3d/skeleton_3d.h" + +class OpenXRAPI; +class OpenXRHandTrackingExtension; + +class OpenXRHand : public Node3D { + GDCLASS(OpenXRHand, Node3D); + +public: + enum Hands { + HAND_LEFT, + HAND_RIGHT, + HAND_MAX + }; + + enum MotionRange { + MOTION_RANGE_UNOBSTRUCTED, + MOTION_RANGE_CONFORM_TO_CONTROLLER, + MOTION_RANGE_MAX + }; + +private: + OpenXRAPI *openxr_api = nullptr; + OpenXRHandTrackingExtension *hand_tracking_ext = nullptr; + + Hands hand = HAND_LEFT; + MotionRange motion_range = MOTION_RANGE_UNOBSTRUCTED; + NodePath hand_skeleton; + + int64_t bones[XR_HAND_JOINT_COUNT_EXT]; + + void _set_motion_range(); + + Skeleton3D *get_skeleton(); + void _get_bones(); + void _update_skeleton(); + +protected: + static void _bind_methods(); + +public: + OpenXRHand(); + + void set_hand(const Hands p_hand); + Hands get_hand() const; + + void set_motion_range(const MotionRange p_motion_range); + MotionRange get_motion_range() const; + + void set_hand_skeleton(const NodePath &p_hand_skeleton); + NodePath get_hand_skeleton() const; + + void _notification(int p_what); +}; + +VARIANT_ENUM_CAST(OpenXRHand::Hands) +VARIANT_ENUM_CAST(OpenXRHand::MotionRange) + +#endif // OPENXR_HAND_H diff --git a/modules/openxr/util.h b/modules/openxr/util.h new file mode 100644 index 0000000000..1b5e0451dc --- /dev/null +++ b/modules/openxr/util.h @@ -0,0 +1,110 @@ +/*************************************************************************/ +/* util.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 UTIL_H +#define UTIL_H + +#define UNPACK(...) __VA_ARGS__ + +#define INIT_XR_FUNC_V(openxr_api, name) \ + do { \ + XrResult get_instance_proc_addr_result; \ + get_instance_proc_addr_result = openxr_api->get_instance_proc_addr(#name, (PFN_xrVoidFunction *)&name##_ptr); \ + ERR_FAIL_COND_V(XR_FAILED(get_instance_proc_addr_result), false); \ + } while (0) + +#define EXT_INIT_XR_FUNC_V(name) INIT_XR_FUNC_V(openxr_api, name) +#define OPENXR_API_INIT_XR_FUNC_V(name) INIT_XR_FUNC_V(this, name) + +#define INIT_XR_FUNC(openxr_api, name) \ + do { \ + XrResult get_instance_proc_addr_result; \ + get_instance_proc_addr_result = openxr_api->get_instance_proc_addr(#name, (PFN_xrVoidFunction *)&name##_ptr); \ + ERR_FAIL_COND(XR_FAILED(get_instance_proc_addr_result)); \ + } while (0) + +#define EXT_INIT_XR_FUNC(name) INIT_XR_FUNC(openxr_api, name) +#define OPENXR_API_INIT_XR_FUNC(name) INIT_XR_FUNC(this, name) + +#define EXT_PROTO_XRRESULT_FUNC1(func_name, arg1_type, arg1) \ + PFN_##func_name func_name##_ptr = nullptr; \ + XRAPI_ATTR XrResult XRAPI_CALL func_name(UNPACK arg1_type p_##arg1) const { \ + if (!func_name##_ptr) { \ + return XR_ERROR_HANDLE_INVALID; \ + } \ + return (*func_name##_ptr)(p_##arg1); \ + } + +#define EXT_PROTO_XRRESULT_FUNC2(func_name, arg1_type, arg1, arg2_type, arg2) \ + PFN_##func_name func_name##_ptr = nullptr; \ + XRAPI_ATTR XrResult XRAPI_CALL func_name(UNPACK arg1_type p_##arg1, UNPACK arg2_type p_##arg2) const { \ + if (!func_name##_ptr) { \ + return XR_ERROR_HANDLE_INVALID; \ + } \ + return (*func_name##_ptr)(p_##arg1, p_##arg2); \ + } + +#define EXT_PROTO_XRRESULT_FUNC3(func_name, arg1_type, arg1, arg2_type, arg2, arg3_type, arg3) \ + PFN_##func_name func_name##_ptr = nullptr; \ + XRAPI_ATTR XrResult XRAPI_CALL func_name(UNPACK arg1_type p_##arg1, UNPACK arg2_type p_##arg2, UNPACK arg3_type p_##arg3) const { \ + if (!func_name##_ptr) { \ + return XR_ERROR_HANDLE_INVALID; \ + } \ + return (*func_name##_ptr)(p_##arg1, p_##arg2, p_##arg3); \ + } + +#define EXT_PROTO_XRRESULT_FUNC4(func_name, arg1_type, arg1, arg2_type, arg2, arg3_type, arg3, arg4_type, arg4) \ + PFN_##func_name func_name##_ptr = nullptr; \ + XRAPI_ATTR XrResult XRAPI_CALL func_name(UNPACK arg1_type p_##arg1, UNPACK arg2_type p_##arg2, UNPACK arg3_type p_##arg3, UNPACK arg4_type p_##arg4) const { \ + if (!func_name##_ptr) { \ + return XR_ERROR_HANDLE_INVALID; \ + } \ + return (*func_name##_ptr)(p_##arg1, p_##arg2, p_##arg3, p_##arg4); \ + } + +#define EXT_PROTO_XRRESULT_FUNC5(func_name, arg1_type, arg1, arg2_type, arg2, arg3_type, arg3, arg4_type, arg4, arg5_type, arg5) \ + PFN_##func_name func_name##_ptr = nullptr; \ + XRAPI_ATTR XrResult XRAPI_CALL func_name(UNPACK arg1_type p_##arg1, UNPACK arg2_type p_##arg2, UNPACK arg3_type p_##arg3, UNPACK arg4_type p_##arg4, UNPACK arg5_type p_##arg5) const { \ + if (!func_name##_ptr) { \ + return XR_ERROR_HANDLE_INVALID; \ + } \ + return (*func_name##_ptr)(p_##arg1, p_##arg2, p_##arg3, p_##arg4, p_##arg5); \ + } + +#define EXT_PROTO_XRRESULT_FUNC6(func_name, arg1_type, arg1, arg2_type, arg2, arg3_type, arg3, arg4_type, arg4, arg5_type, arg5, arg6_type, arg6) \ + PFN_##func_name func_name##_ptr = nullptr; \ + XRAPI_ATTR XrResult XRAPI_CALL func_name(UNPACK arg1_type p_##arg1, UNPACK arg2_type p_##arg2, UNPACK arg3_type p_##arg3, UNPACK arg4_type p_##arg4, UNPACK arg5_type p_##arg5, UNPACK arg6_type p_##arg6) const { \ + if (!func_name##_ptr) { \ + return XR_ERROR_HANDLE_INVALID; \ + } \ + return (*func_name##_ptr)(p_##arg1, p_##arg2, p_##arg3, p_##arg4, p_##arg5, p_##arg6); \ + } + +#endif // UTIL_H diff --git a/modules/raycast/SCsub b/modules/raycast/SCsub index 074795759a..20b05816e1 100644 --- a/modules/raycast/SCsub +++ b/modules/raycast/SCsub @@ -63,7 +63,8 @@ if env["builtin_embree"]: thirdparty_sources = [thirdparty_dir + file for file in embree_src] env_raycast.Prepend(CPPPATH=[thirdparty_dir, thirdparty_dir + "include"]) - env_raycast.Append(CPPDEFINES=["EMBREE_TARGET_SSE2", "EMBREE_LOWEST_ISA", "TASKING_INTERNAL", "NDEBUG"]) + env_raycast.Append(CPPDEFINES=["EMBREE_TARGET_SSE2", "EMBREE_LOWEST_ISA", "TASKING_INTERNAL"]) + env_raycast.AppendUnique(CPPDEFINES=["NDEBUG"]) # No assert() even in debug builds. if not env.msvc: if env["arch"] == "x86_64": @@ -78,6 +79,9 @@ if env["builtin_embree"]: else: env.Append(LIBS=["psapi"]) + if env.msvc: # Disable bogus warning about intentional struct padding. + env_raycast.Append(CCFLAGS=["/wd4324"]) + env_thirdparty = env_raycast.Clone() env_thirdparty.force_optimization_on_debug() env_thirdparty.disable_warnings() diff --git a/modules/raycast/lightmap_raycaster.cpp b/modules/raycast/lightmap_raycaster_embree.cpp index 9b35b5616e..e6a579bd3a 100644 --- a/modules/raycast/lightmap_raycaster.cpp +++ b/modules/raycast/lightmap_raycaster_embree.cpp @@ -1,5 +1,5 @@ /*************************************************************************/ -/* lightmap_raycaster.cpp */ +/* lightmap_raycaster_embree.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -30,7 +30,7 @@ #ifdef TOOLS_ENABLED -#include "lightmap_raycaster.h" +#include "lightmap_raycaster_embree.h" #ifdef __SSE2__ #include <pmmintrin.h> @@ -193,4 +193,4 @@ LightmapRaycasterEmbree::~LightmapRaycasterEmbree() { } } -#endif +#endif // TOOLS_ENABLED diff --git a/modules/raycast/lightmap_raycaster.h b/modules/raycast/lightmap_raycaster_embree.h index 2e9f59dda4..0c3371f07c 100644 --- a/modules/raycast/lightmap_raycaster.h +++ b/modules/raycast/lightmap_raycaster_embree.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* lightmap_raycaster.h */ +/* lightmap_raycaster_embree.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,6 +28,9 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ +#ifndef LIGHTMAP_RAYCASTER_EMBREE_H +#define LIGHTMAP_RAYCASTER_EMBREE_H + #ifdef TOOLS_ENABLED #include "core/io/image.h" @@ -74,4 +77,6 @@ public: ~LightmapRaycasterEmbree(); }; -#endif // LIGHTMAP_RAYCASTER_H +#endif // TOOLS_ENABLED + +#endif // LIGHTMAP_RAYCASTER_EMBREE_H diff --git a/modules/raycast/register_types.cpp b/modules/raycast/register_types.cpp index 42de1d971d..a8380b00ba 100644 --- a/modules/raycast/register_types.cpp +++ b/modules/raycast/register_types.cpp @@ -30,9 +30,9 @@ #include "register_types.h" -#include "lightmap_raycaster.h" +#include "lightmap_raycaster_embree.h" #include "raycast_occlusion_cull.h" -#include "static_raycaster.h" +#include "static_raycaster_embree.h" RaycastOcclusionCull *raycast_occlusion_cull = nullptr; diff --git a/modules/raycast/register_types.h b/modules/raycast/register_types.h index a917285390..25a6c346b9 100644 --- a/modules/raycast/register_types.h +++ b/modules/raycast/register_types.h @@ -28,7 +28,12 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ +#ifndef RAYCAST_REGISTER_TYPES_H +#define RAYCAST_REGISTER_TYPES_H + #include "modules/register_module_types.h" void initialize_raycast_module(ModuleInitializationLevel p_level); void uninitialize_raycast_module(ModuleInitializationLevel p_level); + +#endif // RAYCAST_REGISTER_TYPES_H diff --git a/modules/raycast/static_raycaster.cpp b/modules/raycast/static_raycaster_embree.cpp index 7659eea27f..b5a4ab42d4 100644 --- a/modules/raycast/static_raycaster.cpp +++ b/modules/raycast/static_raycaster_embree.cpp @@ -1,5 +1,5 @@ /*************************************************************************/ -/* static_raycaster.cpp */ +/* static_raycaster_embree.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -30,7 +30,7 @@ #ifdef TOOLS_ENABLED -#include "static_raycaster.h" +#include "static_raycaster_embree.h" #ifdef __SSE2__ #include <pmmintrin.h> @@ -134,4 +134,4 @@ StaticRaycasterEmbree::~StaticRaycasterEmbree() { } } -#endif +#endif // TOOLS_ENABLED diff --git a/modules/raycast/static_raycaster.h b/modules/raycast/static_raycaster_embree.h index 607a392683..4d631e3ca0 100644 --- a/modules/raycast/static_raycaster.h +++ b/modules/raycast/static_raycaster_embree.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* static_raycaster.h */ +/* static_raycaster_embree.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,6 +28,9 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ +#ifndef STATIC_RAYCASTER_EMBREE_H +#define STATIC_RAYCASTER_EMBREE_H + #ifdef TOOLS_ENABLED #include "core/math/static_raycaster.h" @@ -61,4 +64,6 @@ public: ~StaticRaycasterEmbree(); }; -#endif // STATIC_RAYCASTER_H +#endif // TOOLS_ENABLED + +#endif // STATIC_RAYCASTER_EMBREE_H diff --git a/modules/regex/SCsub b/modules/regex/SCsub index deb9db7591..6fd7cd47f3 100644 --- a/modules/regex/SCsub +++ b/modules/regex/SCsub @@ -58,10 +58,10 @@ if env["builtin_pcre2"]: env_pcre2["OBJSUFFIX"] = "_" + width + env_pcre2["OBJSUFFIX"] env_pcre2.Append(CPPDEFINES=[("PCRE2_CODE_UNIT_WIDTH", width)]) env_pcre2.add_source_files(thirdparty_obj, thirdparty_sources) - env.modules_sources += thirdparty_obj pcre2_builtin("16") pcre2_builtin("32") + env.modules_sources += thirdparty_obj # Godot source files diff --git a/modules/regex/doc_classes/RegEx.xml b/modules/regex/doc_classes/RegEx.xml index 56404f796c..02260c837e 100644 --- a/modules/regex/doc_classes/RegEx.xml +++ b/modules/regex/doc_classes/RegEx.xml @@ -4,7 +4,7 @@ Class for searching text for patterns using regular expressions. </brief_description> <description> - A regular expression (or regex) is a compact language that can be used to recognise strings that follow a specific pattern, such as URLs, email addresses, complete sentences, etc. For instance, a regex of [code]ab[0-9][/code] would find any string that is [code]ab[/code] followed by any number from [code]0[/code] to [code]9[/code]. For a more in-depth look, you can easily find various tutorials and detailed explanations on the Internet. + A regular expression (or regex) is a compact language that can be used to recognize strings that follow a specific pattern, such as URLs, email addresses, complete sentences, etc. For example, a regex of [code]ab[0-9][/code] would find any string that is [code]ab[/code] followed by any number from [code]0[/code] to [code]9[/code]. For a more in-depth look, you can easily find various tutorials and detailed explanations on the Internet. To begin, the RegEx object needs to be compiled with the search pattern using [method compile] before it can be used. [codeblock] var regex = RegEx.new() @@ -99,7 +99,8 @@ <param index="1" name="offset" type="int" default="0" /> <param index="2" name="end" type="int" default="-1" /> <description> - Searches the text for the compiled pattern. Returns a [RegExMatch] container of the first matching result if found, otherwise [code]null[/code]. The region to search within can be specified without modifying where the start and end anchor would be. + Searches the text for the compiled pattern. Returns a [RegExMatch] container of the first matching result if found, otherwise [code]null[/code]. + The region to search within can be specified with [param offset] and [param end]. This is useful when searching for another match in the same [param subject] by calling this method again after a previous success. Note that setting these parameters differs from passing over a shortened string. For example, the start anchor [code]^[/code] is not affected by [param offset], and the character before [param offset] will be checked for the word boundary [code]\b[/code]. </description> </method> <method name="search_all" qualifiers="const"> @@ -108,7 +109,8 @@ <param index="1" name="offset" type="int" default="0" /> <param index="2" name="end" type="int" default="-1" /> <description> - Searches the text for the compiled pattern. Returns an array of [RegExMatch] containers for each non-overlapping result. If no results were found, an empty array is returned instead. The region to search within can be specified without modifying where the start and end anchor would be. + Searches the text for the compiled pattern. Returns an array of [RegExMatch] containers for each non-overlapping result. If no results were found, an empty array is returned instead. + The region to search within can be specified with [param offset] and [param end]. This is useful when searching for another match in the same [param subject] by calling this method again after a previous success. Note that setting these parameters differs from passing over a shortened string. For example, the start anchor [code]^[/code] is not affected by [param offset], and the character before [param offset] will be checked for the word boundary [code]\b[/code]. </description> </method> <method name="sub" qualifiers="const"> @@ -119,7 +121,8 @@ <param index="3" name="offset" type="int" default="0" /> <param index="4" name="end" type="int" default="-1" /> <description> - Searches the text for the compiled pattern and replaces it with the specified string. Escapes and backreferences such as [code]$1[/code] and [code]$name[/code] are expanded and resolved. By default, only the first instance is replaced, but it can be changed for all instances (global replacement). The region to search within can be specified without modifying where the start and end anchor would be. + Searches the text for the compiled pattern and replaces it with the specified string. Escapes and backreferences such as [code]$1[/code] and [code]$name[/code] are expanded and resolved. By default, only the first instance is replaced, but it can be changed for all instances (global replacement). + The region to search within can be specified with [param offset] and [param end]. This is useful when searching for another match in the same [param subject] by calling this method again after a previous success. Note that setting these parameters differs from passing over a shortened string. For example, the start anchor [code]^[/code] is not affected by [param offset], and the character before [param offset] will be checked for the word boundary [code]\b[/code]. </description> </method> </methods> diff --git a/modules/squish/image_decompress_squish.cpp b/modules/squish/image_decompress_squish.cpp index 3a810e5259..2abd9a0c69 100644 --- a/modules/squish/image_decompress_squish.cpp +++ b/modules/squish/image_decompress_squish.cpp @@ -70,7 +70,7 @@ void image_decompress_squish(Image *p_image) { h >>= 1; } - p_image->create(p_image->get_width(), p_image->get_height(), p_image->has_mipmaps(), target_format, data); + p_image->set_data(p_image->get_width(), p_image->get_height(), p_image->has_mipmaps(), target_format, data); if (p_image->get_format() == Image::FORMAT_DXT5_RA_AS_RG) { p_image->convert_ra_rgba8_to_rg(); diff --git a/modules/svg/SCsub b/modules/svg/SCsub index 93262f4f87..ae3e1bdedb 100644 --- a/modules/svg/SCsub +++ b/modules/svg/SCsub @@ -11,6 +11,16 @@ thirdparty_obj = [] thirdparty_dir = "#thirdparty/thorvg/" thirdparty_sources = [ + "src/lib/sw_engine/tvgSwFill.cpp", + "src/lib/sw_engine/tvgSwImage.cpp", + "src/lib/sw_engine/tvgSwMath.cpp", + "src/lib/sw_engine/tvgSwMemPool.cpp", + "src/lib/sw_engine/tvgSwRaster.cpp", + "src/lib/sw_engine/tvgSwRenderer.cpp", + "src/lib/sw_engine/tvgSwRle.cpp", + "src/lib/sw_engine/tvgSwShape.cpp", + "src/lib/sw_engine/tvgSwStroke.cpp", + "src/lib/tvgAccessor.cpp", "src/lib/tvgBezier.cpp", "src/lib/tvgCanvas.cpp", "src/lib/tvgFill.cpp", @@ -28,27 +38,18 @@ thirdparty_sources = [ "src/lib/tvgShape.cpp", "src/lib/tvgSwCanvas.cpp", "src/lib/tvgTaskScheduler.cpp", + "src/loaders/external_png/tvgPngLoader.cpp", + "src/loaders/jpg/tvgJpgd.cpp", + "src/loaders/jpg/tvgJpgLoader.cpp", "src/loaders/raw/tvgRawLoader.cpp", - "src/loaders/svg/tvgXmlParser.cpp", - "src/loaders/svg/tvgSvgUtil.cpp", - "src/loaders/svg/tvgSvgSceneBuilder.cpp", - "src/loaders/svg/tvgSvgPath.cpp", - "src/loaders/svg/tvgSvgLoader.cpp", "src/loaders/svg/tvgSvgCssStyle.cpp", + "src/loaders/svg/tvgSvgLoader.cpp", + "src/loaders/svg/tvgSvgPath.cpp", + "src/loaders/svg/tvgSvgSceneBuilder.cpp", + "src/loaders/svg/tvgSvgUtil.cpp", + "src/loaders/svg/tvgXmlParser.cpp", "src/loaders/tvg/tvgTvgBinInterpreter.cpp", "src/loaders/tvg/tvgTvgLoader.cpp", - "src/loaders/jpg/tvgJpgLoader.cpp", - "src/loaders/jpg/tvgJpgd.cpp", - "src/loaders/external_png/tvgPngLoader.cpp", - "src/lib/sw_engine/tvgSwFill.cpp", - "src/lib/sw_engine/tvgSwImage.cpp", - "src/lib/sw_engine/tvgSwMath.cpp", - "src/lib/sw_engine/tvgSwMemPool.cpp", - "src/lib/sw_engine/tvgSwRaster.cpp", - "src/lib/sw_engine/tvgSwRenderer.cpp", - "src/lib/sw_engine/tvgSwRle.cpp", - "src/lib/sw_engine/tvgSwShape.cpp", - "src/lib/sw_engine/tvgSwStroke.cpp", "src/savers/tvg/tvgTvgSaver.cpp", ] @@ -62,14 +63,18 @@ env_thirdparty.Prepend( CPPPATH=[ thirdparty_dir + "src/lib", thirdparty_dir + "src/lib/sw_engine", + thirdparty_dir + "src/loaders/external_png", + thirdparty_dir + "src/loaders/jpg", thirdparty_dir + "src/loaders/raw", thirdparty_dir + "src/loaders/svg", - thirdparty_dir + "src/loaders/jpg", - thirdparty_dir + "src/loaders/png", thirdparty_dir + "src/loaders/tvg", thirdparty_dir + "src/savers/tvg", ] ) +# Also requires libpng headers +if env["builtin_libpng"]: + env_thirdparty.Prepend(CPPPATH=["#thirdparty/libpng"]) + env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources) env.modules_sources += thirdparty_obj diff --git a/modules/svg/image_loader_svg.cpp b/modules/svg/image_loader_svg.cpp index cd6081f91b..b8c412a201 100644 --- a/modules/svg/image_loader_svg.cpp +++ b/modules/svg/image_loader_svg.cpp @@ -135,14 +135,14 @@ void ImageLoaderSVG::create_image_from_string(Ref<Image> p_image, String p_strin res = sw_canvas->clear(true); memfree(buffer); - p_image->create(width, height, false, Image::FORMAT_RGBA8, image); + p_image->set_data(width, height, false, Image::FORMAT_RGBA8, image); } void ImageLoaderSVG::get_recognized_extensions(List<String> *p_extensions) const { p_extensions->push_back("svg"); } -Error ImageLoaderSVG::load_image(Ref<Image> p_image, Ref<FileAccess> p_fileaccess, uint32_t p_flags, float p_scale) { +Error ImageLoaderSVG::load_image(Ref<Image> p_image, Ref<FileAccess> p_fileaccess, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale) { String svg = p_fileaccess->get_as_utf8_string(); if (p_flags & FLAG_CONVERT_COLORS) { diff --git a/modules/svg/image_loader_svg.h b/modules/svg/image_loader_svg.h index e6f73ab18f..b0b0963c15 100644 --- a/modules/svg/image_loader_svg.h +++ b/modules/svg/image_loader_svg.h @@ -43,7 +43,7 @@ public: void create_image_from_string(Ref<Image> p_image, String p_string, float p_scale, bool p_upsample, const HashMap<Color, Color> &p_color_map); - virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> p_fileaccess, uint32_t p_flags, float p_scale) override; + virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> p_fileaccess, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale) override; virtual void get_recognized_extensions(List<String> *p_extensions) const override; }; diff --git a/modules/svg/register_types.cpp b/modules/svg/register_types.cpp index 5b4d1d31ca..323b1d652a 100644 --- a/modules/svg/register_types.cpp +++ b/modules/svg/register_types.cpp @@ -34,7 +34,7 @@ #include <thorvg.h> -static ImageLoaderSVG *image_loader_svg = nullptr; +static Ref<ImageLoaderSVG> image_loader_svg; void initialize_svg_module(ModuleInitializationLevel p_level) { if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) { @@ -45,7 +45,8 @@ void initialize_svg_module(ModuleInitializationLevel p_level) { if (tvg::Initializer::init(tvgEngine, 1) != tvg::Result::Success) { return; } - image_loader_svg = memnew(ImageLoaderSVG); + + image_loader_svg.instantiate(); ImageLoader::add_image_format_loader(image_loader_svg); } @@ -54,9 +55,12 @@ void uninitialize_svg_module(ModuleInitializationLevel p_level) { return; } - if (!image_loader_svg) { + if (image_loader_svg.is_null()) { + // It failed to initialize so it was not added. return; } - memdelete(image_loader_svg); + + ImageLoader::remove_image_format_loader(image_loader_svg); + image_loader_svg.unref(); tvg::Initializer::term(tvg::CanvasEngine::Sw); } diff --git a/modules/text_server_adv/SCsub b/modules/text_server_adv/SCsub index 8d0245f0f6..3c7a89b705 100644 --- a/modules/text_server_adv/SCsub +++ b/modules/text_server_adv/SCsub @@ -39,6 +39,9 @@ thirdparty_obj = [] freetype_enabled = "freetype" in env.module_list msdfgen_enabled = "msdfgen" in env.module_list +if "svg" in env.module_list: + env_text_server_adv.Prepend(CPPPATH=["#thirdparty/thorvg/inc", "#thirdparty/thorvg/src/lib"]) + if env["builtin_harfbuzz"]: env_harfbuzz = env_modules.Clone() env_harfbuzz.disable_warnings() @@ -131,9 +134,14 @@ if env["builtin_harfbuzz"]: env_harfbuzz.Append( CCFLAGS=[ "-DHAVE_FREETYPE", - "-DHAVE_GRAPHITE2", ] ) + if env["graphite"]: + env_harfbuzz.Append( + CCFLAGS=[ + "-DHAVE_GRAPHITE2", + ] + ) if env["builtin_freetype"]: env_harfbuzz.Prepend(CPPPATH=["#thirdparty/freetype/include"]) if env["builtin_graphite"] and env["graphite"]: @@ -215,6 +223,9 @@ if env["builtin_graphite"] and freetype_enabled and env["graphite"]: ] ) + if env.msvc: # Not our business to fix. + env_graphite.Append(CCFLAGS=["-D_SILENCE_ALL_CXX17_DEPRECATION_WARNINGS"]) + lib = env_graphite.add_library("graphite_builtin", thirdparty_sources) thirdparty_obj += lib @@ -443,9 +454,9 @@ if env["builtin_icu"]: ] thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] - icu_data_name = "icudt71l.dat" + icu_data_name = "icudt72l.dat" - if env_icu["tools"]: + if env.editor_build: 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) env_text_server_adv.Prepend(CPPPATH=["#thirdparty/icu4c/"]) @@ -479,7 +490,7 @@ if env["builtin_icu"]: "-DICU_DATA_NAME=" + icu_data_name, ] ) - if env_text_server_adv["tools"]: + if env.editor_build: env_text_server_adv.Append(CXXFLAGS=["-DICU_STATIC_DATA"]) env_text_server_adv.Prepend(CPPPATH=["#thirdparty/icu4c/common/", "#thirdparty/icu4c/i18n/"]) diff --git a/modules/text_server_adv/gdextension_build/SConstruct b/modules/text_server_adv/gdextension_build/SConstruct index 0170c007ae..4a363fdd7a 100644 --- a/modules/text_server_adv/gdextension_build/SConstruct +++ b/modules/text_server_adv/gdextension_build/SConstruct @@ -19,9 +19,11 @@ env = SConscript("./godot-cpp/SConstruct") env.__class__.disable_warnings = methods.disable_warnings opts = Variables([], ARGUMENTS) +opts.Add(BoolVariable("brotli_enabled", "Use Brotli library", True)) opts.Add(BoolVariable("freetype_enabled", "Use FreeType library", True)) opts.Add(BoolVariable("msdfgen_enabled", "Use MSDFgen library (require FreeType)", True)) opts.Add(BoolVariable("graphite_enabled", "Use Graphite library (require FreeType)", True)) +opts.Add(BoolVariable("thorvg_enabled", "Use ThorVG library (require FreeType)", True)) opts.Add(BoolVariable("static_icu_data", "Use built-in ICU data", True)) opts.Add(BoolVariable("verbose", "Enable verbose output for the compilation", False)) @@ -33,6 +35,79 @@ if not env["verbose"]: if env["platform"] == "windows" and not env["use_mingw"]: env.AppendUnique(CCFLAGS=["/utf-8"]) # Force to use Unicode encoding. +# ThorVG +if env["thorvg_enabled"] and env["freetype_enabled"]: + env_tvg = env.Clone() + env_tvg.disable_warnings() + + thirdparty_tvg_dir = "../../../thirdparty/thorvg/" + thirdparty_tvg_sources = [ + "src/lib/sw_engine/tvgSwFill.cpp", + "src/lib/sw_engine/tvgSwImage.cpp", + "src/lib/sw_engine/tvgSwMath.cpp", + "src/lib/sw_engine/tvgSwMemPool.cpp", + "src/lib/sw_engine/tvgSwRaster.cpp", + "src/lib/sw_engine/tvgSwRenderer.cpp", + "src/lib/sw_engine/tvgSwRle.cpp", + "src/lib/sw_engine/tvgSwShape.cpp", + "src/lib/sw_engine/tvgSwStroke.cpp", + "src/lib/tvgAccessor.cpp", + "src/lib/tvgBezier.cpp", + "src/lib/tvgCanvas.cpp", + "src/lib/tvgFill.cpp", + "src/lib/tvgGlCanvas.cpp", + "src/lib/tvgInitializer.cpp", + "src/lib/tvgLinearGradient.cpp", + "src/lib/tvgLoader.cpp", + "src/lib/tvgLzw.cpp", + "src/lib/tvgPaint.cpp", + "src/lib/tvgPicture.cpp", + "src/lib/tvgRadialGradient.cpp", + "src/lib/tvgRender.cpp", + "src/lib/tvgSaver.cpp", + "src/lib/tvgScene.cpp", + "src/lib/tvgShape.cpp", + "src/lib/tvgSwCanvas.cpp", + "src/lib/tvgTaskScheduler.cpp", + "src/loaders/external_png/tvgPngLoader.cpp", + "src/loaders/jpg/tvgJpgd.cpp", + "src/loaders/jpg/tvgJpgLoader.cpp", + "src/loaders/raw/tvgRawLoader.cpp", + "src/loaders/svg/tvgSvgCssStyle.cpp", + "src/loaders/svg/tvgSvgLoader.cpp", + "src/loaders/svg/tvgSvgPath.cpp", + "src/loaders/svg/tvgSvgSceneBuilder.cpp", + "src/loaders/svg/tvgSvgUtil.cpp", + "src/loaders/svg/tvgXmlParser.cpp", + "src/loaders/tvg/tvgTvgBinInterpreter.cpp", + "src/loaders/tvg/tvgTvgLoader.cpp", + "src/savers/tvg/tvgTvgSaver.cpp", + ] + thirdparty_tvg_sources = [thirdparty_tvg_dir + file for file in thirdparty_tvg_sources] + + env_tvg.Append( + CPPPATH=[ + "../../../thirdparty/thorvg/inc", + "../../../thirdparty/thorvg/src/lib", + "../../../thirdparty/thorvg/src/lib/sw_engine", + "../../../thirdparty/thorvg/src/loaders/external_png", + "../../../thirdparty/thorvg/src/loaders/jpg", + "../../../thirdparty/thorvg/src/loaders/raw", + "../../../thirdparty/thorvg/src/loaders/svg", + "../../../thirdparty/thorvg/src/loaders/tvg", + "../../../thirdparty/thorvg/src/savers/tvg", + "../../../thirdparty/libpng", + ] + ) + env.Append(CPPPATH=["../../../thirdparty/thorvg/inc", "../../../thirdparty/thorvg/src/lib"]) + env.Append(CPPDEFINES=["MODULE_SVG_ENABLED"]) + + lib = env_tvg.Library( + f'tvg_builtin{env["suffix"]}{env["LIBSUFFIX"]}', + thirdparty_tvg_sources, + ) + env.Append(LIBS=[lib]) + # MSDFGEN if env["msdfgen_enabled"] and env["freetype_enabled"]: env_msdfgen = env.Clone() @@ -67,7 +142,7 @@ if env["msdfgen_enabled"] and env["freetype_enabled"]: env.Append(CPPDEFINES=["MODULE_MSDFGEN_ENABLED"]) lib = env_msdfgen.Library( - f'msdfgen_builtin.{env["platform"]}.{env["target"]}.{env["arch_suffix"]}{env["LIBSUFFIX"]}', + f'msdfgen_builtin{env["suffix"]}{env["LIBSUFFIX"]}', thirdparty_msdfgen_sources, ) env.Append(LIBS=[lib]) @@ -162,6 +237,25 @@ if env["freetype_enabled"]: ] thirdparty_freetype_sources += [thirdparty_zlib_dir + file for file in thirdparty_zlib_sources] + if env["brotli_enabled"]: + thirdparty_brotli_dir = "../../../thirdparty/brotli/" + thirdparty_brotli_sources = [ + "common/constants.c", + "common/context.c", + "common/dictionary.c", + "common/platform.c", + "common/shared_dictionary.c", + "common/transform.c", + "dec/bit_reader.c", + "dec/decode.c", + "dec/huffman.c", + "dec/state.c", + ] + thirdparty_freetype_sources += [thirdparty_brotli_dir + file for file in thirdparty_brotli_sources] + env_freetype.Append(CPPDEFINES=["FT_CONFIG_OPTION_USE_BROTLI"]) + env_freetype.Prepend(CPPPATH=[thirdparty_brotli_dir + "include"]) + env.Append(CPPDEFINES=["FT_CONFIG_OPTION_USE_BROTLI"]) + env_freetype.Append(CPPPATH=[thirdparty_freetype_dir + "/include", thirdparty_zlib_dir, thirdparty_png_dir]) env.Append(CPPPATH=[thirdparty_freetype_dir + "/include"]) @@ -173,13 +267,13 @@ if env["freetype_enabled"]: "FT_CONFIG_OPTION_SYSTEM_ZLIB", ] ) - if env["target"] == "debug": + if env.dev_build: env_freetype.Append(CPPDEFINES=["ZLIB_DEBUG"]) env.Append(CPPDEFINES=["MODULE_FREETYPE_ENABLED"]) lib = env_freetype.Library( - f'freetype_builtin.{env["platform"]}.{env["target"]}.{env["arch_suffix"]}{env["LIBSUFFIX"]}', + f'freetype_builtin{env["suffix"]}{env["LIBSUFFIX"]}', thirdparty_freetype_sources, ) env.Append(LIBS=[lib]) @@ -265,6 +359,7 @@ env_harfbuzz.Append( CPPPATH=[ "../../../thirdparty/harfbuzz/src", "../../../thirdparty/icu4c/common/", + "../../../thirdparty/icu4c/i18n/", ] ) @@ -300,7 +395,7 @@ if env["freetype_enabled"]: env.Append(CPPPATH=["../../../thirdparty/harfbuzz/src"]) lib = env_harfbuzz.Library( - f'harfbuzz_builtin.{env["platform"]}.{env["target"]}.{env["arch_suffix"]}{env["LIBSUFFIX"]}', + f'harfbuzz_builtin{env["suffix"]}{env["LIBSUFFIX"]}', thirdparty_harfbuzz_sources, ) env.Prepend(LIBS=[lib]) @@ -360,7 +455,7 @@ if env["graphite_enabled"] and env["freetype_enabled"]: ) lib = env_graphite.Library( - f'graphite_builtin.{env["platform"]}.{env["target"]}.{env["arch_suffix"]}{env["LIBSUFFIX"]}', + f'graphite_builtin{env["suffix"]}{env["LIBSUFFIX"]}', thirdparty_graphite_sources, ) env.Append(LIBS=[lib]) @@ -569,10 +664,14 @@ thirdparty_icu_sources = [ "common/uvectr32.cpp", "common/uvectr64.cpp", "common/wintz.cpp", + "i18n/scriptset.cpp", + "i18n/ucln_in.cpp", + "i18n/uspoof.cpp", + "i18n/uspoof_impl.cpp", ] thirdparty_icu_sources = [thirdparty_icu_dir + file for file in thirdparty_icu_sources] -icu_data_name = "icudt71l.dat" +icu_data_name = "icudt72l.dat" if env["static_icu_data"]: env_icu.Depends("../../../thirdparty/icu4c/icudata.gen.h", "../../../thirdparty/icu4c/" + icu_data_name) @@ -584,7 +683,7 @@ if env["static_icu_data"]: else: thirdparty_sources += ["../icu_data/icudata_stub.cpp"] -env_icu.Append(CPPPATH=["../../../thirdparty/icu4c/common/"]) +env_icu.Append(CPPPATH=["../../../thirdparty/icu4c/common/", "../../../thirdparty/icu4c/i18n/"]) env_icu.Append( CXXFLAGS=[ "-DU_STATIC_IMPLEMENTATION", @@ -610,14 +709,12 @@ env.Append( "-DICU_DATA_NAME=" + icu_data_name, ] ) -env.Append(CPPPATH=["../../../thirdparty/icu4c/common/"]) +env.Append(CPPPATH=["../../../thirdparty/icu4c/common/", "../../../thirdparty/icu4c/i18n/"]) if env["platform"] == "windows": env.Append(LIBS=["advapi32"]) -lib = env_icu.Library( - f'icu_builtin.{env["platform"]}.{env["target"]}.{env["arch_suffix"]}{env["LIBSUFFIX"]}', thirdparty_icu_sources -) +lib = env_icu.Library(f'icu_builtin{env["suffix"]}{env["LIBSUFFIX"]}', thirdparty_icu_sources) env.Append(LIBS=[lib]) env.Append(CPPDEFINES=["GDEXTENSION"]) @@ -637,7 +734,7 @@ if env["platform"] == "macos": ) else: library = env.SharedLibrary( - f'./bin/libtextserver_advanced.{env["platform"]}.{env["target"]}.{env["arch_suffix"]}{env["SHLIBSUFFIX"]}', + f'./bin/libtextserver_advanced{env["suffix"]}{env["SHLIBSUFFIX"]}', source=sources, ) diff --git a/modules/text_server_adv/gdextension_build/text_server_adv.gdextension b/modules/text_server_adv/gdextension_build/text_server_adv.gdextension index 11ed271ae9..c12fcfdfdf 100644 --- a/modules/text_server_adv/gdextension_build/text_server_adv.gdextension +++ b/modules/text_server_adv/gdextension_build/text_server_adv.gdextension @@ -4,9 +4,21 @@ entry_symbol = "textserver_advanced_init" [libraries] -linux.64.debug = "bin/libtextserver_advanced.linux.debug.64.so" -linux.64.release = "bin/libtextserver_advanced.linux.release.64.so" -windows.64.debug = "bin/libtextserver_advanced.windows.debug.64.dll" -windows.64.release = "bin/libtextserver_advanced.windows.release.64.dll" -macos.debug = "bin/libtextserver_advanced.macos.debug.framework" -macos.release = "bin/libtextserver_advanced.macos.release.framework" +linux.x86_64.debug = "bin/libtextserver_advanced.linux.template_debug.x86_64.so" +linux.x86_64.release = "bin/libtextserver_advanced.linux.template_release.x86_64.so" +linux.x86_32.debug = "bin/libtextserver_advanced.linux.template_debug.x86_32.so" +linux.x86_32.release = "bin/libtextserver_advanced.linux.template_release.x86_32.so" +linux.arm64.debug = "bin/libtextserver_advanced.linux.template_debug.arm64.so" +linux.arm64.release = "bin/libtextserver_advanced.linux.template_release.arm64.so" +linux.rv64.debug = "bin/libtextserver_advanced.linux.template_debug.rv64.so" +linux.rv64.release = "bin/libtextserver_advanced.linux.template_release.rv64.so" + +windows.x86_64.debug = "bin/libtextserver_advanced.windows.template_debug.x86_64.dll" +windows.x86_64.release = "bin/libtextserver_advanced.windows.template_release.x86_64.dll" +windows.x86_32.debug = "bin/libtextserver_advanced.windows.template_debug.x86_32.dll" +windows.x86_32.release = "bin/libtextserver_advanced.windows.template_release.x86_32.dll" +windows.arm64.debug = "bin/libtextserver_advanced.windows.template_debug.arm64.dll" +windows.arm64.release = "bin/libtextserver_advanced.windows.template_release.arm64.dll" + +macos.debug = "bin/libtextserver_advanced.macos.template_debug.framework" +macos.release = "bin/libtextserver_advanced.macos.template_release.framework" diff --git a/modules/text_server_adv/text_server_adv.cpp b/modules/text_server_adv/text_server_adv.cpp index 7aebeafe70..166325c551 100644 --- a/modules/text_server_adv/text_server_adv.cpp +++ b/modules/text_server_adv/text_server_adv.cpp @@ -33,7 +33,7 @@ #ifdef GDEXTENSION // Headers for building as GDExtension plug-in. -#include <godot_cpp/classes/file.hpp> +#include <godot_cpp/classes/file_access.hpp> #include <godot_cpp/classes/project_settings.hpp> #include <godot_cpp/classes/rendering_server.hpp> #include <godot_cpp/classes/translation_server.hpp> @@ -41,19 +41,18 @@ using namespace godot; +#define GLOBAL_GET(m_var) ProjectSettings::get_singleton()->get(m_var) + #else // Headers for building as built-in module. #include "core/config/project_settings.h" -#include "core/core_bind.h" #include "core/error/error_macros.h" #include "core/object/worker_thread_pool.h" #include "core/string/print_string.h" #include "core/string/translation.h" -#include "modules/modules_enabled.gen.h" // For freetype, msdfgen. - -using namespace core_bind; +#include "modules/modules_enabled.gen.h" // For freetype, msdfgen, svg. #endif @@ -72,6 +71,10 @@ using namespace core_bind; #include "msdfgen.h" #endif +#ifdef MODULE_SVG_ENABLED +#include "thorvg_svg_in_ot.h" +#endif + /*************************************************************************/ /* bmp_font_t HarfBuzz Bitmap font interface */ /*************************************************************************/ @@ -330,7 +333,7 @@ _FORCE_INLINE_ bool is_connected_to_prev(char32_t p_chr, char32_t p_pchr) { /*************************************************************************/ -bool TextServerAdvanced::has_feature(Feature p_feature) const { +bool TextServerAdvanced::_has_feature(Feature p_feature) const { switch (p_feature) { case FEATURE_SIMPLE_LAYOUT: case FEATURE_BIDI_LAYOUT: @@ -357,7 +360,7 @@ bool TextServerAdvanced::has_feature(Feature p_feature) const { return false; } -String TextServerAdvanced::get_name() const { +String TextServerAdvanced::_get_name() const { #ifdef GDEXTENSION return "ICU / HarfBuzz / Graphite (GDExtension)"; #else @@ -365,7 +368,7 @@ String TextServerAdvanced::get_name() const { #endif } -int64_t TextServerAdvanced::get_features() const { +int64_t TextServerAdvanced::_get_features() const { int64_t interface_features = FEATURE_SIMPLE_LAYOUT | FEATURE_BIDI_LAYOUT | FEATURE_VERTICAL_LAYOUT | FEATURE_SHAPING | FEATURE_KASHIDA_JUSTIFICATION | FEATURE_BREAK_ITERATORS | FEATURE_FONT_BITMAP | FEATURE_FONT_VARIABLE | FEATURE_CONTEXT_SENSITIVE_CASE_CONVERSION | FEATURE_USE_SUPPORT_DATA; #ifdef MODULE_FREETYPE_ENABLED interface_features |= FEATURE_FONT_DYNAMIC; @@ -377,7 +380,7 @@ int64_t TextServerAdvanced::get_features() const { return interface_features; } -void TextServerAdvanced::free_rid(const RID &p_rid) { +void TextServerAdvanced::_free_rid(const RID &p_rid) { _THREAD_SAFE_METHOD_ if (font_owner.owns(p_rid)) { FontAdvanced *fd = font_owner.get_or_null(p_rid); @@ -390,12 +393,12 @@ void TextServerAdvanced::free_rid(const RID &p_rid) { } } -bool TextServerAdvanced::has(const RID &p_rid) { +bool TextServerAdvanced::_has(const 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) { +bool TextServerAdvanced::_load_support_data(const String &p_filename) { _THREAD_SAFE_METHOD_ #ifdef ICU_STATIC_DATA @@ -408,13 +411,16 @@ bool TextServerAdvanced::load_support_data(const String &p_filename) { if (!icu_data_loaded) { String filename = (p_filename.is_empty()) ? String("res://") + _MKSTR(ICU_DATA_NAME) : p_filename; - Ref<File> f; - f.instantiate(); - if (f->open(filename, File::READ) != OK) { + Ref<FileAccess> f = FileAccess::open(filename, FileAccess::READ); + if (f.is_null()) { return false; } uint64_t len = f->get_length(); +#ifdef GDEXTENSION PackedByteArray icu_data = f->get_buffer(len); +#else + PackedByteArray icu_data = f->_get_buffer(len); +#endif UErrorCode err = U_ZERO_ERROR; udata_setCommonData(icu_data.ptr(), &err); @@ -433,7 +439,7 @@ bool TextServerAdvanced::load_support_data(const String &p_filename) { return true; } -String TextServerAdvanced::get_support_data_filename() const { +String TextServerAdvanced::_get_support_data_filename() const { #ifdef ICU_STATIC_DATA return _MKSTR(ICU_DATA_NAME); #else @@ -441,7 +447,7 @@ String TextServerAdvanced::get_support_data_filename() const { #endif } -String TextServerAdvanced::get_support_data_info() const { +String TextServerAdvanced::_get_support_data_info() const { #ifdef ICU_STATIC_DATA return String("ICU break iteration data (") + _MKSTR(ICU_DATA_NAME) + String(")."); #else @@ -449,22 +455,25 @@ String TextServerAdvanced::get_support_data_info() const { #endif } -bool TextServerAdvanced::save_support_data(const String &p_filename) const { +bool TextServerAdvanced::_save_support_data(const String &p_filename) const { _THREAD_SAFE_METHOD_ #ifdef ICU_STATIC_DATA // Store data to the res file if it's available. - Ref<File> f; - f.instantiate(); - if (f->open(p_filename, File::WRITE) != OK) { + Ref<FileAccess> f = FileAccess::open(p_filename, FileAccess::WRITE); + if (f.is_null()) { return false; } PackedByteArray icu_data; icu_data.resize(U_ICUDATA_SIZE); memcpy(icu_data.ptrw(), U_ICUDATA_ENTRY_POINT, U_ICUDATA_SIZE); +#ifdef GDEXTENSION f->store_buffer(icu_data); +#else + f->_store_buffer(icu_data); +#endif return true; #else @@ -472,7 +481,7 @@ bool TextServerAdvanced::save_support_data(const String &p_filename) const { #endif } -bool TextServerAdvanced::is_locale_right_to_left(const String &p_locale) const { +bool TextServerAdvanced::_is_locale_right_to_left(const String &p_locale) const { String l = p_locale.get_slicec('_', 0); if ((l == "ar") || (l == "dv") || (l == "he") || (l == "fa") || (l == "ff") || (l == "ku") || (l == "ur")) { return true; @@ -744,7 +753,7 @@ void TextServerAdvanced::_insert_feature_sets() { _insert_feature("weight", HB_TAG('w', 'g', 'h', 't'), Variant::Type::INT, false); } -int64_t TextServerAdvanced::name_to_tag(const String &p_name) const { +int64_t TextServerAdvanced::_name_to_tag(const String &p_name) const { if (feature_sets.has(p_name)) { return feature_sets[p_name]; } @@ -767,7 +776,7 @@ bool TextServerAdvanced::_get_tag_hidden(int64_t p_tag) const { return false; } -String TextServerAdvanced::tag_to_name(int64_t p_tag) const { +String TextServerAdvanced::_tag_to_name(int64_t p_tag) const { if (feature_sets_inv.has(p_tag)) { return feature_sets_inv[p_tag].name; } @@ -785,58 +794,27 @@ String TextServerAdvanced::tag_to_name(int64_t p_tag) const { _FORCE_INLINE_ TextServerAdvanced::FontTexturePosition TextServerAdvanced::find_texture_pos_for_glyph(FontForSizeAdvanced *p_data, int p_color_size, Image::Format p_image_format, int p_width, int p_height, bool p_msdf) const { FontTexturePosition ret; - ret.index = -1; int mw = p_width; int mh = p_height; - for (int i = 0; i < p_data->textures.size(); i++) { - const FontTexture &ct = p_data->textures[i]; - - if (p_image_format != ct.format) { + ShelfPackTexture *ct = p_data->textures.ptrw(); + for (int32_t i = 0; i < p_data->textures.size(); i++) { + if (p_image_format != ct[i].format) { continue; } - - if (mw > ct.texture_w || mh > ct.texture_h) { // Too big for this texture. + if (mw > ct[i].texture_w || mh > ct[i].texture_h) { // Too big for this texture. continue; } - if (ct.offsets.size() < ct.texture_w) { - continue; - } - - ret.y = 0x7fffffff; - ret.x = 0; - - for (int j = 0; j < ct.texture_w - 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_h) { - continue; // Fail, could not fit it here. + ret = ct[i].pack_rect(i, mh, mw); + if (ret.index != -1) { + break; } - - 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.x * p_data->oversampling * 8, 256); #ifdef GDEXTENSION @@ -864,12 +842,9 @@ _FORCE_INLINE_ TextServerAdvanced::FontTexturePosition TextServerAdvanced::find_ #endif } - FontTexture tex; - tex.texture_w = texsize; - tex.texture_h = texsize; + ShelfPackTexture tex = ShelfPackTexture(texsize, texsize); tex.format = p_image_format; tex.imgdata.resize(texsize * texsize * p_color_size); - { // Zero texture. uint8_t *w = tex.imgdata.ptrw(); @@ -892,14 +867,10 @@ _FORCE_INLINE_ TextServerAdvanced::FontTexturePosition TextServerAdvanced::find_ ERR_FAIL_V(ret); } } - tex.offsets.resize(texsize); - int32_t *offw = tex.offsets.ptrw(); - for (int i = 0; i < texsize; i++) { // Zero offsets. - offw[i] = 0; - } - p_data->textures.push_back(tex); - ret.index = p_data->textures.size() - 1; + + int32_t idx = p_data->textures.size() - 1; + ret = p_data->textures.write[idx].pack_rect(idx, mh, mw); } return ret; @@ -1033,7 +1004,7 @@ _FORCE_INLINE_ TextServerAdvanced::FontGlyph TextServerAdvanced::rasterize_msdf( FontTexturePosition tex_pos = find_texture_pos_for_glyph(p_data, 4, Image::FORMAT_RGBA8, mw, mh, true); ERR_FAIL_COND_V(tex_pos.index < 0, FontGlyph()); - FontTexture &tex = p_data->textures.write[tex_pos.index]; + ShelfPackTexture &tex = p_data->textures.write[tex_pos.index]; edgeColoringSimple(shape, 3.0); // Max. angle. msdfgen::Bitmap<float, 4> image(w, h); // Texture size. @@ -1048,8 +1019,14 @@ _FORCE_INLINE_ TextServerAdvanced::FontGlyph TextServerAdvanced::rasterize_msdf( td.projection = &projection; td.distancePixelConversion = &distancePixelConversion; +#ifdef GDEXTENSION + for (int i = 0; i < h; i++) { + _generateMTSDF_threaded(i, &td); + } +#else WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &TextServerAdvanced::_generateMTSDF_threaded, &td, h, -1, true, SNAME("FontServerRasterizeMSDF")); WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task); +#endif msdfgen::msdfErrorCorrection(image, shape, projection, p_pixel_range, config); @@ -1070,12 +1047,6 @@ _FORCE_INLINE_ TextServerAdvanced::FontGlyph TextServerAdvanced::rasterize_msdf( tex.dirty = true; - // Update height array. - int32_t *offw = tex.offsets.ptrw(); - for (int k = tex_pos.x; k < tex_pos.x + mw; k++) { - offw[k] = tex_pos.y + mh; - } - chr.texture_idx = tex_pos.index; chr.uv_rect = Rect2(tex_pos.x + p_rect_margin, tex_pos.y + p_rect_margin, w + p_rect_margin * 2, h + p_rect_margin * 2); @@ -1123,8 +1094,7 @@ _FORCE_INLINE_ TextServerAdvanced::FontGlyph TextServerAdvanced::rasterize_bitma ERR_FAIL_COND_V(tex_pos.index < 0, FontGlyph()); // Fit character in char texture. - - FontTexture &tex = p_data->textures.write[tex_pos.index]; + ShelfPackTexture &tex = p_data->textures.write[tex_pos.index]; { uint8_t *wr = tex.imgdata.ptrw(); @@ -1189,12 +1159,6 @@ _FORCE_INLINE_ TextServerAdvanced::FontGlyph TextServerAdvanced::rasterize_bitma tex.dirty = true; - // Update height array. - int32_t *offw = tex.offsets.ptrw(); - for (int k = tex_pos.x; k < tex_pos.x + mw; k++) { - offw[k] = tex_pos.y + mh; - } - FontGlyph chr; chr.advance = advance * p_data->scale / p_data->oversampling; chr.texture_idx = tex_pos.index; @@ -1384,7 +1348,13 @@ _FORCE_INLINE_ bool TextServerAdvanced::_ensure_cache_for_size(FontAdvanced *p_f int error = 0; if (!ft_library) { error = FT_Init_FreeType(&ft_library); - ERR_FAIL_COND_V_MSG(error != 0, false, "FreeType: Error initializing library: '" + String(FT_Error_String(error)) + "'."); + if (error != 0) { + memdelete(fd); + ERR_FAIL_V_MSG(false, "FreeType: Error initializing library: '" + String(FT_Error_String(error)) + "'."); + } +#ifdef MODULE_SVG_ENABLED + FT_Property_Set(ft_library, "ot-svg", "svg-hooks", get_tvg_svg_in_ot_hooks()); +#endif } memset(&fd->stream, 0, sizeof(FT_StreamRec)); @@ -1413,6 +1383,7 @@ _FORCE_INLINE_ bool TextServerAdvanced::_ensure_cache_for_size(FontAdvanced *p_f if (error) { FT_Done_Face(fd->face); fd->face = nullptr; + memdelete(fd); ERR_FAIL_V_MSG(false, "FreeType: Error loading font: '" + String(FT_Error_String(error)) + "'."); } @@ -1420,7 +1391,7 @@ _FORCE_INLINE_ bool TextServerAdvanced::_ensure_cache_for_size(FontAdvanced *p_f fd->oversampling = 1.0; fd->size.x = p_font_data->msdf_source_size; } else if (p_font_data->oversampling <= 0.0) { - fd->oversampling = font_get_global_oversampling(); + fd->oversampling = _font_get_global_oversampling(); } else { fd->oversampling = p_font_data->oversampling; } @@ -1813,8 +1784,8 @@ _FORCE_INLINE_ bool TextServerAdvanced::_ensure_cache_for_size(FontAdvanced *p_f coords.write[i] = CLAMP(var.value * 65536.0, amaster->axis[i].minimum, amaster->axis[i].maximum); } - if (p_font_data->variation_coordinates.has(tag_to_name(var.tag))) { - var.value = p_font_data->variation_coordinates[tag_to_name(var.tag)]; + if (p_font_data->variation_coordinates.has(_tag_to_name(var.tag))) { + var.value = p_font_data->variation_coordinates[_tag_to_name(var.tag)]; coords.write[i] = CLAMP(var.value * 65536.0, amaster->axis[i].minimum, amaster->axis[i].maximum); } @@ -1826,6 +1797,7 @@ _FORCE_INLINE_ bool TextServerAdvanced::_ensure_cache_for_size(FontAdvanced *p_f FT_Done_MM_Var(ft_library, amaster); } #else + memdelete(fd); ERR_FAIL_V_MSG(false, "FreeType: Can't load dynamic font, engine is compiled without FreeType support!"); #endif } else { @@ -1859,7 +1831,7 @@ hb_font_t *TextServerAdvanced::_font_get_hb_handle(const RID &p_font_rid, int64_ return fd->cache[size]->hb_handle; } -RID TextServerAdvanced::create_font() { +RID TextServerAdvanced::_create_font() { _THREAD_SAFE_METHOD_ FontAdvanced *fd = memnew(FontAdvanced); @@ -1867,7 +1839,7 @@ RID TextServerAdvanced::create_font() { return font_owner.make_rid(fd); } -void TextServerAdvanced::font_set_data(const RID &p_font_rid, const PackedByteArray &p_data) { +void TextServerAdvanced::_font_set_data(const RID &p_font_rid, const PackedByteArray &p_data) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1878,7 +1850,7 @@ void TextServerAdvanced::font_set_data(const RID &p_font_rid, const PackedByteAr fd->data_size = fd->data.size(); } -void TextServerAdvanced::font_set_data_ptr(const RID &p_font_rid, const uint8_t *p_data_ptr, int64_t p_data_size) { +void TextServerAdvanced::_font_set_data_ptr(const RID &p_font_rid, const uint8_t *p_data_ptr, int64_t p_data_size) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1889,7 +1861,7 @@ void TextServerAdvanced::font_set_data_ptr(const RID &p_font_rid, const uint8_t fd->data_size = p_data_size; } -void TextServerAdvanced::font_set_face_index(const RID &p_font_rid, int64_t p_face_index) { +void TextServerAdvanced::_font_set_face_index(const RID &p_font_rid, int64_t p_face_index) { ERR_FAIL_COND(p_face_index < 0); ERR_FAIL_COND(p_face_index >= 0x7FFF); @@ -1903,7 +1875,7 @@ void TextServerAdvanced::font_set_face_index(const RID &p_font_rid, int64_t p_fa } } -int64_t TextServerAdvanced::font_get_face_index(const RID &p_font_rid) const { +int64_t TextServerAdvanced::_font_get_face_index(const RID &p_font_rid) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, 0); @@ -1911,7 +1883,7 @@ int64_t TextServerAdvanced::font_get_face_index(const RID &p_font_rid) const { return fd->face_index; } -int64_t TextServerAdvanced::font_get_face_count(const RID &p_font_rid) const { +int64_t TextServerAdvanced::_font_get_face_count(const RID &p_font_rid) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, 0); @@ -1925,6 +1897,9 @@ int64_t TextServerAdvanced::font_get_face_count(const RID &p_font_rid) const { if (!ft_library) { error = FT_Init_FreeType(&ft_library); ERR_FAIL_COND_V_MSG(error != 0, false, "FreeType: Error initializing library: '" + String(FT_Error_String(error)) + "'."); +#ifdef MODULE_SVG_ENABLED + FT_Property_Set(ft_library, "ot-svg", "svg-hooks", get_tvg_svg_in_ot_hooks()); +#endif } FT_StreamRec stream; @@ -1940,19 +1915,19 @@ int64_t TextServerAdvanced::font_get_face_count(const RID &p_font_rid) const { fargs.flags = FT_OPEN_MEMORY; fargs.stream = &stream; - FT_Face tmp_face; + FT_Face tmp_face = nullptr; error = FT_Open_Face(ft_library, &fargs, -1, &tmp_face); if (error == 0) { face_count = tmp_face->num_faces; + FT_Done_Face(tmp_face); } - FT_Done_Face(tmp_face); #endif } return face_count; } -void TextServerAdvanced::font_set_style(const RID &p_font_rid, BitField<FontStyle> p_style) { +void TextServerAdvanced::_font_set_style(const RID &p_font_rid, BitField<FontStyle> p_style) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1962,7 +1937,7 @@ void TextServerAdvanced::font_set_style(const RID &p_font_rid, BitField<FontStyl fd->style_flags = p_style; } -BitField<TextServer::FontStyle> TextServerAdvanced::font_get_style(const RID &p_font_rid) const { +BitField<TextServer::FontStyle> TextServerAdvanced::_font_get_style(const RID &p_font_rid) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, 0); @@ -1972,7 +1947,7 @@ BitField<TextServer::FontStyle> TextServerAdvanced::font_get_style(const RID &p_ return fd->style_flags; } -void TextServerAdvanced::font_set_style_name(const RID &p_font_rid, const String &p_name) { +void TextServerAdvanced::_font_set_style_name(const RID &p_font_rid, const String &p_name) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1982,7 +1957,7 @@ void TextServerAdvanced::font_set_style_name(const RID &p_font_rid, const String fd->style_name = p_name; } -String TextServerAdvanced::font_get_style_name(const RID &p_font_rid) const { +String TextServerAdvanced::_font_get_style_name(const RID &p_font_rid) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, String()); @@ -1992,7 +1967,7 @@ String TextServerAdvanced::font_get_style_name(const RID &p_font_rid) const { return fd->style_name; } -void TextServerAdvanced::font_set_name(const RID &p_font_rid, const String &p_name) { +void TextServerAdvanced::_font_set_name(const RID &p_font_rid, const String &p_name) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2002,7 +1977,7 @@ void TextServerAdvanced::font_set_name(const RID &p_font_rid, const String &p_na fd->font_name = p_name; } -String TextServerAdvanced::font_get_name(const RID &p_font_rid) const { +String TextServerAdvanced::_font_get_name(const RID &p_font_rid) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, String()); @@ -2012,7 +1987,7 @@ String TextServerAdvanced::font_get_name(const RID &p_font_rid) const { return fd->font_name; } -void TextServerAdvanced::font_set_antialiasing(RID p_font_rid, TextServer::FontAntialiasing p_antialiasing) { +void TextServerAdvanced::_font_set_antialiasing(const RID &p_font_rid, TextServer::FontAntialiasing p_antialiasing) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2023,7 +1998,7 @@ void TextServerAdvanced::font_set_antialiasing(RID p_font_rid, TextServer::FontA } } -TextServer::FontAntialiasing TextServerAdvanced::font_get_antialiasing(RID p_font_rid) const { +TextServer::FontAntialiasing TextServerAdvanced::_font_get_antialiasing(const RID &p_font_rid) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, TextServer::FONT_ANTIALIASING_NONE); @@ -2031,7 +2006,7 @@ TextServer::FontAntialiasing TextServerAdvanced::font_get_antialiasing(RID p_fon return fd->antialiasing; } -void TextServerAdvanced::font_set_generate_mipmaps(const RID &p_font_rid, bool p_generate_mipmaps) { +void TextServerAdvanced::_font_set_generate_mipmaps(const RID &p_font_rid, bool p_generate_mipmaps) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2040,13 +2015,14 @@ void TextServerAdvanced::font_set_generate_mipmaps(const RID &p_font_rid, bool p for (KeyValue<Vector2i, FontForSizeAdvanced *> &E : fd->cache) { for (int i = 0; i < E.value->textures.size(); i++) { E.value->textures.write[i].dirty = true; + E.value->textures.write[i].texture = Ref<ImageTexture>(); } } fd->mipmaps = p_generate_mipmaps; } } -bool TextServerAdvanced::font_get_generate_mipmaps(const RID &p_font_rid) const { +bool TextServerAdvanced::_font_get_generate_mipmaps(const RID &p_font_rid) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, false); @@ -2054,7 +2030,7 @@ bool TextServerAdvanced::font_get_generate_mipmaps(const RID &p_font_rid) const return fd->mipmaps; } -void TextServerAdvanced::font_set_multichannel_signed_distance_field(const RID &p_font_rid, bool p_msdf) { +void TextServerAdvanced::_font_set_multichannel_signed_distance_field(const RID &p_font_rid, bool p_msdf) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2065,7 +2041,7 @@ void TextServerAdvanced::font_set_multichannel_signed_distance_field(const RID & } } -bool TextServerAdvanced::font_is_multichannel_signed_distance_field(const RID &p_font_rid) const { +bool TextServerAdvanced::_font_is_multichannel_signed_distance_field(const RID &p_font_rid) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, false); @@ -2073,7 +2049,7 @@ bool TextServerAdvanced::font_is_multichannel_signed_distance_field(const RID &p return fd->msdf; } -void TextServerAdvanced::font_set_msdf_pixel_range(const RID &p_font_rid, int64_t p_msdf_pixel_range) { +void TextServerAdvanced::_font_set_msdf_pixel_range(const RID &p_font_rid, int64_t p_msdf_pixel_range) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2084,7 +2060,7 @@ void TextServerAdvanced::font_set_msdf_pixel_range(const RID &p_font_rid, int64_ } } -int64_t TextServerAdvanced::font_get_msdf_pixel_range(const RID &p_font_rid) const { +int64_t TextServerAdvanced::_font_get_msdf_pixel_range(const RID &p_font_rid) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, false); @@ -2092,7 +2068,7 @@ int64_t TextServerAdvanced::font_get_msdf_pixel_range(const RID &p_font_rid) con return fd->msdf_range; } -void TextServerAdvanced::font_set_msdf_size(const RID &p_font_rid, int64_t p_msdf_size) { +void TextServerAdvanced::_font_set_msdf_size(const RID &p_font_rid, int64_t p_msdf_size) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2103,7 +2079,7 @@ void TextServerAdvanced::font_set_msdf_size(const RID &p_font_rid, int64_t p_msd } } -int64_t TextServerAdvanced::font_get_msdf_size(const RID &p_font_rid) const { +int64_t TextServerAdvanced::_font_get_msdf_size(const RID &p_font_rid) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, false); @@ -2111,7 +2087,7 @@ int64_t TextServerAdvanced::font_get_msdf_size(const RID &p_font_rid) const { return fd->msdf_source_size; } -void TextServerAdvanced::font_set_fixed_size(const RID &p_font_rid, int64_t p_fixed_size) { +void TextServerAdvanced::_font_set_fixed_size(const RID &p_font_rid, int64_t p_fixed_size) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2119,7 +2095,7 @@ void TextServerAdvanced::font_set_fixed_size(const RID &p_font_rid, int64_t p_fi fd->fixed_size = p_fixed_size; } -int64_t TextServerAdvanced::font_get_fixed_size(const RID &p_font_rid) const { +int64_t TextServerAdvanced::_font_get_fixed_size(const RID &p_font_rid) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, false); @@ -2127,7 +2103,7 @@ int64_t TextServerAdvanced::font_get_fixed_size(const RID &p_font_rid) const { return fd->fixed_size; } -void TextServerAdvanced::font_set_force_autohinter(const RID &p_font_rid, bool p_force_autohinter) { +void TextServerAdvanced::_font_set_force_autohinter(const RID &p_font_rid, bool p_force_autohinter) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2138,7 +2114,7 @@ void TextServerAdvanced::font_set_force_autohinter(const RID &p_font_rid, bool p } } -bool TextServerAdvanced::font_is_force_autohinter(const RID &p_font_rid) const { +bool TextServerAdvanced::_font_is_force_autohinter(const RID &p_font_rid) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, false); @@ -2146,7 +2122,7 @@ bool TextServerAdvanced::font_is_force_autohinter(const RID &p_font_rid) const { return fd->force_autohinter; } -void TextServerAdvanced::font_set_hinting(const RID &p_font_rid, TextServer::Hinting p_hinting) { +void TextServerAdvanced::_font_set_hinting(const RID &p_font_rid, TextServer::Hinting p_hinting) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2157,7 +2133,7 @@ void TextServerAdvanced::font_set_hinting(const RID &p_font_rid, TextServer::Hin } } -TextServer::Hinting TextServerAdvanced::font_get_hinting(const RID &p_font_rid) const { +TextServer::Hinting TextServerAdvanced::_font_get_hinting(const RID &p_font_rid) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, HINTING_NONE); @@ -2165,7 +2141,7 @@ TextServer::Hinting TextServerAdvanced::font_get_hinting(const RID &p_font_rid) return fd->hinting; } -void TextServerAdvanced::font_set_subpixel_positioning(const RID &p_font_rid, TextServer::SubpixelPositioning p_subpixel) { +void TextServerAdvanced::_font_set_subpixel_positioning(const RID &p_font_rid, TextServer::SubpixelPositioning p_subpixel) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2173,7 +2149,7 @@ void TextServerAdvanced::font_set_subpixel_positioning(const RID &p_font_rid, Te fd->subpixel_positioning = p_subpixel; } -TextServer::SubpixelPositioning TextServerAdvanced::font_get_subpixel_positioning(const RID &p_font_rid) const { +TextServer::SubpixelPositioning TextServerAdvanced::_font_get_subpixel_positioning(const RID &p_font_rid) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, SUBPIXEL_POSITIONING_DISABLED); @@ -2181,7 +2157,7 @@ TextServer::SubpixelPositioning TextServerAdvanced::font_get_subpixel_positionin return fd->subpixel_positioning; } -void TextServerAdvanced::font_set_embolden(const RID &p_font_rid, double p_strength) { +void TextServerAdvanced::_font_set_embolden(const RID &p_font_rid, double p_strength) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2192,7 +2168,7 @@ void TextServerAdvanced::font_set_embolden(const RID &p_font_rid, double p_stren } } -double TextServerAdvanced::font_get_embolden(const RID &p_font_rid) const { +double TextServerAdvanced::_font_get_embolden(const RID &p_font_rid) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, 0.0); @@ -2200,7 +2176,7 @@ double TextServerAdvanced::font_get_embolden(const RID &p_font_rid) const { return fd->embolden; } -void TextServerAdvanced::font_set_transform(const RID &p_font_rid, const Transform2D &p_transform) { +void TextServerAdvanced::_font_set_transform(const RID &p_font_rid, const Transform2D &p_transform) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2211,7 +2187,7 @@ void TextServerAdvanced::font_set_transform(const RID &p_font_rid, const Transfo } } -Transform2D TextServerAdvanced::font_get_transform(const RID &p_font_rid) const { +Transform2D TextServerAdvanced::_font_get_transform(const RID &p_font_rid) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Transform2D()); @@ -2219,7 +2195,7 @@ Transform2D TextServerAdvanced::font_get_transform(const RID &p_font_rid) const return fd->transform; } -void TextServerAdvanced::font_set_variation_coordinates(const RID &p_font_rid, const Dictionary &p_variation_coordinates) { +void TextServerAdvanced::_font_set_variation_coordinates(const RID &p_font_rid, const Dictionary &p_variation_coordinates) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2230,7 +2206,7 @@ void TextServerAdvanced::font_set_variation_coordinates(const RID &p_font_rid, c } } -Dictionary TextServerAdvanced::font_get_variation_coordinates(const RID &p_font_rid) const { +Dictionary TextServerAdvanced::_font_get_variation_coordinates(const RID &p_font_rid) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Dictionary()); @@ -2238,7 +2214,7 @@ Dictionary TextServerAdvanced::font_get_variation_coordinates(const RID &p_font_ return fd->variation_coordinates; } -void TextServerAdvanced::font_set_oversampling(const RID &p_font_rid, double p_oversampling) { +void TextServerAdvanced::_font_set_oversampling(const RID &p_font_rid, double p_oversampling) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2249,7 +2225,7 @@ void TextServerAdvanced::font_set_oversampling(const RID &p_font_rid, double p_o } } -double TextServerAdvanced::font_get_oversampling(const RID &p_font_rid) const { +double TextServerAdvanced::_font_get_oversampling(const RID &p_font_rid) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, 0.0); @@ -2257,7 +2233,7 @@ double TextServerAdvanced::font_get_oversampling(const RID &p_font_rid) const { return fd->oversampling; } -TypedArray<Vector2i> TextServerAdvanced::font_get_size_cache_list(const RID &p_font_rid) const { +TypedArray<Vector2i> TextServerAdvanced::_font_get_size_cache_list(const RID &p_font_rid) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, TypedArray<Vector2i>()); @@ -2269,7 +2245,7 @@ TypedArray<Vector2i> TextServerAdvanced::font_get_size_cache_list(const RID &p_f return ret; } -void TextServerAdvanced::font_clear_size_cache(const RID &p_font_rid) { +void TextServerAdvanced::_font_clear_size_cache(const RID &p_font_rid) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2280,7 +2256,7 @@ void TextServerAdvanced::font_clear_size_cache(const RID &p_font_rid) { fd->cache.clear(); } -void TextServerAdvanced::font_remove_size_cache(const RID &p_font_rid, const Vector2i &p_size) { +void TextServerAdvanced::_font_remove_size_cache(const RID &p_font_rid, const Vector2i &p_size) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2291,7 +2267,7 @@ void TextServerAdvanced::font_remove_size_cache(const RID &p_font_rid, const Vec } } -void TextServerAdvanced::font_set_ascent(const RID &p_font_rid, int64_t p_size, double p_ascent) { +void TextServerAdvanced::_font_set_ascent(const RID &p_font_rid, int64_t p_size, double p_ascent) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2302,7 +2278,7 @@ void TextServerAdvanced::font_set_ascent(const RID &p_font_rid, int64_t p_size, fd->cache[size]->ascent = p_ascent; } -double TextServerAdvanced::font_get_ascent(const RID &p_font_rid, int64_t p_size) const { +double TextServerAdvanced::_font_get_ascent(const RID &p_font_rid, int64_t p_size) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, 0.0); @@ -2318,7 +2294,7 @@ double TextServerAdvanced::font_get_ascent(const RID &p_font_rid, int64_t p_size } } -void TextServerAdvanced::font_set_descent(const RID &p_font_rid, int64_t p_size, double p_descent) { +void TextServerAdvanced::_font_set_descent(const RID &p_font_rid, int64_t p_size, double p_descent) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2328,7 +2304,7 @@ void TextServerAdvanced::font_set_descent(const RID &p_font_rid, int64_t p_size, fd->cache[size]->descent = p_descent; } -double TextServerAdvanced::font_get_descent(const RID &p_font_rid, int64_t p_size) const { +double TextServerAdvanced::_font_get_descent(const RID &p_font_rid, int64_t p_size) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, 0.0); @@ -2344,7 +2320,7 @@ double TextServerAdvanced::font_get_descent(const RID &p_font_rid, int64_t p_siz } } -void TextServerAdvanced::font_set_underline_position(const RID &p_font_rid, int64_t p_size, double p_underline_position) { +void TextServerAdvanced::_font_set_underline_position(const RID &p_font_rid, int64_t p_size, double p_underline_position) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2355,7 +2331,7 @@ void TextServerAdvanced::font_set_underline_position(const RID &p_font_rid, int6 fd->cache[size]->underline_position = p_underline_position; } -double TextServerAdvanced::font_get_underline_position(const RID &p_font_rid, int64_t p_size) const { +double TextServerAdvanced::_font_get_underline_position(const RID &p_font_rid, int64_t p_size) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, 0.0); @@ -2371,7 +2347,7 @@ double TextServerAdvanced::font_get_underline_position(const RID &p_font_rid, in } } -void TextServerAdvanced::font_set_underline_thickness(const RID &p_font_rid, int64_t p_size, double p_underline_thickness) { +void TextServerAdvanced::_font_set_underline_thickness(const RID &p_font_rid, int64_t p_size, double p_underline_thickness) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2382,7 +2358,7 @@ void TextServerAdvanced::font_set_underline_thickness(const RID &p_font_rid, int fd->cache[size]->underline_thickness = p_underline_thickness; } -double TextServerAdvanced::font_get_underline_thickness(const RID &p_font_rid, int64_t p_size) const { +double TextServerAdvanced::_font_get_underline_thickness(const RID &p_font_rid, int64_t p_size) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, 0.0); @@ -2398,7 +2374,7 @@ double TextServerAdvanced::font_get_underline_thickness(const RID &p_font_rid, i } } -void TextServerAdvanced::font_set_scale(const RID &p_font_rid, int64_t p_size, double p_scale) { +void TextServerAdvanced::_font_set_scale(const RID &p_font_rid, int64_t p_size, double p_scale) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2414,7 +2390,7 @@ void TextServerAdvanced::font_set_scale(const RID &p_font_rid, int64_t p_size, d fd->cache[size]->scale = p_scale; } -double TextServerAdvanced::font_get_scale(const RID &p_font_rid, int64_t p_size) const { +double TextServerAdvanced::_font_get_scale(const RID &p_font_rid, int64_t p_size) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, 0.0); @@ -2430,7 +2406,7 @@ double TextServerAdvanced::font_get_scale(const RID &p_font_rid, int64_t p_size) } } -int64_t TextServerAdvanced::font_get_texture_count(const RID &p_font_rid, const Vector2i &p_size) const { +int64_t TextServerAdvanced::_font_get_texture_count(const RID &p_font_rid, const Vector2i &p_size) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, 0); @@ -2442,7 +2418,7 @@ int64_t TextServerAdvanced::font_get_texture_count(const RID &p_font_rid, const return fd->cache[size]->textures.size(); } -void TextServerAdvanced::font_clear_textures(const RID &p_font_rid, const Vector2i &p_size) { +void TextServerAdvanced::_font_clear_textures(const RID &p_font_rid, const Vector2i &p_size) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); MutexLock lock(fd->mutex); @@ -2452,7 +2428,7 @@ void TextServerAdvanced::font_clear_textures(const RID &p_font_rid, const Vector fd->cache[size]->textures.clear(); } -void TextServerAdvanced::font_remove_texture(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) { +void TextServerAdvanced::_font_remove_texture(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2464,7 +2440,7 @@ void TextServerAdvanced::font_remove_texture(const RID &p_font_rid, const Vector fd->cache[size]->textures.remove_at(p_texture_index); } -void TextServerAdvanced::font_set_texture_image(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index, const Ref<Image> &p_image) { +void TextServerAdvanced::_font_set_texture_image(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index, const Ref<Image> &p_image) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); ERR_FAIL_COND(p_image.is_null()); @@ -2477,16 +2453,14 @@ void TextServerAdvanced::font_set_texture_image(const RID &p_font_rid, const Vec fd->cache[size]->textures.resize(p_texture_index + 1); } - FontTexture &tex = fd->cache[size]->textures.write[p_texture_index]; + ShelfPackTexture &tex = fd->cache[size]->textures.write[p_texture_index]; tex.imgdata = p_image->get_data(); tex.texture_w = p_image->get_width(); tex.texture_h = p_image->get_height(); tex.format = p_image->get_format(); - Ref<Image> img; - img.instantiate(); - img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); + Ref<Image> img = Image::create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); if (fd->mipmaps) { img->generate_mipmaps(); } @@ -2495,7 +2469,7 @@ void TextServerAdvanced::font_set_texture_image(const RID &p_font_rid, const Vec tex.dirty = false; } -Ref<Image> TextServerAdvanced::font_get_texture_image(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) const { +Ref<Image> TextServerAdvanced::_font_get_texture_image(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Ref<Image>()); @@ -2504,15 +2478,12 @@ Ref<Image> TextServerAdvanced::font_get_texture_image(const RID &p_font_rid, con ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), Ref<Image>()); ERR_FAIL_INDEX_V(p_texture_index, fd->cache[size]->textures.size(), Ref<Image>()); - const FontTexture &tex = fd->cache[size]->textures[p_texture_index]; - Ref<Image> img; - img.instantiate(); - img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); - - return img; + const ShelfPackTexture &tex = fd->cache[size]->textures[p_texture_index]; + return Image::create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); } -void TextServerAdvanced::font_set_texture_offsets(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index, const PackedInt32Array &p_offset) { +void TextServerAdvanced::_font_set_texture_offsets(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index, const PackedInt32Array &p_offsets) { + ERR_FAIL_COND(p_offsets.size() % 4 != 0); FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2524,11 +2495,14 @@ void TextServerAdvanced::font_set_texture_offsets(const RID &p_font_rid, const V fd->cache[size]->textures.resize(p_texture_index + 1); } - FontTexture &tex = fd->cache[size]->textures.write[p_texture_index]; - tex.offsets = p_offset; + ShelfPackTexture &tex = fd->cache[size]->textures.write[p_texture_index]; + tex.shelves.clear(); + for (int32_t i = 0; i < p_offsets.size(); i += 4) { + tex.shelves.push_back(Shelf(p_offsets[i], p_offsets[i + 1], p_offsets[i + 2], p_offsets[i + 3])); + } } -PackedInt32Array TextServerAdvanced::font_get_texture_offsets(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) const { +PackedInt32Array TextServerAdvanced::_font_get_texture_offsets(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, PackedInt32Array()); @@ -2537,11 +2511,23 @@ PackedInt32Array TextServerAdvanced::font_get_texture_offsets(const RID &p_font_ ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), PackedInt32Array()); ERR_FAIL_INDEX_V(p_texture_index, fd->cache[size]->textures.size(), PackedInt32Array()); - const FontTexture &tex = fd->cache[size]->textures[p_texture_index]; - return tex.offsets; + const ShelfPackTexture &tex = fd->cache[size]->textures[p_texture_index]; + PackedInt32Array ret; + ret.resize(tex.shelves.size() * 4); + + int32_t *wr = ret.ptrw(); + int32_t i = 0; + for (const Shelf &E : tex.shelves) { + wr[i * 4] = E.x; + wr[i * 4 + 1] = E.y; + wr[i * 4 + 2] = E.w; + wr[i * 4 + 3] = E.h; + i++; + } + return ret; } -PackedInt32Array TextServerAdvanced::font_get_glyph_list(const RID &p_font_rid, const Vector2i &p_size) const { +PackedInt32Array TextServerAdvanced::_font_get_glyph_list(const RID &p_font_rid, const Vector2i &p_size) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, PackedInt32Array()); @@ -2557,7 +2543,7 @@ PackedInt32Array TextServerAdvanced::font_get_glyph_list(const RID &p_font_rid, return ret; } -void TextServerAdvanced::font_clear_glyphs(const RID &p_font_rid, const Vector2i &p_size) { +void TextServerAdvanced::_font_clear_glyphs(const RID &p_font_rid, const Vector2i &p_size) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2568,7 +2554,7 @@ void TextServerAdvanced::font_clear_glyphs(const RID &p_font_rid, const Vector2i fd->cache[size]->glyph_map.clear(); } -void TextServerAdvanced::font_remove_glyph(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) { +void TextServerAdvanced::_font_remove_glyph(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2593,7 +2579,7 @@ double TextServerAdvanced::_get_extra_advance(RID p_font_rid, int p_font_size) c } } -Vector2 TextServerAdvanced::font_get_glyph_advance(const RID &p_font_rid, int64_t p_size, int64_t p_glyph) const { +Vector2 TextServerAdvanced::_font_get_glyph_advance(const RID &p_font_rid, int64_t p_size, int64_t p_glyph) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Vector2()); @@ -2621,16 +2607,17 @@ Vector2 TextServerAdvanced::font_get_glyph_advance(const RID &p_font_rid, int64_ ea.x = fd->embolden * double(size.x) / 64.0; } + double scale = _font_get_scale(p_font_rid, p_size); if (fd->msdf) { return (gl[p_glyph | mod].advance + ea) * (double)p_size / (double)fd->msdf_source_size; - } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_DISABLED) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x > SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) { + } else if ((scale == 1.0) && ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_DISABLED) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x > SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE))) { return (gl[p_glyph | mod].advance + ea).round(); } else { return gl[p_glyph | mod].advance + ea; } } -void TextServerAdvanced::font_set_glyph_advance(const RID &p_font_rid, int64_t p_size, int64_t p_glyph, const Vector2 &p_advance) { +void TextServerAdvanced::_font_set_glyph_advance(const RID &p_font_rid, int64_t p_size, int64_t p_glyph, const Vector2 &p_advance) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2645,7 +2632,7 @@ void TextServerAdvanced::font_set_glyph_advance(const RID &p_font_rid, int64_t p gl[p_glyph].found = true; } -Vector2 TextServerAdvanced::font_get_glyph_offset(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const { +Vector2 TextServerAdvanced::_font_get_glyph_offset(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Vector2()); @@ -2675,7 +2662,7 @@ Vector2 TextServerAdvanced::font_get_glyph_offset(const RID &p_font_rid, const V } } -void TextServerAdvanced::font_set_glyph_offset(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, const Vector2 &p_offset) { +void TextServerAdvanced::_font_set_glyph_offset(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, const Vector2 &p_offset) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2690,7 +2677,7 @@ void TextServerAdvanced::font_set_glyph_offset(const RID &p_font_rid, const Vect gl[p_glyph].found = true; } -Vector2 TextServerAdvanced::font_get_glyph_size(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const { +Vector2 TextServerAdvanced::_font_get_glyph_size(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Vector2()); @@ -2720,7 +2707,7 @@ Vector2 TextServerAdvanced::font_get_glyph_size(const RID &p_font_rid, const Vec } } -void TextServerAdvanced::font_set_glyph_size(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, const Vector2 &p_gl_size) { +void TextServerAdvanced::_font_set_glyph_size(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, const Vector2 &p_gl_size) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2735,7 +2722,7 @@ void TextServerAdvanced::font_set_glyph_size(const RID &p_font_rid, const Vector gl[p_glyph].found = true; } -Rect2 TextServerAdvanced::font_get_glyph_uv_rect(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const { +Rect2 TextServerAdvanced::_font_get_glyph_uv_rect(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Rect2()); @@ -2760,7 +2747,7 @@ Rect2 TextServerAdvanced::font_get_glyph_uv_rect(const RID &p_font_rid, const Ve return gl[p_glyph | mod].uv_rect; } -void TextServerAdvanced::font_set_glyph_uv_rect(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, const Rect2 &p_uv_rect) { +void TextServerAdvanced::_font_set_glyph_uv_rect(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, const Rect2 &p_uv_rect) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2775,7 +2762,7 @@ void TextServerAdvanced::font_set_glyph_uv_rect(const RID &p_font_rid, const Vec gl[p_glyph].found = true; } -int64_t TextServerAdvanced::font_get_glyph_texture_idx(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const { +int64_t TextServerAdvanced::_font_get_glyph_texture_idx(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, -1); @@ -2800,7 +2787,7 @@ int64_t TextServerAdvanced::font_get_glyph_texture_idx(const RID &p_font_rid, co return gl[p_glyph | mod].texture_idx; } -void TextServerAdvanced::font_set_glyph_texture_idx(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, int64_t p_texture_idx) { +void TextServerAdvanced::_font_set_glyph_texture_idx(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, int64_t p_texture_idx) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2815,7 +2802,7 @@ void TextServerAdvanced::font_set_glyph_texture_idx(const RID &p_font_rid, const gl[p_glyph].found = true; } -RID TextServerAdvanced::font_get_glyph_texture_rid(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const { +RID TextServerAdvanced::_font_get_glyph_texture_rid(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, RID()); @@ -2842,10 +2829,8 @@ RID TextServerAdvanced::font_get_glyph_texture_rid(const RID &p_font_rid, const if (RenderingServer::get_singleton() != nullptr) { if (gl[p_glyph | mod].texture_idx != -1) { if (fd->cache[size]->textures[gl[p_glyph | mod].texture_idx].dirty) { - FontTexture &tex = fd->cache[size]->textures.write[gl[p_glyph | mod].texture_idx]; - Ref<Image> img; - img.instantiate(); - img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); + ShelfPackTexture &tex = fd->cache[size]->textures.write[gl[p_glyph | mod].texture_idx]; + Ref<Image> img = Image::create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); if (fd->mipmaps) { img->generate_mipmaps(); } @@ -2863,7 +2848,7 @@ RID TextServerAdvanced::font_get_glyph_texture_rid(const RID &p_font_rid, const return RID(); } -Size2 TextServerAdvanced::font_get_glyph_texture_size(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const { +Size2 TextServerAdvanced::_font_get_glyph_texture_size(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Size2()); @@ -2890,10 +2875,8 @@ Size2 TextServerAdvanced::font_get_glyph_texture_size(const RID &p_font_rid, con if (RenderingServer::get_singleton() != nullptr) { if (gl[p_glyph | mod].texture_idx != -1) { if (fd->cache[size]->textures[gl[p_glyph | mod].texture_idx].dirty) { - FontTexture &tex = fd->cache[size]->textures.write[gl[p_glyph | mod].texture_idx]; - Ref<Image> img; - img.instantiate(); - img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); + ShelfPackTexture &tex = fd->cache[size]->textures.write[gl[p_glyph | mod].texture_idx]; + Ref<Image> img = Image::create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); if (fd->mipmaps) { img->generate_mipmaps(); } @@ -2911,7 +2894,7 @@ Size2 TextServerAdvanced::font_get_glyph_texture_size(const RID &p_font_rid, con return Size2(); } -Dictionary TextServerAdvanced::font_get_glyph_contours(const RID &p_font_rid, int64_t p_size, int64_t p_index) const { +Dictionary TextServerAdvanced::_font_get_glyph_contours(const RID &p_font_rid, int64_t p_size, int64_t p_index) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Dictionary()); @@ -2961,7 +2944,7 @@ Dictionary TextServerAdvanced::font_get_glyph_contours(const RID &p_font_rid, in #endif } -TypedArray<Vector2i> TextServerAdvanced::font_get_kerning_list(const RID &p_font_rid, int64_t p_size) const { +TypedArray<Vector2i> TextServerAdvanced::_font_get_kerning_list(const RID &p_font_rid, int64_t p_size) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, TypedArray<Vector2i>()); @@ -2977,7 +2960,7 @@ TypedArray<Vector2i> TextServerAdvanced::font_get_kerning_list(const RID &p_font return ret; } -void TextServerAdvanced::font_clear_kerning_map(const RID &p_font_rid, int64_t p_size) { +void TextServerAdvanced::_font_clear_kerning_map(const RID &p_font_rid, int64_t p_size) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2988,7 +2971,7 @@ void TextServerAdvanced::font_clear_kerning_map(const RID &p_font_rid, int64_t p fd->cache[size]->kerning_map.clear(); } -void TextServerAdvanced::font_remove_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair) { +void TextServerAdvanced::_font_remove_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2999,7 +2982,7 @@ void TextServerAdvanced::font_remove_kerning(const RID &p_font_rid, int64_t p_si fd->cache[size]->kerning_map.erase(p_glyph_pair); } -void TextServerAdvanced::font_set_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair, const Vector2 &p_kerning) { +void TextServerAdvanced::_font_set_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair, const Vector2 &p_kerning) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -3010,7 +2993,7 @@ void TextServerAdvanced::font_set_kerning(const RID &p_font_rid, int64_t p_size, fd->cache[size]->kerning_map[p_glyph_pair] = p_kerning; } -Vector2 TextServerAdvanced::font_get_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair) const { +Vector2 TextServerAdvanced::_font_get_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Vector2()); @@ -3043,7 +3026,7 @@ Vector2 TextServerAdvanced::font_get_kerning(const RID &p_font_rid, int64_t p_si return Vector2(); } -int64_t TextServerAdvanced::font_get_glyph_index(const RID &p_font_rid, int64_t p_size, int64_t p_char, int64_t p_variation_selector) const { +int64_t TextServerAdvanced::_font_get_glyph_index(const RID &p_font_rid, int64_t p_size, int64_t p_char, int64_t p_variation_selector) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, 0); ERR_FAIL_COND_V_MSG((p_char >= 0xd800 && p_char <= 0xdfff) || (p_char > 0x10ffff), 0, "Unicode parsing error: Invalid unicode codepoint " + String::num_int64(p_char, 16) + "."); @@ -3068,10 +3051,12 @@ int64_t TextServerAdvanced::font_get_glyph_index(const RID &p_font_rid, int64_t #endif } -bool TextServerAdvanced::font_has_char(const RID &p_font_rid, int64_t p_char) const { +bool TextServerAdvanced::_font_has_char(const RID &p_font_rid, int64_t p_char) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); - ERR_FAIL_COND_V(!fd, false); ERR_FAIL_COND_V_MSG((p_char >= 0xd800 && p_char <= 0xdfff) || (p_char > 0x10ffff), false, "Unicode parsing error: Invalid unicode codepoint " + String::num_int64(p_char, 16) + "."); + if (!fd) { + return false; + } MutexLock lock(fd->mutex); if (fd->cache.is_empty()) { @@ -3087,7 +3072,7 @@ bool TextServerAdvanced::font_has_char(const RID &p_font_rid, int64_t p_char) co return (at_size) ? at_size->glyph_map.has((int32_t)p_char) : false; } -String TextServerAdvanced::font_get_supported_chars(const RID &p_font_rid) const { +String TextServerAdvanced::_font_get_supported_chars(const RID &p_font_rid) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, String()); @@ -3120,7 +3105,7 @@ String TextServerAdvanced::font_get_supported_chars(const RID &p_font_rid) const return chars; } -void TextServerAdvanced::font_render_range(const RID &p_font_rid, const Vector2i &p_size, int64_t p_start, int64_t p_end) { +void TextServerAdvanced::_font_render_range(const RID &p_font_rid, const Vector2i &p_size, int64_t p_start, int64_t p_end) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); ERR_FAIL_COND_MSG((p_start >= 0xd800 && p_start <= 0xdfff) || (p_start > 0x10ffff), "Unicode parsing error: Invalid unicode codepoint " + String::num_int64(p_start, 16) + "."); @@ -3155,7 +3140,7 @@ void TextServerAdvanced::font_render_range(const RID &p_font_rid, const Vector2i } } -void TextServerAdvanced::font_render_glyph(const RID &p_font_rid, const Vector2i &p_size, int64_t p_index) { +void TextServerAdvanced::_font_render_glyph(const RID &p_font_rid, const Vector2i &p_size, int64_t p_index) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -3186,7 +3171,7 @@ void TextServerAdvanced::font_render_glyph(const RID &p_font_rid, const Vector2i #endif } -void TextServerAdvanced::font_draw_glyph(const RID &p_font_rid, const RID &p_canvas, int64_t p_size, const Vector2 &p_pos, int64_t p_index, const Color &p_color) const { +void TextServerAdvanced::_font_draw_glyph(const RID &p_font_rid, const RID &p_canvas, int64_t p_size, const Vector2 &p_pos, int64_t p_index, const Color &p_color) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -3235,10 +3220,8 @@ void TextServerAdvanced::font_draw_glyph(const RID &p_font_rid, const RID &p_can #endif if (RenderingServer::get_singleton() != nullptr) { if (fd->cache[size]->textures[gl.texture_idx].dirty) { - FontTexture &tex = fd->cache[size]->textures.write[gl.texture_idx]; - Ref<Image> img; - img.instantiate(); - img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); + ShelfPackTexture &tex = fd->cache[size]->textures.write[gl.texture_idx]; + Ref<Image> img = Image::create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); if (fd->mipmaps) { img->generate_mipmaps(); } @@ -3256,13 +3239,15 @@ void TextServerAdvanced::font_draw_glyph(const RID &p_font_rid, const RID &p_can Size2 csize = gl.rect.size * (double)p_size / (double)fd->msdf_source_size; RenderingServer::get_singleton()->canvas_item_add_msdf_texture_rect_region(p_canvas, Rect2(cpos, csize), texture, gl.uv_rect, modulate, 0, fd->msdf_range); } else { + double scale = _font_get_scale(p_font_rid, p_size); Point2 cpos = p_pos; - cpos.y = Math::floor(cpos.y); if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) { - cpos.x = ((int)Math::floor(cpos.x + 0.125)); + cpos.x = cpos.x + 0.125; } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) { - cpos.x = ((int)Math::floor(cpos.x + 0.25)); - } else { + cpos.x = cpos.x + 0.25; + } + if (scale == 1.0) { + cpos.y = Math::floor(cpos.y); cpos.x = Math::floor(cpos.x); } cpos += gl.rect.position; @@ -3278,7 +3263,7 @@ void TextServerAdvanced::font_draw_glyph(const RID &p_font_rid, const RID &p_can } } -void TextServerAdvanced::font_draw_glyph_outline(const RID &p_font_rid, const RID &p_canvas, int64_t p_size, int64_t p_outline_size, const Vector2 &p_pos, int64_t p_index, const Color &p_color) const { +void TextServerAdvanced::_font_draw_glyph_outline(const RID &p_font_rid, const RID &p_canvas, int64_t p_size, int64_t p_outline_size, const Vector2 &p_pos, int64_t p_index, const Color &p_color) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -3327,10 +3312,8 @@ void TextServerAdvanced::font_draw_glyph_outline(const RID &p_font_rid, const RI #endif if (RenderingServer::get_singleton() != nullptr) { if (fd->cache[size]->textures[gl.texture_idx].dirty) { - FontTexture &tex = fd->cache[size]->textures.write[gl.texture_idx]; - Ref<Image> img; - img.instantiate(); - img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); + ShelfPackTexture &tex = fd->cache[size]->textures.write[gl.texture_idx]; + Ref<Image> img = Image::create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); if (fd->mipmaps) { img->generate_mipmaps(); } @@ -3349,12 +3332,14 @@ void TextServerAdvanced::font_draw_glyph_outline(const RID &p_font_rid, const RI RenderingServer::get_singleton()->canvas_item_add_msdf_texture_rect_region(p_canvas, Rect2(cpos, csize), texture, gl.uv_rect, modulate, p_outline_size * 2, fd->msdf_range); } else { Point2 cpos = p_pos; - cpos.y = Math::floor(cpos.y); + double scale = _font_get_scale(p_font_rid, p_size); if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) { - cpos.x = ((int)Math::floor(cpos.x + 0.125)); + cpos.x = cpos.x + 0.125; } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) { - cpos.x = ((int)Math::floor(cpos.x + 0.25)); - } else { + cpos.x = cpos.x + 0.25; + } + if (scale == 1.0) { + cpos.y = Math::floor(cpos.y); cpos.x = Math::floor(cpos.x); } cpos += gl.rect.position; @@ -3370,7 +3355,7 @@ void TextServerAdvanced::font_draw_glyph_outline(const RID &p_font_rid, const RI } } -bool TextServerAdvanced::font_is_language_supported(const RID &p_font_rid, const String &p_language) const { +bool TextServerAdvanced::_font_is_language_supported(const RID &p_font_rid, const String &p_language) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, false); @@ -3382,7 +3367,7 @@ bool TextServerAdvanced::font_is_language_supported(const RID &p_font_rid, const } } -void TextServerAdvanced::font_set_language_support_override(const RID &p_font_rid, const String &p_language, bool p_supported) { +void TextServerAdvanced::_font_set_language_support_override(const RID &p_font_rid, const String &p_language, bool p_supported) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -3390,7 +3375,7 @@ void TextServerAdvanced::font_set_language_support_override(const RID &p_font_ri fd->language_support_overrides[p_language] = p_supported; } -bool TextServerAdvanced::font_get_language_support_override(const RID &p_font_rid, const String &p_language) { +bool TextServerAdvanced::_font_get_language_support_override(const RID &p_font_rid, const String &p_language) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, false); @@ -3398,7 +3383,7 @@ bool TextServerAdvanced::font_get_language_support_override(const RID &p_font_ri return fd->language_support_overrides[p_language]; } -void TextServerAdvanced::font_remove_language_support_override(const RID &p_font_rid, const String &p_language) { +void TextServerAdvanced::_font_remove_language_support_override(const RID &p_font_rid, const String &p_language) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -3406,7 +3391,7 @@ void TextServerAdvanced::font_remove_language_support_override(const RID &p_font fd->language_support_overrides.erase(p_language); } -PackedStringArray TextServerAdvanced::font_get_language_support_overrides(const RID &p_font_rid) { +PackedStringArray TextServerAdvanced::_font_get_language_support_overrides(const RID &p_font_rid) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, PackedStringArray()); @@ -3418,7 +3403,7 @@ PackedStringArray TextServerAdvanced::font_get_language_support_overrides(const return out; } -bool TextServerAdvanced::font_is_script_supported(const RID &p_font_rid, const String &p_script) const { +bool TextServerAdvanced::_font_is_script_supported(const RID &p_font_rid, const String &p_script) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, false); @@ -3432,7 +3417,7 @@ bool TextServerAdvanced::font_is_script_supported(const RID &p_font_rid, const S } } -void TextServerAdvanced::font_set_script_support_override(const RID &p_font_rid, const String &p_script, bool p_supported) { +void TextServerAdvanced::_font_set_script_support_override(const RID &p_font_rid, const String &p_script, bool p_supported) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -3440,7 +3425,7 @@ void TextServerAdvanced::font_set_script_support_override(const RID &p_font_rid, fd->script_support_overrides[p_script] = p_supported; } -bool TextServerAdvanced::font_get_script_support_override(const RID &p_font_rid, const String &p_script) { +bool TextServerAdvanced::_font_get_script_support_override(const RID &p_font_rid, const String &p_script) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, false); @@ -3448,7 +3433,7 @@ bool TextServerAdvanced::font_get_script_support_override(const RID &p_font_rid, return fd->script_support_overrides[p_script]; } -void TextServerAdvanced::font_remove_script_support_override(const RID &p_font_rid, const String &p_script) { +void TextServerAdvanced::_font_remove_script_support_override(const RID &p_font_rid, const String &p_script) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -3456,7 +3441,7 @@ void TextServerAdvanced::font_remove_script_support_override(const RID &p_font_r fd->script_support_overrides.erase(p_script); } -PackedStringArray TextServerAdvanced::font_get_script_support_overrides(const RID &p_font_rid) { +PackedStringArray TextServerAdvanced::_font_get_script_support_overrides(const RID &p_font_rid) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, PackedStringArray()); @@ -3468,7 +3453,7 @@ PackedStringArray TextServerAdvanced::font_get_script_support_overrides(const RI return out; } -void TextServerAdvanced::font_set_opentype_feature_overrides(const RID &p_font_rid, const Dictionary &p_overrides) { +void TextServerAdvanced::_font_set_opentype_feature_overrides(const RID &p_font_rid, const Dictionary &p_overrides) { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -3478,7 +3463,7 @@ void TextServerAdvanced::font_set_opentype_feature_overrides(const RID &p_font_r fd->feature_overrides = p_overrides; } -Dictionary TextServerAdvanced::font_get_opentype_feature_overrides(const RID &p_font_rid) const { +Dictionary TextServerAdvanced::_font_get_opentype_feature_overrides(const RID &p_font_rid) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Dictionary()); @@ -3486,7 +3471,7 @@ Dictionary TextServerAdvanced::font_get_opentype_feature_overrides(const RID &p_ return fd->feature_overrides; } -Dictionary TextServerAdvanced::font_supported_feature_list(const RID &p_font_rid) const { +Dictionary TextServerAdvanced::_font_supported_feature_list(const RID &p_font_rid) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Dictionary()); @@ -3496,7 +3481,7 @@ Dictionary TextServerAdvanced::font_supported_feature_list(const RID &p_font_rid return fd->supported_features; } -Dictionary TextServerAdvanced::font_supported_variation_list(const RID &p_font_rid) const { +Dictionary TextServerAdvanced::_font_supported_variation_list(const RID &p_font_rid) const { FontAdvanced *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Dictionary()); @@ -3506,11 +3491,11 @@ Dictionary TextServerAdvanced::font_supported_variation_list(const RID &p_font_r return fd->supported_varaitions; } -double TextServerAdvanced::font_get_global_oversampling() const { +double TextServerAdvanced::_font_get_global_oversampling() const { return oversampling; } -void TextServerAdvanced::font_set_global_oversampling(double p_oversampling) { +void TextServerAdvanced::_font_set_global_oversampling(double p_oversampling) { _THREAD_SAFE_METHOD_ if (oversampling != p_oversampling) { oversampling = p_oversampling; @@ -3518,8 +3503,8 @@ void TextServerAdvanced::font_set_global_oversampling(double p_oversampling) { font_owner.get_owned_list(&fonts); bool font_cleared = false; for (const RID &E : fonts) { - if (!font_is_multichannel_signed_distance_field(E) && font_get_oversampling(E) <= 0) { - font_clear_size_cache(E); + if (!_font_is_multichannel_signed_distance_field(E) && _font_get_oversampling(E) <= 0) { + _font_clear_size_cache(E); font_cleared = true; } } @@ -3628,7 +3613,7 @@ void TextServerAdvanced::full_copy(ShapedTextDataAdvanced *p_shaped) { p_shaped->parent = RID(); } -RID TextServerAdvanced::create_shaped_text(TextServer::Direction p_direction, TextServer::Orientation p_orientation) { +RID TextServerAdvanced::_create_shaped_text(TextServer::Direction p_direction, TextServer::Orientation p_orientation) { _THREAD_SAFE_METHOD_ ShapedTextDataAdvanced *sd = memnew(ShapedTextDataAdvanced); @@ -3638,7 +3623,7 @@ RID TextServerAdvanced::create_shaped_text(TextServer::Direction p_direction, Te return shaped_owner.make_rid(sd); } -void TextServerAdvanced::shaped_text_clear(const RID &p_shaped) { +void TextServerAdvanced::_shaped_text_clear(const RID &p_shaped) { ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND(!sd); @@ -3653,7 +3638,7 @@ void TextServerAdvanced::shaped_text_clear(const RID &p_shaped) { invalidate(sd, true); } -void TextServerAdvanced::shaped_text_set_direction(const RID &p_shaped, TextServer::Direction p_direction) { +void TextServerAdvanced::_shaped_text_set_direction(const RID &p_shaped, TextServer::Direction p_direction) { ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND(!sd); @@ -3667,7 +3652,7 @@ void TextServerAdvanced::shaped_text_set_direction(const RID &p_shaped, TextServ } } -TextServer::Direction TextServerAdvanced::shaped_text_get_direction(const RID &p_shaped) const { +TextServer::Direction TextServerAdvanced::_shaped_text_get_direction(const RID &p_shaped) const { const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, TextServer::DIRECTION_LTR); @@ -3675,7 +3660,7 @@ TextServer::Direction TextServerAdvanced::shaped_text_get_direction(const RID &p return sd->direction; } -TextServer::Direction TextServerAdvanced::shaped_text_get_inferred_direction(const RID &p_shaped) const { +TextServer::Direction TextServerAdvanced::_shaped_text_get_inferred_direction(const RID &p_shaped) const { const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, TextServer::DIRECTION_LTR); @@ -3683,7 +3668,7 @@ TextServer::Direction TextServerAdvanced::shaped_text_get_inferred_direction(con return sd->para_direction; } -void TextServerAdvanced::shaped_text_set_custom_punctuation(const RID &p_shaped, const String &p_punct) { +void TextServerAdvanced::_shaped_text_set_custom_punctuation(const RID &p_shaped, const String &p_punct) { _THREAD_SAFE_METHOD_ ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND(!sd); @@ -3697,14 +3682,14 @@ void TextServerAdvanced::shaped_text_set_custom_punctuation(const RID &p_shaped, } } -String TextServerAdvanced::shaped_text_get_custom_punctuation(const RID &p_shaped) const { +String TextServerAdvanced::_shaped_text_get_custom_punctuation(const RID &p_shaped) const { _THREAD_SAFE_METHOD_ const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, String()); return sd->custom_punct; } -void TextServerAdvanced::shaped_text_set_bidi_override(const RID &p_shaped, const Array &p_override) { +void TextServerAdvanced::_shaped_text_set_bidi_override(const RID &p_shaped, const Array &p_override) { ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND(!sd); @@ -3721,7 +3706,7 @@ void TextServerAdvanced::shaped_text_set_bidi_override(const RID &p_shaped, cons invalidate(sd, false); } -void TextServerAdvanced::shaped_text_set_orientation(const RID &p_shaped, TextServer::Orientation p_orientation) { +void TextServerAdvanced::_shaped_text_set_orientation(const RID &p_shaped, TextServer::Orientation p_orientation) { ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND(!sd); @@ -3735,7 +3720,7 @@ void TextServerAdvanced::shaped_text_set_orientation(const RID &p_shaped, TextSe } } -void TextServerAdvanced::shaped_text_set_preserve_invalid(const RID &p_shaped, bool p_enabled) { +void TextServerAdvanced::_shaped_text_set_preserve_invalid(const RID &p_shaped, bool p_enabled) { ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND(!sd); @@ -3747,7 +3732,7 @@ void TextServerAdvanced::shaped_text_set_preserve_invalid(const RID &p_shaped, b } } -bool TextServerAdvanced::shaped_text_get_preserve_invalid(const RID &p_shaped) const { +bool TextServerAdvanced::_shaped_text_get_preserve_invalid(const RID &p_shaped) const { const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, false); @@ -3755,7 +3740,7 @@ bool TextServerAdvanced::shaped_text_get_preserve_invalid(const RID &p_shaped) c return sd->preserve_invalid; } -void TextServerAdvanced::shaped_text_set_preserve_control(const RID &p_shaped, bool p_enabled) { +void TextServerAdvanced::_shaped_text_set_preserve_control(const RID &p_shaped, bool p_enabled) { ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND(!sd); @@ -3769,7 +3754,7 @@ void TextServerAdvanced::shaped_text_set_preserve_control(const RID &p_shaped, b } } -bool TextServerAdvanced::shaped_text_get_preserve_control(const RID &p_shaped) const { +bool TextServerAdvanced::_shaped_text_get_preserve_control(const RID &p_shaped) const { const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, false); @@ -3777,7 +3762,7 @@ bool TextServerAdvanced::shaped_text_get_preserve_control(const RID &p_shaped) c return sd->preserve_control; } -void TextServerAdvanced::shaped_text_set_spacing(const RID &p_shaped, SpacingType p_spacing, int64_t p_value) { +void TextServerAdvanced::_shaped_text_set_spacing(const RID &p_shaped, SpacingType p_spacing, int64_t p_value) { ERR_FAIL_INDEX((int)p_spacing, 4); ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND(!sd); @@ -3792,7 +3777,7 @@ void TextServerAdvanced::shaped_text_set_spacing(const RID &p_shaped, SpacingTyp } } -int64_t TextServerAdvanced::shaped_text_get_spacing(const RID &p_shaped, SpacingType p_spacing) const { +int64_t TextServerAdvanced::_shaped_text_get_spacing(const RID &p_shaped, SpacingType p_spacing) const { ERR_FAIL_INDEX_V((int)p_spacing, 4, 0); const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); @@ -3802,7 +3787,7 @@ int64_t TextServerAdvanced::shaped_text_get_spacing(const RID &p_shaped, Spacing return sd->extra_spacing[p_spacing]; } -TextServer::Orientation TextServerAdvanced::shaped_text_get_orientation(const RID &p_shaped) const { +TextServer::Orientation TextServerAdvanced::_shaped_text_get_orientation(const RID &p_shaped) const { const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, TextServer::ORIENTATION_HORIZONTAL); @@ -3810,41 +3795,33 @@ TextServer::Orientation TextServerAdvanced::shaped_text_get_orientation(const RI return sd->orientation; } -int64_t TextServerAdvanced::shaped_get_span_count(const RID &p_shaped) const { +int64_t TextServerAdvanced::_shaped_get_span_count(const RID &p_shaped) const { ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, 0); return sd->spans.size(); } -Variant TextServerAdvanced::shaped_get_span_meta(const RID &p_shaped, int64_t p_index) const { +Variant TextServerAdvanced::_shaped_get_span_meta(const RID &p_shaped, int64_t p_index) const { ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, Variant()); ERR_FAIL_INDEX_V(p_index, sd->spans.size(), Variant()); return sd->spans[p_index].meta; } -void TextServerAdvanced::shaped_set_span_update_font(const RID &p_shaped, int64_t p_index, const TypedArray<RID> &p_fonts, int64_t p_size, const Dictionary &p_opentype_features) { +void TextServerAdvanced::_shaped_set_span_update_font(const RID &p_shaped, int64_t p_index, const TypedArray<RID> &p_fonts, int64_t p_size, const Dictionary &p_opentype_features) { ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND(!sd); ERR_FAIL_INDEX(p_index, sd->spans.size()); ShapedTextDataAdvanced::Span &span = sd->spans.ptrw()[p_index]; - bool changed = (span.font_size != p_size) || (span.features != p_opentype_features) || (p_fonts.size() != span.fonts.size()); - if (!changed) { - for (int i = 0; i < p_fonts.size(); i++) { - changed = changed || (span.fonts[i] != p_fonts[i]); - } - } - if (changed) { - span.fonts = p_fonts; - span.font_size = p_size; - span.features = p_opentype_features; + span.fonts = p_fonts; + span.font_size = p_size; + span.features = p_opentype_features; - invalidate(sd, false); - } + invalidate(sd, false); } -bool TextServerAdvanced::shaped_text_add_string(const RID &p_shaped, const String &p_text, const TypedArray<RID> &p_fonts, int64_t p_size, const Dictionary &p_opentype_features, const String &p_language, const Variant &p_meta) { +bool TextServerAdvanced::_shaped_text_add_string(const RID &p_shaped, const String &p_text, const TypedArray<RID> &p_fonts, int64_t p_size, const Dictionary &p_opentype_features, const String &p_language, const Variant &p_meta) { ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, false); ERR_FAIL_COND_V(p_size <= 0, false); @@ -3879,7 +3856,7 @@ bool TextServerAdvanced::shaped_text_add_string(const RID &p_shaped, const Strin return true; } -bool TextServerAdvanced::shaped_text_add_object(const RID &p_shaped, const Variant &p_key, const Size2 &p_size, InlineAlignment p_inline_align, int64_t p_length) { +bool TextServerAdvanced::_shaped_text_add_object(const RID &p_shaped, const Variant &p_key, const Size2 &p_size, InlineAlignment p_inline_align, int64_t p_length) { _THREAD_SAFE_METHOD_ ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, false); @@ -3909,7 +3886,7 @@ bool TextServerAdvanced::shaped_text_add_object(const RID &p_shaped, const Varia return true; } -bool TextServerAdvanced::shaped_text_resize_object(const RID &p_shaped, const Variant &p_key, const Size2 &p_size, InlineAlignment p_inline_align) { +bool TextServerAdvanced::_shaped_text_resize_object(const RID &p_shaped, const Variant &p_key, const Size2 &p_size, InlineAlignment p_inline_align) { ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, false); @@ -3950,14 +3927,14 @@ bool TextServerAdvanced::shaped_text_resize_object(const RID &p_shaped, const Va } else { if (gl.font_rid.is_valid()) { if (sd->orientation == ORIENTATION_HORIZONTAL) { - sd->ascent = MAX(sd->ascent, MAX(font_get_ascent(gl.font_rid, gl.font_size), -gl.y_off)); - sd->descent = MAX(sd->descent, MAX(font_get_descent(gl.font_rid, gl.font_size), gl.y_off)); + sd->ascent = MAX(sd->ascent, MAX(_font_get_ascent(gl.font_rid, gl.font_size), -gl.y_off)); + sd->descent = MAX(sd->descent, MAX(_font_get_descent(gl.font_rid, gl.font_size), gl.y_off)); } else { - sd->ascent = MAX(sd->ascent, Math::round(font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5)); - sd->descent = MAX(sd->descent, Math::round(font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5)); + sd->ascent = MAX(sd->ascent, Math::round(_font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5)); + sd->descent = MAX(sd->descent, Math::round(_font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).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)); + 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) { @@ -4044,7 +4021,7 @@ void TextServerAdvanced::_realign(ShapedTextDataAdvanced *p_sd) const { p_sd->descent = full_descent; } -RID TextServerAdvanced::shaped_text_substr(const RID &p_shaped, int64_t p_start, int64_t p_length) const { +RID TextServerAdvanced::_shaped_text_substr(const RID &p_shaped, int64_t p_start, int64_t p_length) const { _THREAD_SAFE_METHOD_ const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); @@ -4052,10 +4029,10 @@ RID TextServerAdvanced::shaped_text_substr(const RID &p_shaped, int64_t p_start, MutexLock lock(sd->mutex); if (sd->parent != RID()) { - return shaped_text_substr(sd->parent, p_start, p_length); + return _shaped_text_substr(sd->parent, p_start, p_length); } if (!sd->valid) { - const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + 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()); @@ -4159,11 +4136,11 @@ bool TextServerAdvanced::_shape_substr(ShapedTextDataAdvanced *p_new_sd, const S } else { if (gl.font_rid.is_valid()) { if (p_new_sd->orientation == ORIENTATION_HORIZONTAL) { - p_new_sd->ascent = MAX(p_new_sd->ascent, MAX(font_get_ascent(gl.font_rid, gl.font_size), -gl.y_off)); - p_new_sd->descent = MAX(p_new_sd->descent, MAX(font_get_descent(gl.font_rid, gl.font_size), gl.y_off)); + p_new_sd->ascent = MAX(p_new_sd->ascent, MAX(_font_get_ascent(gl.font_rid, gl.font_size), -gl.y_off)); + p_new_sd->descent = MAX(p_new_sd->descent, MAX(_font_get_descent(gl.font_rid, gl.font_size), gl.y_off)); } else { - p_new_sd->ascent = MAX(p_new_sd->ascent, Math::round(font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5)); - p_new_sd->descent = MAX(p_new_sd->descent, Math::round(font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5)); + p_new_sd->ascent = MAX(p_new_sd->ascent, Math::round(_font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5)); + p_new_sd->descent = MAX(p_new_sd->descent, Math::round(_font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5)); } } else if (p_new_sd->preserve_invalid || (p_new_sd->preserve_control && is_control(gl.index))) { // Glyph not found, replace with hex code box. @@ -4189,7 +4166,7 @@ bool TextServerAdvanced::_shape_substr(ShapedTextDataAdvanced *p_new_sd, const S return true; } -RID TextServerAdvanced::shaped_text_get_parent(const RID &p_shaped) const { +RID TextServerAdvanced::_shaped_text_get_parent(const RID &p_shaped) const { ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, RID()); @@ -4197,16 +4174,16 @@ RID TextServerAdvanced::shaped_text_get_parent(const RID &p_shaped) const { return sd->parent; } -double TextServerAdvanced::shaped_text_fit_to_width(const RID &p_shaped, double p_width, BitField<TextServer::JustificationFlag> p_jst_flags) { +double TextServerAdvanced::_shaped_text_fit_to_width(const RID &p_shaped, double p_width, BitField<TextServer::JustificationFlag> p_jst_flags) { ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, 0.0); MutexLock lock(sd->mutex); if (!sd->valid) { - const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + 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); + const_cast<TextServerAdvanced *>(this)->_shaped_text_update_justification_ops(p_shaped); } sd->fit_width_minimum_reached = false; @@ -4354,16 +4331,16 @@ double TextServerAdvanced::shaped_text_fit_to_width(const RID &p_shaped, double return Math::ceil(justification_width); } -double TextServerAdvanced::shaped_text_tab_align(const RID &p_shaped, const PackedFloat32Array &p_tab_stops) { +double TextServerAdvanced::_shaped_text_tab_align(const RID &p_shaped, const PackedFloat32Array &p_tab_stops) { ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, 0.0); MutexLock lock(sd->mutex); if (!sd->valid) { - const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped); } if (!sd->line_breaks_valid) { - const_cast<TextServerAdvanced *>(this)->shaped_text_update_breaks(p_shaped); + const_cast<TextServerAdvanced *>(this)->_shaped_text_update_breaks(p_shaped); } for (int i = 0; i < p_tab_stops.size(); i++) { @@ -4410,13 +4387,13 @@ double TextServerAdvanced::shaped_text_tab_align(const RID &p_shaped, const Pack return 0.0; } -void TextServerAdvanced::shaped_text_overrun_trim_to_width(const RID &p_shaped_line, double p_width, BitField<TextServer::TextOverrunFlag> p_trim_flags) { +void TextServerAdvanced::_shaped_text_overrun_trim_to_width(const RID &p_shaped_line, double p_width, BitField<TextServer::TextOverrunFlag> p_trim_flags) { ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped_line); ERR_FAIL_COND_MSG(!sd, "ShapedTextDataAdvanced invalid."); MutexLock lock(sd->mutex); if (!sd->valid) { - shaped_text_shape(p_shaped_line); + _shaped_text_shape(p_shaped_line); } sd->text_trimmed = false; @@ -4455,30 +4432,30 @@ void TextServerAdvanced::shaped_text_overrun_trim_to_width(const RID &p_shaped_l // Find usable fonts, if fonts from the last glyph do not have required chars. RID dot_gl_font_rid = sd_glyphs[sd_size - 1].font_rid; - if (!font_has_char(dot_gl_font_rid, '.')) { + if (!_font_has_char(dot_gl_font_rid, '.')) { const Array &fonts = spans[spans.size() - 1].fonts; for (int i = 0; i < fonts.size(); i++) { - if (font_has_char(fonts[i], '.')) { + if (_font_has_char(fonts[i], '.')) { dot_gl_font_rid = fonts[i]; break; } } } RID whitespace_gl_font_rid = sd_glyphs[sd_size - 1].font_rid; - if (!font_has_char(whitespace_gl_font_rid, '.')) { + if (!_font_has_char(whitespace_gl_font_rid, '.')) { const Array &fonts = spans[spans.size() - 1].fonts; for (int i = 0; i < fonts.size(); i++) { - if (font_has_char(fonts[i], ' ')) { + if (_font_has_char(fonts[i], ' ')) { whitespace_gl_font_rid = fonts[i]; break; } } } - int32_t dot_gl_idx = dot_gl_font_rid.is_valid() ? font_get_glyph_index(dot_gl_font_rid, last_gl_font_size, '.') : -10; - Vector2 dot_adv = dot_gl_font_rid.is_valid() ? font_get_glyph_advance(dot_gl_font_rid, last_gl_font_size, dot_gl_idx) : Vector2(); - int32_t whitespace_gl_idx = whitespace_gl_font_rid.is_valid() ? font_get_glyph_index(whitespace_gl_font_rid, last_gl_font_size, ' ') : -10; - Vector2 whitespace_adv = whitespace_gl_font_rid.is_valid() ? font_get_glyph_advance(whitespace_gl_font_rid, last_gl_font_size, whitespace_gl_idx) : Vector2(); + int32_t dot_gl_idx = dot_gl_font_rid.is_valid() ? _font_get_glyph_index(dot_gl_font_rid, last_gl_font_size, '.', 0) : -10; + Vector2 dot_adv = dot_gl_font_rid.is_valid() ? _font_get_glyph_advance(dot_gl_font_rid, last_gl_font_size, dot_gl_idx) : Vector2(); + int32_t whitespace_gl_idx = whitespace_gl_font_rid.is_valid() ? _font_get_glyph_index(whitespace_gl_font_rid, last_gl_font_size, ' ', 0) : -10; + Vector2 whitespace_adv = whitespace_gl_font_rid.is_valid() ? _font_get_glyph_advance(whitespace_gl_font_rid, last_gl_font_size, whitespace_gl_idx) : Vector2(); int ellipsis_width = 0; if (add_ellipsis && whitespace_gl_font_rid.is_valid()) { @@ -4500,35 +4477,40 @@ void TextServerAdvanced::shaped_text_overrun_trim_to_width(const RID &p_shaped_l int glyphs_to = (is_rtl) ? sd_size - 1 : -1; int glyphs_delta = (is_rtl) ? +1 : -1; - for (int i = glyphs_from; i != glyphs_to; i += glyphs_delta) { - if (!is_rtl) { - width -= sd_glyphs[i].advance * sd_glyphs[i].repeat; - } - if (sd_glyphs[i].count > 0) { - bool above_min_char_threshold = ((is_rtl) ? sd_size - 1 - i : i) >= ell_min_characters; + if (enforce_ellipsis && (width + ellipsis_width <= p_width)) { + trim_pos = -1; + ellipsis_pos = (is_rtl) ? 0 : sd_size; + } else { + for (int i = glyphs_from; i != glyphs_to; i += glyphs_delta) { + if (!is_rtl) { + width -= sd_glyphs[i].advance * sd_glyphs[i].repeat; + } + if (sd_glyphs[i].count > 0) { + bool above_min_char_threshold = ((is_rtl) ? sd_size - 1 - i : i) >= ell_min_characters; - if (width + (((above_min_char_threshold && add_ellipsis) || enforce_ellipsis) ? ellipsis_width : 0) <= p_width) { - if (cut_per_word && above_min_char_threshold) { - if ((sd_glyphs[i].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT) { + if (width + (((above_min_char_threshold && add_ellipsis) || enforce_ellipsis) ? ellipsis_width : 0) <= p_width) { + if (cut_per_word && above_min_char_threshold) { + if ((sd_glyphs[i].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT) { + last_valid_cut = i; + found = true; + } + } else { last_valid_cut = i; found = true; } - } else { - last_valid_cut = i; - found = true; - } - if (found) { - trim_pos = last_valid_cut; + if (found) { + trim_pos = last_valid_cut; - if (add_ellipsis && (above_min_char_threshold || enforce_ellipsis) && width - ellipsis_width <= p_width) { - ellipsis_pos = trim_pos; + if (add_ellipsis && (above_min_char_threshold || enforce_ellipsis) && width - ellipsis_width <= p_width) { + ellipsis_pos = trim_pos; + } + break; } - break; } } - } - if (is_rtl) { - width -= sd_glyphs[i].advance * sd_glyphs[i].repeat; + if (is_rtl) { + width -= sd_glyphs[i].advance * sd_glyphs[i].repeat; + } } } @@ -4572,7 +4554,7 @@ void TextServerAdvanced::shaped_text_overrun_trim_to_width(const RID &p_shaped_l } } -int64_t TextServerAdvanced::shaped_text_get_trim_pos(const RID &p_shaped) const { +int64_t TextServerAdvanced::_shaped_text_get_trim_pos(const RID &p_shaped) const { ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V_MSG(!sd, -1, "ShapedTextDataAdvanced invalid."); @@ -4580,7 +4562,7 @@ int64_t TextServerAdvanced::shaped_text_get_trim_pos(const RID &p_shaped) const return sd->overrun_trim_data.trim_pos; } -int64_t TextServerAdvanced::shaped_text_get_ellipsis_pos(const RID &p_shaped) const { +int64_t TextServerAdvanced::_shaped_text_get_ellipsis_pos(const RID &p_shaped) const { ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V_MSG(!sd, -1, "ShapedTextDataAdvanced invalid."); @@ -4588,7 +4570,7 @@ int64_t TextServerAdvanced::shaped_text_get_ellipsis_pos(const RID &p_shaped) co return sd->overrun_trim_data.ellipsis_pos; } -const Glyph *TextServerAdvanced::shaped_text_get_ellipsis_glyphs(const RID &p_shaped) const { +const Glyph *TextServerAdvanced::_shaped_text_get_ellipsis_glyphs(const RID &p_shaped) const { ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V_MSG(!sd, nullptr, "ShapedTextDataAdvanced invalid."); @@ -4596,7 +4578,7 @@ const Glyph *TextServerAdvanced::shaped_text_get_ellipsis_glyphs(const RID &p_sh return sd->overrun_trim_data.ellipsis_glyph_buf.ptr(); } -int64_t TextServerAdvanced::shaped_text_get_ellipsis_glyph_count(const RID &p_shaped) const { +int64_t TextServerAdvanced::_shaped_text_get_ellipsis_glyph_count(const RID &p_shaped) const { ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V_MSG(!sd, 0, "ShapedTextDataAdvanced invalid."); @@ -4604,13 +4586,13 @@ int64_t TextServerAdvanced::shaped_text_get_ellipsis_glyph_count(const RID &p_sh return sd->overrun_trim_data.ellipsis_glyph_buf.size(); } -bool TextServerAdvanced::shaped_text_update_breaks(const RID &p_shaped) { +bool TextServerAdvanced::_shaped_text_update_breaks(const RID &p_shaped) { ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, false); MutexLock lock(sd->mutex); if (!sd->valid) { - shaped_text_shape(p_shaped); + _shaped_text_shape(p_shaped); } if (sd->line_breaks_valid) { @@ -4621,6 +4603,7 @@ bool TextServerAdvanced::shaped_text_update_breaks(const RID &p_shaped) { if (!sd->break_ops_valid) { sd->breaks.clear(); + sd->break_inserts = 0; UErrorCode err = U_ZERO_ERROR; int i = 0; while (i < sd->spans.size()) { @@ -4649,6 +4632,12 @@ bool TextServerAdvanced::shaped_text_update_breaks(const RID &p_shaped) { sd->breaks[pos] = true; } else if ((ubrk_getRuleStatus(bi) >= UBRK_LINE_SOFT) && (ubrk_getRuleStatus(bi) < UBRK_LINE_SOFT_LIMIT)) { sd->breaks[pos] = false; + + int pos_p = pos - 1 - sd->start; + char32_t c = sd->text[pos_p]; + if (pos - sd->start != sd->end && !is_whitespace(c) && (c != 0xfffc)) { + sd->break_inserts++; + } } } } @@ -4658,60 +4647,83 @@ bool TextServerAdvanced::shaped_text_update_breaks(const RID &p_shaped) { sd->break_ops_valid = true; } + Vector<Glyph> glyphs_new; + + bool rewrite = false; + int sd_shift = 0; + int sd_size = sd->glyphs.size(); + Glyph *sd_glyphs = sd->glyphs.ptrw(); + Glyph *sd_glyphs_new = nullptr; + + if (sd->break_inserts > 0) { + glyphs_new.resize(sd->glyphs.size() + sd->break_inserts); + sd_glyphs_new = glyphs_new.ptrw(); + rewrite = true; + } else { + sd_glyphs_new = sd_glyphs; + } + sd->sort_valid = false; sd->glyphs_logical.clear(); - int sd_size = sd->glyphs.size(); const char32_t *ch = sd->text.ptr(); - Glyph *sd_glyphs = sd->glyphs.ptrw(); int c_punct_size = sd->custom_punct.length(); const char32_t *c_punct = sd->custom_punct.ptr(); for (int i = 0; i < sd_size; i++) { + if (rewrite) { + for (int j = 0; j < sd_glyphs[i].count; j++) { + sd_glyphs_new[sd_shift + i + j] = sd_glyphs[i + j]; + } + } if (sd_glyphs[i].count > 0) { char32_t c = ch[sd_glyphs[i].start - sd->start]; if (c == 0xfffc) { + i += (sd_glyphs[i].count - 1); continue; } if (c == 0x0009 || c == 0x000b) { - sd_glyphs[i].flags |= GRAPHEME_IS_TAB; + sd_glyphs_new[sd_shift + i].flags |= GRAPHEME_IS_TAB; } if (is_whitespace(c)) { - sd_glyphs[i].flags |= GRAPHEME_IS_SPACE; + sd_glyphs_new[sd_shift + i].flags |= GRAPHEME_IS_SPACE; } if (c_punct_size == 0) { if (u_ispunct(c) && c != 0x005f) { - sd_glyphs[i].flags |= GRAPHEME_IS_PUNCTUATION; + sd_glyphs_new[sd_shift + i].flags |= GRAPHEME_IS_PUNCTUATION; } } else { for (int j = 0; j < c_punct_size; j++) { if (c_punct[j] == c) { - sd_glyphs[i].flags |= GRAPHEME_IS_PUNCTUATION; + sd_glyphs_new[sd_shift + i].flags |= GRAPHEME_IS_PUNCTUATION; break; } } } if (is_underscore(c)) { - sd_glyphs[i].flags |= GRAPHEME_IS_UNDERSCORE; + sd_glyphs_new[sd_shift + i].flags |= GRAPHEME_IS_UNDERSCORE; } if (sd->breaks.has(sd_glyphs[i].end)) { if (sd->breaks[sd_glyphs[i].end] && (is_linebreak(c))) { - sd_glyphs[i].flags |= GRAPHEME_IS_BREAK_HARD; + sd_glyphs_new[sd_shift + i].flags |= GRAPHEME_IS_BREAK_HARD; } else if (is_whitespace(c)) { - sd_glyphs[i].flags |= GRAPHEME_IS_BREAK_SOFT; + sd_glyphs_new[sd_shift + i].flags |= GRAPHEME_IS_BREAK_SOFT; } else { int count = sd_glyphs[i].count; // Do not add extra space at the end of the line. if (sd_glyphs[i].end == sd->end) { + i += (sd_glyphs[i].count - 1); continue; } // Do not add extra space after existing space. if (sd_glyphs[i].flags & GRAPHEME_IS_RTL) { if ((i + count < sd_size - 1) && ((sd_glyphs[i + count].flags & (GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT)) == (GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT))) { + i += (sd_glyphs[i].count - 1); continue; } } else { - if ((i > 0) && ((sd_glyphs[i - 1].flags & (GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT)) == (GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT))) { + if ((sd_glyphs[i].flags & (GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT)) == (GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT)) { + i += (sd_glyphs[i].count - 1); continue; } } @@ -4724,22 +4736,25 @@ bool TextServerAdvanced::shaped_text_update_breaks(const RID &p_shaped) { gl.flags = GRAPHEME_IS_BREAK_SOFT | GRAPHEME_IS_VIRTUAL | GRAPHEME_IS_SPACE; if (sd_glyphs[i].flags & GRAPHEME_IS_RTL) { gl.flags |= GRAPHEME_IS_RTL; - sd->glyphs.insert(i, gl); // Insert before. + for (int j = sd_glyphs[i].count - 1; j >= 0; j--) { + sd_glyphs_new[sd_shift + i + j + 1] = sd_glyphs_new[sd_shift + i + j]; + } + sd_glyphs_new[sd_shift + i] = gl; } else { - sd->glyphs.insert(i + count, gl); // Insert after. + sd_glyphs_new[sd_shift + i + count] = gl; } - i += count; - - // Update write pointer and size. - sd_size = sd->glyphs.size(); - sd_glyphs = sd->glyphs.ptrw(); - continue; + sd_shift++; + ERR_FAIL_COND_V_MSG(sd_shift > sd->break_inserts, false, "Invalid break insert count!"); } } - i += (sd_glyphs[i].count - 1); } } + ERR_FAIL_COND_V_MSG(sd_shift != sd->break_inserts, false, "Invalid break insert count!"); + + if (sd->break_inserts > 0) { + sd->glyphs = glyphs_new; + } sd->line_breaks_valid = true; @@ -4821,16 +4836,16 @@ _FORCE_INLINE_ int64_t _generate_kashida_justification_opportunies(const String return kashida_pos; } -bool TextServerAdvanced::shaped_text_update_justification_ops(const RID &p_shaped) { +bool TextServerAdvanced::_shaped_text_update_justification_ops(const RID &p_shaped) { ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, false); MutexLock lock(sd->mutex); if (!sd->valid) { - shaped_text_shape(p_shaped); + _shaped_text_shape(p_shaped); } if (!sd->line_breaks_valid) { - shaped_text_update_breaks(p_shaped); + _shaped_text_update_breaks(p_shaped); } if (sd->justification_ops_valid) { @@ -4975,7 +4990,8 @@ bool TextServerAdvanced::shaped_text_update_justification_ops(const RID &p_shape Glyph TextServerAdvanced::_shape_single_glyph(ShapedTextDataAdvanced *p_sd, char32_t p_char, hb_script_t p_script, hb_direction_t p_direction, const RID &p_font, int64_t p_font_size) { hb_font_t *hb_font = _font_get_hb_handle(p_font, p_font_size); - bool subpos = (font_get_subpixel_positioning(p_font) == SUBPIXEL_POSITIONING_ONE_HALF) || (font_get_subpixel_positioning(p_font) == SUBPIXEL_POSITIONING_ONE_QUARTER) || (font_get_subpixel_positioning(p_font) == SUBPIXEL_POSITIONING_AUTO && p_font_size <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE); + double scale = _font_get_scale(p_font, p_font_size); + bool subpos = (scale != 1.0) || (_font_get_subpixel_positioning(p_font) == SUBPIXEL_POSITIONING_ONE_HALF) || (_font_get_subpixel_positioning(p_font) == SUBPIXEL_POSITIONING_ONE_QUARTER) || (_font_get_subpixel_positioning(p_font) == SUBPIXEL_POSITIONING_AUTO && p_font_size <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE); ERR_FAIL_COND_V(hb_font == nullptr, Glyph()); hb_buffer_clear_contents(p_sd->hb_buffer); @@ -5001,25 +5017,24 @@ Glyph TextServerAdvanced::_shape_single_glyph(ShapedTextDataAdvanced *p_sd, char gl.font_size = p_font_size; if (glyph_count > 0) { - double scale = font_get_scale(p_font, p_font_size); if (p_sd->orientation == ORIENTATION_HORIZONTAL) { if (subpos) { - gl.advance = glyph_pos[0].x_advance / (64.0 / scale) + _get_extra_advance(p_font, p_font_size); + gl.advance = (double)glyph_pos[0].x_advance / (64.0 / scale) + _get_extra_advance(p_font, p_font_size); } else { - gl.advance = Math::round(glyph_pos[0].x_advance / (64.0 / scale) + _get_extra_advance(p_font, p_font_size)); + gl.advance = Math::round((double)glyph_pos[0].x_advance / (64.0 / scale) + _get_extra_advance(p_font, p_font_size)); } } else { - gl.advance = -Math::round(glyph_pos[0].y_advance / (64.0 / scale)); + gl.advance = -Math::round((double)glyph_pos[0].y_advance / (64.0 / scale)); } gl.count = 1; gl.index = glyph_info[0].codepoint; if (subpos) { - gl.x_off = glyph_pos[0].x_offset / (64.0 / scale); + gl.x_off = (double)glyph_pos[0].x_offset / (64.0 / scale); } else { - gl.x_off = Math::round(glyph_pos[0].x_offset / (64.0 / scale)); + gl.x_off = Math::round((double)glyph_pos[0].x_offset / (64.0 / scale)); } - gl.y_off = -Math::round(glyph_pos[0].y_offset / (64.0 / scale)); + gl.y_off = -Math::round((double)glyph_pos[0].y_offset / (64.0 / scale)); if ((glyph_info[0].codepoint != 0) || !u_isgraph(p_char)) { gl.flags |= GRAPHEME_IS_VALID; @@ -5036,7 +5051,7 @@ _FORCE_INLINE_ void TextServerAdvanced::_add_featuers(const Dictionary &p_source if (value >= 0) { hb_feature_t feature; if (keys[i].get_type() == Variant::STRING) { - feature.tag = name_to_tag(keys[i]); + feature.tag = _name_to_tag(keys[i]); } else { feature.tag = keys[i]; } @@ -5069,6 +5084,8 @@ void TextServerAdvanced::_shape_run(ShapedTextDataAdvanced *p_sd, int64_t p_star p_sd->ascent = MAX(p_sd->ascent, get_hex_code_box_size(fs, gl.index).y); } else { gl.advance = get_hex_code_box_size(fs, gl.index).y; + gl.y_off = get_hex_code_box_size(fs, gl.index).y; + gl.x_off = -Math::round(get_hex_code_box_size(fs, gl.index).x * 0.5); p_sd->ascent = MAX(p_sd->ascent, Math::round(get_hex_code_box_size(fs, gl.index).x * 0.5)); p_sd->descent = MAX(p_sd->descent, Math::round(get_hex_code_box_size(fs, gl.index).x * 0.5)); } @@ -5087,12 +5104,12 @@ void TextServerAdvanced::_shape_run(ShapedTextDataAdvanced *p_sd, int64_t p_star Vector2i fss = _get_size(fd, fs); hb_font_t *hb_font = _font_get_hb_handle(f, fs); - double scale = font_get_scale(f, fs); + double scale = _font_get_scale(f, fs); double sp_sp = p_sd->extra_spacing[SPACING_SPACE]; double sp_gl = p_sd->extra_spacing[SPACING_GLYPH]; bool last_run = (p_sd->end == p_end); double ea = _get_extra_advance(f, fs); - bool subpos = (font_get_subpixel_positioning(f) == SUBPIXEL_POSITIONING_ONE_HALF) || (font_get_subpixel_positioning(f) == SUBPIXEL_POSITIONING_ONE_QUARTER) || (font_get_subpixel_positioning(f) == SUBPIXEL_POSITIONING_AUTO && fs <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE); + bool subpos = (scale != 1.0) || (_font_get_subpixel_positioning(f) == SUBPIXEL_POSITIONING_ONE_HALF) || (_font_get_subpixel_positioning(f) == SUBPIXEL_POSITIONING_ONE_QUARTER) || (_font_get_subpixel_positioning(f) == SUBPIXEL_POSITIONING_AUTO && fs <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE); ERR_FAIL_COND(hb_font == nullptr); hb_buffer_clear_contents(p_sd->hb_buffer); @@ -5120,7 +5137,7 @@ void TextServerAdvanced::_shape_run(ShapedTextDataAdvanced *p_sd, int64_t p_star 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; - _add_featuers(font_get_opentype_feature_overrides(f), ftrs); + _add_featuers(_font_get_opentype_feature_overrides(f), ftrs); _add_featuers(p_sd->spans[p_span].features, ftrs); hb_shape(hb_font, p_sd->hb_buffer, ftrs.is_empty() ? nullptr : &ftrs[0], ftrs.size()); @@ -5193,19 +5210,19 @@ void TextServerAdvanced::_shape_run(ShapedTextDataAdvanced *p_sd, int64_t p_star _ensure_glyph(fd, fss, gl.index | mod); if (p_sd->orientation == ORIENTATION_HORIZONTAL) { if (subpos) { - gl.advance = glyph_pos[i].x_advance / (64.0 / scale) + ea; + gl.advance = (double)glyph_pos[i].x_advance / (64.0 / scale) + ea; } else { - gl.advance = Math::round(glyph_pos[i].x_advance / (64.0 / scale) + ea); + gl.advance = Math::round((double)glyph_pos[i].x_advance / (64.0 / scale) + ea); } } else { - gl.advance = -Math::round(glyph_pos[i].y_advance / (64.0 / scale)); + gl.advance = -Math::round((double)glyph_pos[i].y_advance / (64.0 / scale)); } if (subpos) { - gl.x_off = glyph_pos[i].x_offset / (64.0 / scale); + gl.x_off = (double)glyph_pos[i].x_offset / (64.0 / scale); } else { - gl.x_off = Math::round(glyph_pos[i].x_offset / (64.0 / scale)); + gl.x_off = Math::round((double)glyph_pos[i].x_offset / (64.0 / scale)); } - gl.y_off = -Math::round(glyph_pos[i].y_offset / (64.0 / scale)); + gl.y_off = -Math::round((double)glyph_pos[i].y_offset / (64.0 / scale)); } if (!last_run || i < glyph_count - 1) { // Do not add extra spacing to the last glyph of the string. @@ -5251,7 +5268,7 @@ void TextServerAdvanced::_shape_run(ShapedTextDataAdvanced *p_sd, int64_t p_star p_sd->ascent = MAX(p_sd->ascent, -w[i + j].y_off); p_sd->descent = MAX(p_sd->descent, w[i + j].y_off); } else { - double gla = Math::round(font_get_glyph_advance(f, fs, w[i + j].index).x * 0.5); + double gla = Math::round(_font_get_glyph_advance(f, fs, w[i + j].index).x * 0.5); p_sd->ascent = MAX(p_sd->ascent, gla); p_sd->descent = MAX(p_sd->descent, gla); } @@ -5274,14 +5291,14 @@ void TextServerAdvanced::_shape_run(ShapedTextDataAdvanced *p_sd, int64_t p_star 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); } - p_sd->ascent = MAX(p_sd->ascent, font_get_ascent(f, fs)); - p_sd->descent = MAX(p_sd->descent, font_get_descent(f, fs)); - p_sd->upos = MAX(p_sd->upos, font_get_underline_position(f, fs)); - p_sd->uthk = MAX(p_sd->uthk, font_get_underline_thickness(f, fs)); + p_sd->ascent = MAX(p_sd->ascent, _font_get_ascent(f, fs)); + p_sd->descent = MAX(p_sd->descent, _font_get_descent(f, fs)); + p_sd->upos = MAX(p_sd->upos, _font_get_underline_position(f, fs)); + p_sd->uthk = MAX(p_sd->uthk, _font_get_underline_thickness(f, fs)); } } -bool TextServerAdvanced::shaped_text_shape(const RID &p_shaped) { +bool TextServerAdvanced::_shaped_text_shape(const RID &p_shaped) { ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, false); @@ -5292,7 +5309,7 @@ bool TextServerAdvanced::shaped_text_shape(const RID &p_shaped) { invalidate(sd, false); if (sd->parent != RID()) { - shaped_text_shape(sd->parent); + _shaped_text_shape(sd->parent); ShapedTextDataAdvanced *parent_sd = shaped_owner.get_or_null(sd->parent); ERR_FAIL_COND_V(!parent_sd->valid, false); ERR_FAIL_COND_V(!_shape_substr(sd, parent_sd, sd->start, sd->end - sd->start), false); @@ -5392,7 +5409,7 @@ bool TextServerAdvanced::shaped_text_shape(const RID &p_shaped) { 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); + String script_code = String(scr_buffer); int spn_from = (is_rtl) ? 0 : sd->spans.size() - 1; int spn_to = (is_rtl) ? sd->spans.size() : -1; @@ -5428,9 +5445,12 @@ bool TextServerAdvanced::shaped_text_shape(const RID &p_shaped) { Array fonts_scr_only; Array fonts_no_match; int font_count = span.fonts.size(); - for (int l = 0; l < font_count; l++) { - if (font_is_script_supported(span.fonts[l], script)) { - if (font_is_language_supported(span.fonts[l], span.language)) { + if (font_count > 0) { + fonts.push_back(sd->spans[k].fonts[0]); + } + for (int l = 1; l < font_count; l++) { + if (_font_is_script_supported(span.fonts[l], script_code)) { + if (_font_is_language_supported(span.fonts[l], span.language)) { fonts.push_back(sd->spans[k].fonts[l]); } else { fonts_scr_only.push_back(sd->spans[k].fonts[l]); @@ -5454,7 +5474,7 @@ bool TextServerAdvanced::shaped_text_shape(const RID &p_shaped) { return sd->valid; } -bool TextServerAdvanced::shaped_text_is_ready(const RID &p_shaped) const { +bool TextServerAdvanced::_shaped_text_is_ready(const RID &p_shaped) const { const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, false); @@ -5462,35 +5482,35 @@ bool TextServerAdvanced::shaped_text_is_ready(const RID &p_shaped) const { return sd->valid; } -const Glyph *TextServerAdvanced::shaped_text_get_glyphs(const RID &p_shaped) const { +const Glyph *TextServerAdvanced::_shaped_text_get_glyphs(const RID &p_shaped) const { const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, nullptr); MutexLock lock(sd->mutex); if (!sd->valid) { - const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped); } return sd->glyphs.ptr(); } -int64_t TextServerAdvanced::shaped_text_get_glyph_count(const RID &p_shaped) const { +int64_t TextServerAdvanced::_shaped_text_get_glyph_count(const RID &p_shaped) const { const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, 0); MutexLock lock(sd->mutex); if (!sd->valid) { - const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped); } return sd->glyphs.size(); } -const Glyph *TextServerAdvanced::shaped_text_sort_logical(const RID &p_shaped) { +const Glyph *TextServerAdvanced::_shaped_text_sort_logical(const RID &p_shaped) { ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, nullptr); MutexLock lock(sd->mutex); if (!sd->valid) { - const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped); } if (!sd->sort_valid) { @@ -5502,7 +5522,7 @@ const Glyph *TextServerAdvanced::shaped_text_sort_logical(const RID &p_shaped) { return sd->glyphs_logical.ptr(); } -Vector2i TextServerAdvanced::shaped_text_get_range(const RID &p_shaped) const { +Vector2i TextServerAdvanced::_shaped_text_get_range(const RID &p_shaped) const { const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, Vector2i()); @@ -5510,7 +5530,7 @@ Vector2i TextServerAdvanced::shaped_text_get_range(const RID &p_shaped) const { return Vector2(sd->start, sd->end); } -Array TextServerAdvanced::shaped_text_get_objects(const RID &p_shaped) const { +Array TextServerAdvanced::_shaped_text_get_objects(const RID &p_shaped) const { Array ret; const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, ret); @@ -5523,25 +5543,25 @@ Array TextServerAdvanced::shaped_text_get_objects(const RID &p_shaped) const { return ret; } -Rect2 TextServerAdvanced::shaped_text_get_object_rect(const RID &p_shaped, const Variant &p_key) const { +Rect2 TextServerAdvanced::_shaped_text_get_object_rect(const RID &p_shaped, const Variant &p_key) const { const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, Rect2()); MutexLock lock(sd->mutex); ERR_FAIL_COND_V(!sd->objects.has(p_key), Rect2()); if (!sd->valid) { - const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped); } return sd->objects[p_key].rect; } -Size2 TextServerAdvanced::shaped_text_get_size(const RID &p_shaped) const { +Size2 TextServerAdvanced::_shaped_text_get_size(const RID &p_shaped) const { const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, Size2()); MutexLock lock(sd->mutex); if (!sd->valid) { - const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped); } if (sd->orientation == TextServer::ORIENTATION_HORIZONTAL) { return Size2((sd->text_trimmed ? sd->width_trimmed : sd->width), sd->ascent + sd->descent + sd->extra_spacing[SPACING_TOP] + sd->extra_spacing[SPACING_BOTTOM]).ceil(); @@ -5550,58 +5570,58 @@ Size2 TextServerAdvanced::shaped_text_get_size(const RID &p_shaped) const { } } -double TextServerAdvanced::shaped_text_get_ascent(const RID &p_shaped) const { +double TextServerAdvanced::_shaped_text_get_ascent(const RID &p_shaped) const { const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, 0.0); MutexLock lock(sd->mutex); if (!sd->valid) { - const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped); } return sd->ascent + sd->extra_spacing[SPACING_TOP]; } -double TextServerAdvanced::shaped_text_get_descent(const RID &p_shaped) const { +double TextServerAdvanced::_shaped_text_get_descent(const RID &p_shaped) const { const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, 0.0); MutexLock lock(sd->mutex); if (!sd->valid) { - const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped); } return sd->descent + sd->extra_spacing[SPACING_BOTTOM]; } -double TextServerAdvanced::shaped_text_get_width(const RID &p_shaped) const { +double TextServerAdvanced::_shaped_text_get_width(const RID &p_shaped) const { const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, 0.0); MutexLock lock(sd->mutex); if (!sd->valid) { - const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped); } return Math::ceil(sd->text_trimmed ? sd->width_trimmed : sd->width); } -double TextServerAdvanced::shaped_text_get_underline_position(const RID &p_shaped) const { +double TextServerAdvanced::_shaped_text_get_underline_position(const RID &p_shaped) const { const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, 0.0); MutexLock lock(sd->mutex); if (!sd->valid) { - const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped); } return sd->upos; } -double TextServerAdvanced::shaped_text_get_underline_thickness(const RID &p_shaped) const { +double TextServerAdvanced::_shaped_text_get_underline_thickness(const RID &p_shaped) const { const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, 0.0); MutexLock lock(sd->mutex); if (!sd->valid) { - const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); + const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped); } return sd->uthk; @@ -5782,7 +5802,7 @@ void TextServerAdvanced::_insert_num_systems_lang() { } } -String TextServerAdvanced::format_number(const String &p_string, const String &p_language) const { +String TextServerAdvanced::_format_number(const String &p_string, const String &p_language) const { const StringName lang = (p_language.is_empty()) ? TranslationServer::get_singleton()->get_tool_locale() : p_language; String res = p_string; @@ -5807,7 +5827,7 @@ String TextServerAdvanced::format_number(const String &p_string, const String &p return res; } -String TextServerAdvanced::parse_number(const String &p_string, const String &p_language) const { +String TextServerAdvanced::_parse_number(const String &p_string, const String &p_language) const { const StringName lang = (p_language.is_empty()) ? TranslationServer::get_singleton()->get_tool_locale() : p_language; String res = p_string; @@ -5835,7 +5855,7 @@ String TextServerAdvanced::parse_number(const String &p_string, const String &p_ return res; } -String TextServerAdvanced::percent_sign(const String &p_language) const { +String TextServerAdvanced::_percent_sign(const String &p_language) const { const StringName lang = (p_language.is_empty()) ? TranslationServer::get_singleton()->get_tool_locale() : p_language; for (int i = 0; i < num_systems.size(); i++) { @@ -5849,9 +5869,9 @@ String TextServerAdvanced::percent_sign(const String &p_language) const { return "%"; } -int TextServerAdvanced::is_confusable(const String &p_string, const PackedStringArray &p_dict) const { +int64_t TextServerAdvanced::_is_confusable(const String &p_string, const PackedStringArray &p_dict) const { UErrorCode status = U_ZERO_ERROR; - int match_index = -1; + int64_t match_index = -1; Char16String utf16 = p_string.utf16(); Vector<UChar *> skeletons; @@ -5889,7 +5909,7 @@ int TextServerAdvanced::is_confusable(const String &p_string, const PackedString return match_index; } -bool TextServerAdvanced::spoof_check(const String &p_string) const { +bool TextServerAdvanced::_spoof_check(const String &p_string) const { UErrorCode status = U_ZERO_ERROR; Char16String utf16 = p_string.utf16(); @@ -5911,7 +5931,7 @@ bool TextServerAdvanced::spoof_check(const String &p_string) const { return (bitmask != 0); } -String TextServerAdvanced::strip_diacritics(const String &p_string) const { +String TextServerAdvanced::_strip_diacritics(const String &p_string) const { UErrorCode err = U_ZERO_ERROR; // Get NFKD normalizer singleton. @@ -5944,7 +5964,7 @@ String TextServerAdvanced::strip_diacritics(const String &p_string) const { return result; } -String TextServerAdvanced::string_to_upper(const String &p_string, const String &p_language) const { +String TextServerAdvanced::_string_to_upper(const String &p_string, const String &p_language) const { const String lang = (p_language.is_empty()) ? TranslationServer::get_singleton()->get_tool_locale() : p_language; // Convert to UTF-16. @@ -5963,7 +5983,7 @@ String TextServerAdvanced::string_to_upper(const String &p_string, const String return String::utf16(upper.ptr(), len); } -String TextServerAdvanced::string_to_lower(const String &p_string, const String &p_language) const { +String TextServerAdvanced::_string_to_lower(const String &p_string, const String &p_language) const { const String lang = (p_language.is_empty()) ? TranslationServer::get_singleton()->get_tool_locale() : p_language; // Convert to UTF-16. Char16String utf16 = p_string.utf16(); @@ -5981,7 +6001,7 @@ String TextServerAdvanced::string_to_lower(const String &p_string, const String return String::utf16(lower.ptr(), len); } -PackedInt32Array TextServerAdvanced::string_get_word_breaks(const String &p_string, const String &p_language) const { +PackedInt32Array TextServerAdvanced::_string_get_word_breaks(const String &p_string, const String &p_language) const { const String lang = (p_language.is_empty()) ? TranslationServer::get_singleton()->get_tool_locale() : p_language; // Convert to UTF-16. Char16String utf16 = p_string.utf16(); @@ -6029,7 +6049,7 @@ PackedInt32Array TextServerAdvanced::string_get_word_breaks(const String &p_stri return ret; } -bool TextServerAdvanced::is_valid_identifier(const String &p_string) const { +bool TextServerAdvanced::_is_valid_identifier(const String &p_string) const { enum UAX31SequenceStatus { SEQ_NOT_STARTED, SEQ_STARTED, @@ -6050,7 +6070,7 @@ bool TextServerAdvanced::is_valid_identifier(const String &p_string) const { if (U_FAILURE(err)) { return false; // Failed to load normalizer. } - bool isnurom = unorm2_isNormalized(norm_c, utf16.ptr(), utf16.length(), &err); + bool isnurom = unorm2_isNormalized(norm_c, utf16.get_data(), utf16.length(), &err); if (U_FAILURE(err) || !isnurom) { return false; // Do not conform to Normalization Form C. } diff --git a/modules/text_server_adv/text_server_adv.h b/modules/text_server_adv/text_server_adv.h index 1db95d153b..10fe3c2316 100644 --- a/modules/text_server_adv/text_server_adv.h +++ b/modules/text_server_adv/text_server_adv.h @@ -42,6 +42,7 @@ #include <godot_cpp/godot.hpp> #include <godot_cpp/core/class_db.hpp> +#include <godot_cpp/core/ext_wrappers.gen.inc> #include <godot_cpp/core/mutex_lock.hpp> #include <godot_cpp/variant/array.hpp> @@ -52,6 +53,7 @@ #include <godot_cpp/variant/rect2.hpp> #include <godot_cpp/variant/rid.hpp> #include <godot_cpp/variant/string.hpp> +#include <godot_cpp/variant/typed_array.hpp> #include <godot_cpp/variant/vector2.hpp> #include <godot_cpp/variant/vector2i.hpp> @@ -78,13 +80,15 @@ using namespace godot; #else // Headers for building as built-in module. +#include "servers/text/text_server_extension.h" + +#include "core/extension/ext_wrappers.gen.inc" #include "core/object/worker_thread_pool.h" #include "core/templates/hash_map.h" #include "core/templates/rid_owner.h" #include "scene/resources/texture.h" -#include "servers/text/text_server_extension.h" -#include "modules/modules_enabled.gen.h" // For freetype, msdfgen. +#include "modules/modules_enabled.gen.h" // For freetype, msdfgen, svg. #endif @@ -113,6 +117,7 @@ using namespace godot; #include FT_ADVANCES_H #include FT_MULTIPLE_MASTERS_H #include FT_BBOX_H +#include FT_MODULE_H #include FT_CONFIG_OPTIONS_H #if !defined(FT_CONFIG_OPTION_USE_BROTLI) && !defined(_MSC_VER) #warning FreeType is configured without Brotli support, built-in fonts will not be available. @@ -164,20 +169,86 @@ class TextServerAdvanced : public TextServerExtension { const int rect_range = 1; - struct FontTexture { + struct FontTexturePosition { + int32_t index = -1; + int32_t x = 0; + int32_t y = 0; + + FontTexturePosition() {} + FontTexturePosition(int32_t p_id, int32_t p_x, int32_t p_y) : + index(p_id), x(p_x), y(p_y) {} + }; + + struct Shelf { + int32_t x = 0; + int32_t y = 0; + int32_t w = 0; + int32_t h = 0; + + FontTexturePosition alloc_shelf(int32_t p_id, int32_t p_w, int32_t p_h) { + if (p_w > w || p_h > h) { + return FontTexturePosition(-1, 0, 0); + } + int32_t xx = x; + x += p_w; + w -= p_w; + return FontTexturePosition(p_id, xx, y); + } + + Shelf() {} + Shelf(int32_t p_x, int32_t p_y, int32_t p_w, int32_t p_h) : + x(p_x), y(p_y), w(p_w), h(p_h) {} + }; + + struct ShelfPackTexture { + int32_t texture_w = 1024; + int32_t texture_h = 1024; + Image::Format format; PackedByteArray imgdata; - int texture_w = 0; - int texture_h = 0; - PackedInt32Array offsets; Ref<ImageTexture> texture; bool dirty = true; - }; - struct FontTexturePosition { - int index = 0; - int x = 0; - int y = 0; + List<Shelf> shelves; + + FontTexturePosition pack_rect(int32_t p_id, int32_t p_h, int32_t p_w) { + int32_t y = 0; + int32_t waste = 0; + Shelf *best_shelf = nullptr; + int32_t best_waste = std::numeric_limits<std::int32_t>::max(); + + for (Shelf &E : shelves) { + y += E.h; + if (p_w > E.w) { + continue; + } + if (p_h == E.h) { + return E.alloc_shelf(p_id, p_w, p_h); + } + if (p_h > E.h) { + continue; + } + if (p_h < E.h) { + waste = (E.h - p_h) * p_w; + if (waste < best_waste) { + best_waste = waste; + best_shelf = &E; + } + } + } + if (best_shelf) { + return best_shelf->alloc_shelf(p_id, p_w, p_h); + } + if (p_h <= (texture_h - y) && p_w <= texture_w) { + List<Shelf>::Element *E = shelves.push_back(Shelf(0, y, texture_w, p_h)); + return E->get().alloc_shelf(p_id, p_w, p_h); + } + return FontTexturePosition(-1, 0, 0); + } + + ShelfPackTexture() {} + ShelfPackTexture(int32_t p_w, int32_t p_h) : + texture_w(p_w), texture_h(p_h) {} }; struct FontGlyph { @@ -198,7 +269,7 @@ class TextServerAdvanced : public TextServerExtension { Vector2i size; - Vector<FontTexture> textures; + Vector<ShelfPackTexture> textures; HashMap<int32_t, FontGlyph> glyph_map; HashMap<Vector2i, Vector2> kerning_map; hb_font_t *hb_handle = nullptr; @@ -380,6 +451,7 @@ class TextServerAdvanced : public TextServerExtension { HashMap<int, bool> jstops; HashMap<int, bool> breaks; + int break_inserts = 0; bool break_ops_valid = false; bool js_ops_valid = false; @@ -461,258 +533,259 @@ protected: void invalidate(ShapedTextDataAdvanced *p_shaped, bool p_text = false); public: - virtual bool has_feature(Feature p_feature) const override; - virtual String get_name() const override; - virtual int64_t get_features() const override; + MODBIND1RC(bool, has_feature, Feature); + MODBIND0RC(String, get_name); + MODBIND0RC(int64_t, get_features); - virtual void free_rid(const RID &p_rid) override; - virtual bool has(const RID &p_rid) override; - virtual bool load_support_data(const String &p_filename) override; + MODBIND1(free_rid, const RID &); + MODBIND1R(bool, has, const RID &); + MODBIND1R(bool, load_support_data, const String &); - virtual String get_support_data_filename() const override; - virtual String get_support_data_info() const override; - virtual bool save_support_data(const String &p_filename) const override; + MODBIND0RC(String, get_support_data_filename); + MODBIND0RC(String, get_support_data_info); + MODBIND1RC(bool, save_support_data, const String &); - virtual bool is_locale_right_to_left(const String &p_locale) const override; + MODBIND1RC(bool, is_locale_right_to_left, const String &); - virtual int64_t name_to_tag(const String &p_name) const override; - virtual String tag_to_name(int64_t p_tag) const override; + MODBIND1RC(int64_t, name_to_tag, const String &); + MODBIND1RC(String, tag_to_name, int64_t); /* Font interface */ - virtual RID create_font() override; - virtual void font_set_data(const RID &p_font_rid, const PackedByteArray &p_data) override; - virtual void font_set_data_ptr(const RID &p_font_rid, const uint8_t *p_data_ptr, int64_t p_data_size) override; + MODBIND0R(RID, create_font); + + MODBIND2(font_set_data, const RID &, const PackedByteArray &); + MODBIND3(font_set_data_ptr, const RID &, const uint8_t *, int64_t); - virtual void font_set_face_index(const RID &p_font_rid, int64_t p_index) override; - virtual int64_t font_get_face_index(const RID &p_font_rid) const override; + MODBIND2(font_set_face_index, const RID &, int64_t); + MODBIND1RC(int64_t, font_get_face_index, const RID &); - virtual int64_t font_get_face_count(const RID &p_font_rid) const override; + MODBIND1RC(int64_t, font_get_face_count, const RID &); - virtual void font_set_style(const RID &p_font_rid, BitField<FontStyle> p_style) override; - virtual BitField<FontStyle> font_get_style(const RID &p_font_rid) const override; + MODBIND2(font_set_style, const RID &, BitField<FontStyle>); + MODBIND1RC(BitField<FontStyle>, font_get_style, const RID &); - virtual void font_set_style_name(const RID &p_font_rid, const String &p_name) override; - virtual String font_get_style_name(const RID &p_font_rid) const override; + MODBIND2(font_set_style_name, const RID &, const String &); + MODBIND1RC(String, font_get_style_name, const RID &); - virtual void font_set_name(const RID &p_font_rid, const String &p_name) override; - virtual String font_get_name(const RID &p_font_rid) const override; + MODBIND2(font_set_name, const RID &, const String &); + MODBIND1RC(String, font_get_name, const RID &); - virtual void font_set_antialiasing(RID p_font_rid, TextServer::FontAntialiasing p_antialiasing) override; - virtual TextServer::FontAntialiasing font_get_antialiasing(RID p_font_rid) const override; + MODBIND2(font_set_antialiasing, const RID &, TextServer::FontAntialiasing); + MODBIND1RC(TextServer::FontAntialiasing, font_get_antialiasing, const RID &); - virtual void font_set_generate_mipmaps(const RID &p_font_rid, bool p_generate_mipmaps) override; - virtual bool font_get_generate_mipmaps(const RID &p_font_rid) const override; + MODBIND2(font_set_generate_mipmaps, const RID &, bool); + MODBIND1RC(bool, font_get_generate_mipmaps, const RID &); - virtual void font_set_multichannel_signed_distance_field(const RID &p_font_rid, bool p_msdf) override; - virtual bool font_is_multichannel_signed_distance_field(const RID &p_font_rid) const override; + MODBIND2(font_set_multichannel_signed_distance_field, const RID &, bool); + MODBIND1RC(bool, font_is_multichannel_signed_distance_field, const RID &); - virtual void font_set_msdf_pixel_range(const RID &p_font_rid, int64_t p_msdf_pixel_range) override; - virtual int64_t font_get_msdf_pixel_range(const RID &p_font_rid) const override; + MODBIND2(font_set_msdf_pixel_range, const RID &, int64_t); + MODBIND1RC(int64_t, font_get_msdf_pixel_range, const RID &); - virtual void font_set_msdf_size(const RID &p_font_rid, int64_t p_msdf_size) override; - virtual int64_t font_get_msdf_size(const RID &p_font_rid) const override; + MODBIND2(font_set_msdf_size, const RID &, int64_t); + MODBIND1RC(int64_t, font_get_msdf_size, const RID &); - virtual void font_set_fixed_size(const RID &p_font_rid, int64_t p_fixed_size) override; - virtual int64_t font_get_fixed_size(const RID &p_font_rid) const override; + MODBIND2(font_set_fixed_size, const RID &, int64_t); + MODBIND1RC(int64_t, font_get_fixed_size, const RID &); - virtual void font_set_force_autohinter(const RID &p_font_rid, bool p_force_autohinter) override; - virtual bool font_is_force_autohinter(const RID &p_font_rid) const override; + MODBIND2(font_set_force_autohinter, const RID &, bool); + MODBIND1RC(bool, font_is_force_autohinter, const RID &); - virtual void font_set_subpixel_positioning(const RID &p_font_rid, SubpixelPositioning p_subpixel) override; - virtual SubpixelPositioning font_get_subpixel_positioning(const RID &p_font_rid) const override; + MODBIND2(font_set_subpixel_positioning, const RID &, SubpixelPositioning); + MODBIND1RC(SubpixelPositioning, font_get_subpixel_positioning, const RID &); - virtual void font_set_embolden(const RID &p_font_rid, double p_strength) override; - virtual double font_get_embolden(const RID &p_font_rid) const override; + MODBIND2(font_set_embolden, const RID &, double); + MODBIND1RC(double, font_get_embolden, const RID &); - virtual void font_set_transform(const RID &p_font_rid, const Transform2D &p_transform) override; - virtual Transform2D font_get_transform(const RID &p_font_rid) const override; + MODBIND2(font_set_transform, const RID &, const Transform2D &); + MODBIND1RC(Transform2D, font_get_transform, const RID &); - virtual void font_set_variation_coordinates(const RID &p_font_rid, const Dictionary &p_variation_coordinates) override; - virtual Dictionary font_get_variation_coordinates(const RID &p_font_rid) const override; + MODBIND2(font_set_variation_coordinates, const RID &, const Dictionary &); + MODBIND1RC(Dictionary, font_get_variation_coordinates, const RID &); - virtual void font_set_hinting(const RID &p_font_rid, TextServer::Hinting p_hinting) override; - virtual TextServer::Hinting font_get_hinting(const RID &p_font_rid) const override; + MODBIND2(font_set_hinting, const RID &, TextServer::Hinting); + MODBIND1RC(TextServer::Hinting, font_get_hinting, const RID &); - virtual void font_set_oversampling(const RID &p_font_rid, double p_oversampling) override; - virtual double font_get_oversampling(const RID &p_font_rid) const override; + MODBIND2(font_set_oversampling, const RID &, double); + MODBIND1RC(double, font_get_oversampling, const RID &); - virtual TypedArray<Vector2i> font_get_size_cache_list(const RID &p_font_rid) const override; - virtual void font_clear_size_cache(const RID &p_font_rid) override; - virtual void font_remove_size_cache(const RID &p_font_rid, const Vector2i &p_size) override; + MODBIND1RC(TypedArray<Vector2i>, font_get_size_cache_list, const RID &); + MODBIND1(font_clear_size_cache, const RID &); + MODBIND2(font_remove_size_cache, const RID &, const Vector2i &); - virtual void font_set_ascent(const RID &p_font_rid, int64_t p_size, double p_ascent) override; - virtual double font_get_ascent(const RID &p_font_rid, int64_t p_size) const override; + MODBIND3(font_set_ascent, const RID &, int64_t, double); + MODBIND2RC(double, font_get_ascent, const RID &, int64_t); - virtual void font_set_descent(const RID &p_font_rid, int64_t p_size, double p_descent) override; - virtual double font_get_descent(const RID &p_font_rid, int64_t p_size) const override; + MODBIND3(font_set_descent, const RID &, int64_t, double); + MODBIND2RC(double, font_get_descent, const RID &, int64_t); - virtual void font_set_underline_position(const RID &p_font_rid, int64_t p_size, double p_underline_position) override; - virtual double font_get_underline_position(const RID &p_font_rid, int64_t p_size) const override; + MODBIND3(font_set_underline_position, const RID &, int64_t, double); + MODBIND2RC(double, font_get_underline_position, const RID &, int64_t); - virtual void font_set_underline_thickness(const RID &p_font_rid, int64_t p_size, double p_underline_thickness) override; - virtual double font_get_underline_thickness(const RID &p_font_rid, int64_t p_size) const override; + MODBIND3(font_set_underline_thickness, const RID &, int64_t, double); + MODBIND2RC(double, font_get_underline_thickness, const RID &, int64_t); - virtual void font_set_scale(const RID &p_font_rid, int64_t p_size, double p_scale) override; - virtual double font_get_scale(const RID &p_font_rid, int64_t p_size) const override; + MODBIND3(font_set_scale, const RID &, int64_t, double); + MODBIND2RC(double, font_get_scale, const RID &, int64_t); - virtual int64_t font_get_texture_count(const RID &p_font_rid, const Vector2i &p_size) const override; - virtual void font_clear_textures(const RID &p_font_rid, const Vector2i &p_size) override; - virtual void font_remove_texture(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) override; + MODBIND2RC(int64_t, font_get_texture_count, const RID &, const Vector2i &); + MODBIND2(font_clear_textures, const RID &, const Vector2i &); + MODBIND3(font_remove_texture, const RID &, const Vector2i &, int64_t); - virtual void font_set_texture_image(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index, const Ref<Image> &p_image) override; - virtual Ref<Image> font_get_texture_image(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) const override; + MODBIND4(font_set_texture_image, const RID &, const Vector2i &, int64_t, const Ref<Image> &); + MODBIND3RC(Ref<Image>, font_get_texture_image, const RID &, const Vector2i &, int64_t); - virtual void font_set_texture_offsets(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index, const PackedInt32Array &p_offset) override; - virtual PackedInt32Array font_get_texture_offsets(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) const override; + MODBIND4(font_set_texture_offsets, const RID &, const Vector2i &, int64_t, const PackedInt32Array &); + MODBIND3RC(PackedInt32Array, font_get_texture_offsets, const RID &, const Vector2i &, int64_t); - virtual PackedInt32Array font_get_glyph_list(const RID &p_font_rid, const Vector2i &p_size) const override; - virtual void font_clear_glyphs(const RID &p_font_rid, const Vector2i &p_size) override; - virtual void font_remove_glyph(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) override; + MODBIND2RC(PackedInt32Array, font_get_glyph_list, const RID &, const Vector2i &); + MODBIND2(font_clear_glyphs, const RID &, const Vector2i &); + MODBIND3(font_remove_glyph, const RID &, const Vector2i &, int64_t); - virtual Vector2 font_get_glyph_advance(const RID &p_font_rid, int64_t p_size, int64_t p_glyph) const override; - virtual void font_set_glyph_advance(const RID &p_font_rid, int64_t p_size, int64_t p_glyph, const Vector2 &p_advance) override; + MODBIND3RC(Vector2, font_get_glyph_advance, const RID &, int64_t, int64_t); + MODBIND4(font_set_glyph_advance, const RID &, int64_t, int64_t, const Vector2 &); - virtual Vector2 font_get_glyph_offset(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const override; - virtual void font_set_glyph_offset(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, const Vector2 &p_offset) override; + MODBIND3RC(Vector2, font_get_glyph_offset, const RID &, const Vector2i &, int64_t); + MODBIND4(font_set_glyph_offset, const RID &, const Vector2i &, int64_t, const Vector2 &); - virtual Vector2 font_get_glyph_size(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const override; - virtual void font_set_glyph_size(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, const Vector2 &p_gl_size) override; + MODBIND3RC(Vector2, font_get_glyph_size, const RID &, const Vector2i &, int64_t); + MODBIND4(font_set_glyph_size, const RID &, const Vector2i &, int64_t, const Vector2 &); - virtual Rect2 font_get_glyph_uv_rect(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const override; - virtual void font_set_glyph_uv_rect(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, const Rect2 &p_uv_rect) override; + MODBIND3RC(Rect2, font_get_glyph_uv_rect, const RID &, const Vector2i &, int64_t); + MODBIND4(font_set_glyph_uv_rect, const RID &, const Vector2i &, int64_t, const Rect2 &); - virtual int64_t font_get_glyph_texture_idx(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const override; - virtual void font_set_glyph_texture_idx(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, int64_t p_texture_idx) override; + MODBIND3RC(int64_t, font_get_glyph_texture_idx, const RID &, const Vector2i &, int64_t); + MODBIND4(font_set_glyph_texture_idx, const RID &, const Vector2i &, int64_t, int64_t); - virtual RID font_get_glyph_texture_rid(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const override; - virtual Size2 font_get_glyph_texture_size(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const override; + MODBIND3RC(RID, font_get_glyph_texture_rid, const RID &, const Vector2i &, int64_t); + MODBIND3RC(Size2, font_get_glyph_texture_size, const RID &, const Vector2i &, int64_t); - virtual Dictionary font_get_glyph_contours(const RID &p_font, int64_t p_size, int64_t p_index) const override; + MODBIND3RC(Dictionary, font_get_glyph_contours, const RID &, int64_t, int64_t); - virtual TypedArray<Vector2i> font_get_kerning_list(const RID &p_font_rid, int64_t p_size) const override; - virtual void font_clear_kerning_map(const RID &p_font_rid, int64_t p_size) override; - virtual void font_remove_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair) override; + MODBIND2RC(TypedArray<Vector2i>, font_get_kerning_list, const RID &, int64_t); + MODBIND2(font_clear_kerning_map, const RID &, int64_t); + MODBIND3(font_remove_kerning, const RID &, int64_t, const Vector2i &); - virtual void font_set_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair, const Vector2 &p_kerning) override; - virtual Vector2 font_get_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair) const override; + MODBIND4(font_set_kerning, const RID &, int64_t, const Vector2i &, const Vector2 &); + MODBIND3RC(Vector2, font_get_kerning, const RID &, int64_t, const Vector2i &); - virtual int64_t font_get_glyph_index(const RID &p_font_rid, int64_t p_size, int64_t p_char, int64_t p_variation_selector = 0) const override; + MODBIND4RC(int64_t, font_get_glyph_index, const RID &, int64_t, int64_t, int64_t); - virtual bool font_has_char(const RID &p_font_rid, int64_t p_char) const override; - virtual String font_get_supported_chars(const RID &p_font_rid) const override; + MODBIND2RC(bool, font_has_char, const RID &, int64_t); + MODBIND1RC(String, font_get_supported_chars, const RID &); - virtual void font_render_range(const RID &p_font, const Vector2i &p_size, int64_t p_start, int64_t p_end) override; - virtual void font_render_glyph(const RID &p_font_rid, const Vector2i &p_size, int64_t p_index) override; + MODBIND4(font_render_range, const RID &, const Vector2i &, int64_t, int64_t); + MODBIND3(font_render_glyph, const RID &, const Vector2i &, int64_t); - virtual void font_draw_glyph(const RID &p_font, const RID &p_canvas, int64_t p_size, const Vector2 &p_pos, int64_t p_index, const Color &p_color = Color(1, 1, 1)) const override; - virtual void font_draw_glyph_outline(const RID &p_font, const RID &p_canvas, int64_t p_size, int64_t p_outline_size, const Vector2 &p_pos, int64_t p_index, const Color &p_color = Color(1, 1, 1)) const override; + MODBIND6C(font_draw_glyph, const RID &, const RID &, int64_t, const Vector2 &, int64_t, const Color &); + MODBIND7C(font_draw_glyph_outline, const RID &, const RID &, int64_t, int64_t, const Vector2 &, int64_t, const Color &); - virtual bool font_is_language_supported(const RID &p_font_rid, const String &p_language) const override; - virtual void font_set_language_support_override(const RID &p_font_rid, const String &p_language, bool p_supported) override; - virtual bool font_get_language_support_override(const RID &p_font_rid, const String &p_language) override; - virtual void font_remove_language_support_override(const RID &p_font_rid, const String &p_language) override; - virtual PackedStringArray font_get_language_support_overrides(const RID &p_font_rid) override; + MODBIND2RC(bool, font_is_language_supported, const RID &, const String &); + MODBIND3(font_set_language_support_override, const RID &, const String &, bool); + MODBIND2R(bool, font_get_language_support_override, const RID &, const String &); + MODBIND2(font_remove_language_support_override, const RID &, const String &); + MODBIND1R(PackedStringArray, font_get_language_support_overrides, const RID &); - virtual bool font_is_script_supported(const RID &p_font_rid, const String &p_script) const override; - virtual void font_set_script_support_override(const RID &p_font_rid, const String &p_script, bool p_supported) override; - virtual bool font_get_script_support_override(const RID &p_font_rid, const String &p_script) override; - virtual void font_remove_script_support_override(const RID &p_font_rid, const String &p_script) override; - virtual PackedStringArray font_get_script_support_overrides(const RID &p_font_rid) override; + MODBIND2RC(bool, font_is_script_supported, const RID &, const String &); + MODBIND3(font_set_script_support_override, const RID &, const String &, bool); + MODBIND2R(bool, font_get_script_support_override, const RID &, const String &); + MODBIND2(font_remove_script_support_override, const RID &, const String &); + MODBIND1R(PackedStringArray, font_get_script_support_overrides, const RID &); - virtual void font_set_opentype_feature_overrides(const RID &p_font_rid, const Dictionary &p_overrides) override; - virtual Dictionary font_get_opentype_feature_overrides(const RID &p_font_rid) const override; + MODBIND2(font_set_opentype_feature_overrides, const RID &, const Dictionary &); + MODBIND1RC(Dictionary, font_get_opentype_feature_overrides, const RID &); - virtual Dictionary font_supported_feature_list(const RID &p_font_rid) const override; - virtual Dictionary font_supported_variation_list(const RID &p_font_rid) const override; + MODBIND1RC(Dictionary, font_supported_feature_list, const RID &); + MODBIND1RC(Dictionary, font_supported_variation_list, const RID &); - virtual double font_get_global_oversampling() const override; - virtual void font_set_global_oversampling(double p_oversampling) override; + MODBIND0RC(double, font_get_global_oversampling); + MODBIND1(font_set_global_oversampling, double); /* Shaped text buffer interface */ - virtual RID create_shaped_text(Direction p_direction = DIRECTION_AUTO, Orientation p_orientation = ORIENTATION_HORIZONTAL) override; + MODBIND2R(RID, create_shaped_text, Direction, Orientation); - virtual void shaped_text_clear(const RID &p_shaped) override; + MODBIND1(shaped_text_clear, const RID &); - virtual void shaped_text_set_direction(const RID &p_shaped, Direction p_direction = DIRECTION_AUTO) override; - virtual Direction shaped_text_get_direction(const RID &p_shaped) const override; - virtual Direction shaped_text_get_inferred_direction(const RID &p_shaped) const override; + MODBIND2(shaped_text_set_direction, const RID &, Direction); + MODBIND1RC(Direction, shaped_text_get_direction, const RID &); + MODBIND1RC(Direction, shaped_text_get_inferred_direction, const RID &); - virtual void shaped_text_set_bidi_override(const RID &p_shaped, const Array &p_override) override; + MODBIND2(shaped_text_set_bidi_override, const RID &, const Array &); - virtual void shaped_text_set_custom_punctuation(const RID &p_shaped, const String &p_punct) override; - virtual String shaped_text_get_custom_punctuation(const RID &p_shaped) const override; + MODBIND2(shaped_text_set_custom_punctuation, const RID &, const String &); + MODBIND1RC(String, shaped_text_get_custom_punctuation, const RID &); - virtual void shaped_text_set_orientation(const RID &p_shaped, Orientation p_orientation = ORIENTATION_HORIZONTAL) override; - virtual Orientation shaped_text_get_orientation(const RID &p_shaped) const override; + MODBIND2(shaped_text_set_orientation, const RID &, Orientation); + MODBIND1RC(Orientation, shaped_text_get_orientation, const RID &); - virtual void shaped_text_set_preserve_invalid(const RID &p_shaped, bool p_enabled) override; - virtual bool shaped_text_get_preserve_invalid(const RID &p_shaped) const override; + MODBIND2(shaped_text_set_preserve_invalid, const RID &, bool); + MODBIND1RC(bool, shaped_text_get_preserve_invalid, const RID &); - virtual void shaped_text_set_preserve_control(const RID &p_shaped, bool p_enabled) override; - virtual bool shaped_text_get_preserve_control(const RID &p_shaped) const override; + MODBIND2(shaped_text_set_preserve_control, const RID &, bool); + MODBIND1RC(bool, shaped_text_get_preserve_control, const RID &); - virtual void shaped_text_set_spacing(const RID &p_shaped, SpacingType p_spacing, int64_t p_value) override; - virtual int64_t shaped_text_get_spacing(const RID &p_shaped, SpacingType p_spacing) const override; + MODBIND3(shaped_text_set_spacing, const RID &, SpacingType, int64_t); + MODBIND2RC(int64_t, shaped_text_get_spacing, const RID &, SpacingType); - virtual bool shaped_text_add_string(const RID &p_shaped, const String &p_text, const TypedArray<RID> &p_fonts, int64_t p_size, const Dictionary &p_opentype_features = Dictionary(), const String &p_language = "", const Variant &p_meta = Variant()) override; - virtual bool shaped_text_add_object(const RID &p_shaped, const Variant &p_key, const Size2 &p_size, InlineAlignment p_inline_align = INLINE_ALIGNMENT_CENTER, int64_t p_length = 1) override; - virtual bool shaped_text_resize_object(const RID &p_shaped, const Variant &p_key, const Size2 &p_size, InlineAlignment p_inline_align = INLINE_ALIGNMENT_CENTER) override; + MODBIND7R(bool, shaped_text_add_string, const RID &, const String &, const TypedArray<RID> &, int64_t, const Dictionary &, const String &, const Variant &); + MODBIND5R(bool, shaped_text_add_object, const RID &, const Variant &, const Size2 &, InlineAlignment, int64_t); + MODBIND4R(bool, shaped_text_resize_object, const RID &, const Variant &, const Size2 &, InlineAlignment); - virtual int64_t shaped_get_span_count(const RID &p_shaped) const override; - virtual Variant shaped_get_span_meta(const RID &p_shaped, int64_t p_index) const override; - virtual void shaped_set_span_update_font(const RID &p_shaped, int64_t p_index, const TypedArray<RID> &p_fonts, int64_t p_size, const Dictionary &p_opentype_features = Dictionary()) override; + MODBIND1RC(int64_t, shaped_get_span_count, const RID &); + MODBIND2RC(Variant, shaped_get_span_meta, const RID &, int64_t); + MODBIND5(shaped_set_span_update_font, const RID &, int64_t, const TypedArray<RID> &, int64_t, const Dictionary &); - virtual RID shaped_text_substr(const RID &p_shaped, int64_t p_start, int64_t p_length) const override; - virtual RID shaped_text_get_parent(const RID &p_shaped) const override; + MODBIND3RC(RID, shaped_text_substr, const RID &, int64_t, int64_t); + MODBIND1RC(RID, shaped_text_get_parent, const RID &); - virtual double shaped_text_fit_to_width(const RID &p_shaped, double p_width, BitField<TextServer::JustificationFlag> p_jst_flags = JUSTIFICATION_WORD_BOUND | JUSTIFICATION_KASHIDA) override; - virtual double shaped_text_tab_align(const RID &p_shaped, const PackedFloat32Array &p_tab_stops) override; + MODBIND3R(double, shaped_text_fit_to_width, const RID &, double, BitField<TextServer::JustificationFlag>); + MODBIND2R(double, shaped_text_tab_align, const RID &, const PackedFloat32Array &); - virtual bool shaped_text_shape(const RID &p_shaped) override; - virtual bool shaped_text_update_breaks(const RID &p_shaped) override; - virtual bool shaped_text_update_justification_ops(const RID &p_shaped) override; + MODBIND1R(bool, shaped_text_shape, const RID &); + MODBIND1R(bool, shaped_text_update_breaks, const RID &); + MODBIND1R(bool, shaped_text_update_justification_ops, const RID &); - virtual int64_t shaped_text_get_trim_pos(const RID &p_shaped) const override; - virtual int64_t shaped_text_get_ellipsis_pos(const RID &p_shaped) const override; - virtual const Glyph *shaped_text_get_ellipsis_glyphs(const RID &p_shaped) const override; - virtual int64_t shaped_text_get_ellipsis_glyph_count(const RID &p_shaped) const override; + MODBIND1RC(int64_t, shaped_text_get_trim_pos, const RID &); + MODBIND1RC(int64_t, shaped_text_get_ellipsis_pos, const RID &); + MODBIND1RC(const Glyph *, shaped_text_get_ellipsis_glyphs, const RID &); + MODBIND1RC(int64_t, shaped_text_get_ellipsis_glyph_count, const RID &); - virtual void shaped_text_overrun_trim_to_width(const RID &p_shaped, double p_width, BitField<TextServer::TextOverrunFlag> p_trim_flags) override; + MODBIND3(shaped_text_overrun_trim_to_width, const RID &, double, BitField<TextServer::TextOverrunFlag>); - virtual bool shaped_text_is_ready(const RID &p_shaped) const override; + MODBIND1RC(bool, shaped_text_is_ready, const RID &); - virtual const Glyph *shaped_text_get_glyphs(const RID &p_shaped) const override; - virtual const Glyph *shaped_text_sort_logical(const RID &p_shaped) override; - virtual int64_t shaped_text_get_glyph_count(const RID &p_shaped) const override; + MODBIND1RC(const Glyph *, shaped_text_get_glyphs, const RID &); + MODBIND1R(const Glyph *, shaped_text_sort_logical, const RID &); + MODBIND1RC(int64_t, shaped_text_get_glyph_count, const RID &); - virtual Vector2i shaped_text_get_range(const RID &p_shaped) const override; + MODBIND1RC(Vector2i, shaped_text_get_range, const RID &); - virtual Array shaped_text_get_objects(const RID &p_shaped) const override; - virtual Rect2 shaped_text_get_object_rect(const RID &p_shaped, const Variant &p_key) const override; + MODBIND1RC(Array, shaped_text_get_objects, const RID &); + MODBIND2RC(Rect2, shaped_text_get_object_rect, const RID &, const Variant &); - virtual Size2 shaped_text_get_size(const RID &p_shaped) const override; - virtual double shaped_text_get_ascent(const RID &p_shaped) const override; - virtual double shaped_text_get_descent(const RID &p_shaped) const override; - virtual double shaped_text_get_width(const RID &p_shaped) const override; - virtual double shaped_text_get_underline_position(const RID &p_shaped) const override; - virtual double shaped_text_get_underline_thickness(const RID &p_shaped) const override; + MODBIND1RC(Size2, shaped_text_get_size, const RID &); + MODBIND1RC(double, shaped_text_get_ascent, const RID &); + MODBIND1RC(double, shaped_text_get_descent, const RID &); + MODBIND1RC(double, shaped_text_get_width, const RID &); + MODBIND1RC(double, shaped_text_get_underline_position, const RID &); + MODBIND1RC(double, shaped_text_get_underline_thickness, const RID &); - 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; + MODBIND2RC(String, format_number, const String &, const String &); + MODBIND2RC(String, parse_number, const String &, const String &); + MODBIND1RC(String, percent_sign, const String &); - virtual PackedInt32Array string_get_word_breaks(const String &p_string, const String &p_language = "") const override; + MODBIND2RC(PackedInt32Array, string_get_word_breaks, const String &, const String &); - virtual int is_confusable(const String &p_string, const PackedStringArray &p_dict) const override; - virtual bool spoof_check(const String &p_string) const override; + MODBIND2RC(int64_t, is_confusable, const String &, const PackedStringArray &); + MODBIND1RC(bool, spoof_check, const String &); - virtual String strip_diacritics(const String &p_string) const override; - virtual bool is_valid_identifier(const String &p_string) const override; + MODBIND1RC(String, strip_diacritics, const String &); + MODBIND1RC(bool, is_valid_identifier, const String &); - virtual String string_to_upper(const String &p_string, const String &p_language = "") const override; - virtual String string_to_lower(const String &p_string, const String &p_language = "") const override; + MODBIND2RC(String, string_to_upper, const String &, const String &); + MODBIND2RC(String, string_to_lower, const String &, const String &); TextServerAdvanced(); ~TextServerAdvanced(); diff --git a/modules/text_server_adv/thorvg_bounds_iterator.cpp b/modules/text_server_adv/thorvg_bounds_iterator.cpp new file mode 100644 index 0000000000..54a6136134 --- /dev/null +++ b/modules/text_server_adv/thorvg_bounds_iterator.cpp @@ -0,0 +1,70 @@ +/*************************************************************************/ +/* thorvg_bounds_iterator.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 GDEXTENSION +// Headers for building as GDExtension plug-in. + +#include <godot_cpp/godot.hpp> + +using namespace godot; + +#else +// Headers for building as built-in module. + +#include "core/typedefs.h" + +#include "modules/modules_enabled.gen.h" // For svg. +#endif + +#ifdef MODULE_SVG_ENABLED + +#include "thorvg_bounds_iterator.h" + +#include <tvgIteratorAccessor.h> +#include <tvgPaint.h> + +// This function uses private ThorVG API to get bounding box of top level children elements. + +void tvg_get_bounds(tvg::Picture *p_picture, float &r_min_x, float &r_min_y, float &r_max_x, float &r_max_y) { + tvg::IteratorAccessor itrAccessor; + if (tvg::Iterator *it = itrAccessor.iterator(p_picture)) { + while (const tvg::Paint *child = it->next()) { + float x = 0, y = 0, w = 0, h = 0; + child->bounds(&x, &y, &w, &h, true); + r_min_x = MIN(x, r_min_x); + r_min_y = MIN(y, r_min_y); + r_max_x = MAX(x + w, r_max_x); + r_max_y = MAX(y + h, r_max_y); + } + delete (it); + } +} + +#endif // MODULE_SVG_ENABLED diff --git a/modules/text_server_adv/thorvg_bounds_iterator.h b/modules/text_server_adv/thorvg_bounds_iterator.h new file mode 100644 index 0000000000..e54e30eaa2 --- /dev/null +++ b/modules/text_server_adv/thorvg_bounds_iterator.h @@ -0,0 +1,58 @@ +/*************************************************************************/ +/* thorvg_bounds_iterator.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 THORVG_BOUNDS_ITERATOR_H +#define THORVG_BOUNDS_ITERATOR_H + +#ifdef GDEXTENSION +// Headers for building as GDExtension plug-in. + +#include <godot_cpp/core/mutex_lock.hpp> +#include <godot_cpp/godot.hpp> + +using namespace godot; + +#else +// Headers for building as built-in module. + +#include "core/typedefs.h" + +#include "modules/modules_enabled.gen.h" // For svg. +#endif + +#ifdef MODULE_SVG_ENABLED + +#include <thorvg.h> + +void tvg_get_bounds(tvg::Picture *p_picture, float &r_min_x, float &r_min_y, float &r_max_x, float &r_max_y); + +#endif // MODULE_SVG_ENABLED + +#endif // THORVG_BOUNDS_ITERATOR_H diff --git a/modules/text_server_adv/thorvg_svg_in_ot.cpp b/modules/text_server_adv/thorvg_svg_in_ot.cpp new file mode 100644 index 0000000000..7863ab67fa --- /dev/null +++ b/modules/text_server_adv/thorvg_svg_in_ot.cpp @@ -0,0 +1,320 @@ +/*************************************************************************/ +/* thorvg_svg_in_ot.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 GDEXTENSION +// Headers for building as GDExtension plug-in. + +#include <godot_cpp/classes/xml_parser.hpp> +#include <godot_cpp/core/mutex_lock.hpp> +#include <godot_cpp/godot.hpp> +#include <godot_cpp/templates/vector.hpp> + +using namespace godot; + +#else +// Headers for building as built-in module. + +#include "core/error/error_macros.h" +#include "core/io/xml_parser.h" +#include "core/os/memory.h" +#include "core/os/os.h" +#include "core/string/ustring.h" +#include "core/typedefs.h" +#include "core/variant/variant.h" + +#include "modules/modules_enabled.gen.h" // For svg. +#endif + +#ifdef MODULE_SVG_ENABLED + +#include "thorvg_bounds_iterator.h" +#include "thorvg_svg_in_ot.h" + +#include <freetype/otsvg.h> +#include <ft2build.h> + +#include <math.h> +#include <stdlib.h> + +FT_Error tvg_svg_in_ot_init(FT_Pointer *p_state) { + *p_state = memnew(TVG_State); + + return FT_Err_Ok; +} + +void tvg_svg_in_ot_free(FT_Pointer *p_state) { + TVG_State *state = *reinterpret_cast<TVG_State **>(p_state); + memdelete(state); +} + +FT_Error tvg_svg_in_ot_preset_slot(FT_GlyphSlot p_slot, FT_Bool p_cache, FT_Pointer *p_state) { + TVG_State *state = *reinterpret_cast<TVG_State **>(p_state); + if (!state) { + ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "SVG in OT state not initialized."); + } + MutexLock lock(state->mutex); + + FT_SVG_Document document = (FT_SVG_Document)p_slot->other; + FT_Size_Metrics metrics = document->metrics; + + GL_State &gl_state = state->glyph_map[p_slot->glyph_index]; + if (!gl_state.ready) { + Ref<XMLParser> parser; + parser.instantiate(); +#ifdef GDEXTENSION + PackedByteArray data; + data.resize(document->svg_document_length); + memcpy(data.ptrw(), document->svg_document, document->svg_document_length); + parser->open_buffer(data); +#else + parser->_open_buffer((const uint8_t *)document->svg_document, document->svg_document_length); +#endif + + float aspect = 1.0f; + String xml_body; + while (parser->read() == OK) { + if (parser->has_attribute("id")) { +#ifdef GDEXTENSION + const String &gl_name = parser->get_named_attribute_value("id"); +#else + const String &gl_name = parser->get_attribute_value("id"); +#endif + if (gl_name.begins_with("glyph")) { + int dot_pos = gl_name.find("."); + int64_t gl_idx = gl_name.substr(5, (dot_pos > 0) ? dot_pos - 5 : -1).to_int(); + if (p_slot->glyph_index != gl_idx) { + parser->skip_section(); + continue; + } + } + } + if (parser->get_node_type() == XMLParser::NODE_ELEMENT && parser->get_node_name() == "svg") { + if (parser->has_attribute("viewBox")) { +#ifdef GDEXTENSION + PackedStringArray vb = parser->get_named_attribute_value("viewBox").split(" "); +#else + Vector<String> vb = parser->get_attribute_value("viewBox").split(" "); +#endif + + if (vb.size() == 4) { + aspect = vb[2].to_float() / vb[3].to_float(); + } + } + continue; + } +#ifdef GDEXTENSION + if (parser->get_node_type() == XMLParser::NODE_ELEMENT) { + xml_body = xml_body + "<" + parser->get_node_name(); + for (int i = 0; i < parser->get_attribute_count(); i++) { + xml_body = xml_body + " " + parser->get_attribute_name(i) + "=\"" + parser->get_attribute_value(i) + "\""; + } + xml_body = xml_body + ">"; + } else if (parser->get_node_type() == XMLParser::NODE_TEXT) { + xml_body = xml_body + parser->get_node_data(); + } else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END) { + xml_body = xml_body + "</" + parser->get_node_name() + ">"; + } +#else + if (parser->get_node_type() == XMLParser::NODE_ELEMENT) { + xml_body += vformat("<%s", parser->get_node_name()); + for (int i = 0; i < parser->get_attribute_count(); i++) { + xml_body += vformat(" %s=\"%s\"", parser->get_attribute_name(i), parser->get_attribute_value(i)); + } + xml_body += ">"; + } else if (parser->get_node_type() == XMLParser::NODE_TEXT) { + xml_body += parser->get_node_data(); + } else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END) { + xml_body += vformat("</%s>", parser->get_node_name()); + } +#endif + } + String temp_xml = "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 0 0\">" + xml_body; + + std::unique_ptr<tvg::Picture> picture = tvg::Picture::gen(); + tvg::Result result = picture->load(temp_xml.utf8().get_data(), temp_xml.utf8().length(), "svg+xml", false); + if (result != tvg::Result::Success) { + ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to load SVG document (bounds detection)."); + } + + float min_x = INFINITY, min_y = INFINITY, max_x = -INFINITY, max_y = -INFINITY; + tvg_get_bounds(picture.get(), min_x, min_y, max_x, max_y); + + float new_h = (max_y - min_y); + float new_w = (max_x - min_x); + + if (new_h * aspect >= new_w) { + new_w = (new_h * aspect); + } else { + new_h = (new_w / aspect); + } + +#ifdef GDEXTENSION + gl_state.xml_code = "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"" + rtos(min_x) + " " + rtos(min_y) + " " + rtos(new_w) + " " + rtos(new_h) + "\">" + xml_body; +#else + gl_state.xml_code = vformat("<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"%f %f %f %f\">", min_x, min_y, new_w, new_h) + xml_body; +#endif + + picture = tvg::Picture::gen(); + result = picture->load(gl_state.xml_code.utf8().get_data(), gl_state.xml_code.utf8().length(), "svg+xml", false); + if (result != tvg::Result::Success) { + ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to load SVG document (glyph metrics)."); + } + + float x_svg_to_out, y_svg_to_out; + x_svg_to_out = (float)metrics.x_ppem / new_w; + y_svg_to_out = (float)metrics.y_ppem / new_h; + + gl_state.m.e11 = (double)document->transform.xx / (1 << 16) * x_svg_to_out; + gl_state.m.e12 = -(double)document->transform.xy / (1 << 16) * x_svg_to_out; + gl_state.m.e21 = -(double)document->transform.yx / (1 << 16) * y_svg_to_out; + gl_state.m.e22 = (double)document->transform.yy / (1 << 16) * y_svg_to_out; + gl_state.m.e13 = (double)document->delta.x / 64 * new_w / metrics.x_ppem; + gl_state.m.e23 = -(double)document->delta.y / 64 * new_h / metrics.y_ppem; + gl_state.m.e31 = 0; + gl_state.m.e32 = 0; + gl_state.m.e33 = 1; + + result = picture->transform(gl_state.m); + if (result != tvg::Result::Success) { + ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to apply transform to SVG document."); + } + + result = picture->bounds(&gl_state.x, &gl_state.y, &gl_state.w, &gl_state.h, true); + if (result != tvg::Result::Success) { + ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to get SVG bounds."); + } + + gl_state.bmp_y = -min_y * gl_state.h / new_h; + gl_state.bmp_x = min_x * gl_state.w / new_w; + + gl_state.ready = true; + } + + p_slot->bitmap_left = (FT_Int)gl_state.bmp_x; + p_slot->bitmap_top = (FT_Int)gl_state.bmp_y; + + float tmp = ceil(gl_state.h); + p_slot->bitmap.rows = (unsigned int)tmp; + tmp = ceil(gl_state.w); + p_slot->bitmap.width = (unsigned int)tmp; + p_slot->bitmap.pitch = (int)p_slot->bitmap.width * 4; + p_slot->bitmap.pixel_mode = FT_PIXEL_MODE_BGRA; + + float metrics_width, metrics_height; + float horiBearingX, horiBearingY; + float vertBearingX, vertBearingY; + + metrics_width = (float)gl_state.w; + metrics_height = (float)gl_state.h; + horiBearingX = (float)gl_state.x; + horiBearingY = (float)-gl_state.y; + vertBearingX = p_slot->metrics.horiBearingX / 64.0f - p_slot->metrics.horiAdvance / 64.0f / 2; + vertBearingY = (p_slot->metrics.vertAdvance / 64.0f - p_slot->metrics.height / 64.0f) / 2; + + tmp = roundf(metrics_width * 64); + p_slot->metrics.width = (FT_Pos)tmp; + tmp = roundf(metrics_height * 64); + p_slot->metrics.height = (FT_Pos)tmp; + + p_slot->metrics.horiBearingX = (FT_Pos)(horiBearingX * 64); + p_slot->metrics.horiBearingY = (FT_Pos)(horiBearingY * 64); + p_slot->metrics.vertBearingX = (FT_Pos)(vertBearingX * 64); + p_slot->metrics.vertBearingY = (FT_Pos)(vertBearingY * 64); + + if (p_slot->metrics.vertAdvance == 0) { + p_slot->metrics.vertAdvance = (FT_Pos)(metrics_height * 1.2f * 64); + } + + return FT_Err_Ok; +} + +FT_Error tvg_svg_in_ot_render(FT_GlyphSlot p_slot, FT_Pointer *p_state) { + TVG_State *state = *reinterpret_cast<TVG_State **>(p_state); + if (!state) { + ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "SVG in OT state not initialized."); + } + MutexLock lock(state->mutex); + + if (!state->glyph_map.has(p_slot->glyph_index)) { + ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "SVG glyph not loaded."); + } + + GL_State &gl_state = state->glyph_map[p_slot->glyph_index]; + ERR_FAIL_COND_V_MSG(!gl_state.ready, FT_Err_Invalid_SVG_Document, "SVG glyph not ready."); + + std::unique_ptr<tvg::Picture> picture = tvg::Picture::gen(); + tvg::Result res = picture->load(gl_state.xml_code.utf8().get_data(), gl_state.xml_code.utf8().length(), "svg+xml", false); + if (res != tvg::Result::Success) { + ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to load SVG document (glyph rendering)."); + } + res = picture->transform(gl_state.m); + if (res != tvg::Result::Success) { + ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to apply transform to SVG document."); + } + + std::unique_ptr<tvg::SwCanvas> sw_canvas = tvg::SwCanvas::gen(); + res = sw_canvas->target((uint32_t *)p_slot->bitmap.buffer, (int)p_slot->bitmap.width, (int)p_slot->bitmap.width, (int)p_slot->bitmap.rows, tvg::SwCanvas::ARGB8888_STRAIGHT); + if (res != tvg::Result::Success) { + ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to create SVG canvas."); + } + res = sw_canvas->push(std::move(picture)); + if (res != tvg::Result::Success) { + ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to set SVG canvas source."); + } + res = sw_canvas->draw(); + if (res != tvg::Result::Success) { + ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to draw to SVG canvas."); + } + res = sw_canvas->sync(); + if (res != tvg::Result::Success) { + ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to sync SVG canvas."); + } + + state->glyph_map.erase(p_slot->glyph_index); + + p_slot->bitmap.pixel_mode = FT_PIXEL_MODE_BGRA; + p_slot->bitmap.num_grays = 256; + p_slot->format = FT_GLYPH_FORMAT_BITMAP; + + return FT_Err_Ok; +} + +SVG_RendererHooks tvg_svg_in_ot_hooks = { + (SVG_Lib_Init_Func)tvg_svg_in_ot_init, + (SVG_Lib_Free_Func)tvg_svg_in_ot_free, + (SVG_Lib_Render_Func)tvg_svg_in_ot_render, + (SVG_Lib_Preset_Slot_Func)tvg_svg_in_ot_preset_slot, +}; + +SVG_RendererHooks *get_tvg_svg_in_ot_hooks() { + return &tvg_svg_in_ot_hooks; +} + +#endif // MODULE_SVG_ENABLED diff --git a/modules/text_server_adv/thorvg_svg_in_ot.h b/modules/text_server_adv/thorvg_svg_in_ot.h new file mode 100644 index 0000000000..b2816193d9 --- /dev/null +++ b/modules/text_server_adv/thorvg_svg_in_ot.h @@ -0,0 +1,86 @@ +/*************************************************************************/ +/* thorvg_svg_in_ot.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 THORVG_SVG_IN_OT_H +#define THORVG_SVG_IN_OT_H + +#ifdef GDEXTENSION +// Headers for building as GDExtension plug-in. + +#include <godot_cpp/core/mutex_lock.hpp> +#include <godot_cpp/godot.hpp> +#include <godot_cpp/templates/hash_map.hpp> + +using namespace godot; + +#else +// Headers for building as built-in module. + +#include "core/os/mutex.h" +#include "core/templates/hash_map.h" +#include "core/typedefs.h" + +#include "modules/modules_enabled.gen.h" // For svg. +#endif + +#ifdef MODULE_SVG_ENABLED + +#include <freetype/freetype.h> +#include <freetype/otsvg.h> +#include <ft2build.h> +#include <thorvg.h> + +struct GL_State { + bool ready = false; + float bmp_x = 0; + float bmp_y = 0; + float x = 0; + float y = 0; + float w = 0; + float h = 0; + String xml_code; + tvg::Matrix m; +}; + +struct TVG_State { + Mutex mutex; + HashMap<uint32_t, GL_State> glyph_map; +}; + +FT_Error tvg_svg_in_ot_init(FT_Pointer *p_state); +void tvg_svg_in_ot_free(FT_Pointer *p_state); +FT_Error tvg_svg_in_ot_preset_slot(FT_GlyphSlot p_slot, FT_Bool p_cache, FT_Pointer *p_state); +FT_Error tvg_svg_in_ot_render(FT_GlyphSlot p_slot, FT_Pointer *p_state); + +SVG_RendererHooks *get_tvg_svg_in_ot_hooks(); + +#endif // MODULE_SVG_ENABLED + +#endif // THORVG_SVG_IN_OT_H diff --git a/modules/text_server_fb/SCsub b/modules/text_server_fb/SCsub index 429d2e1fdc..f1d57ec4d3 100644 --- a/modules/text_server_fb/SCsub +++ b/modules/text_server_fb/SCsub @@ -8,6 +8,9 @@ msdfgen_enabled = "msdfgen" in env.module_list env_text_server_fb = env_modules.Clone() +if "svg" in env.module_list: + env_text_server_fb.Prepend(CPPPATH=["#thirdparty/thorvg/inc", "#thirdparty/thorvg/src/lib"]) + if env["builtin_msdfgen"] and msdfgen_enabled: env_text_server_fb.Prepend(CPPPATH=["#thirdparty/msdfgen"]) diff --git a/modules/text_server_fb/gdextension_build/SConstruct b/modules/text_server_fb/gdextension_build/SConstruct index de0a549900..7b4c548a21 100644 --- a/modules/text_server_fb/gdextension_build/SConstruct +++ b/modules/text_server_fb/gdextension_build/SConstruct @@ -19,8 +19,10 @@ env = SConscript("./godot-cpp/SConstruct") env.__class__.disable_warnings = methods.disable_warnings opts = Variables([], ARGUMENTS) +opts.Add(BoolVariable("brotli_enabled", "Use Brotli library", True)) opts.Add(BoolVariable("freetype_enabled", "Use FreeType library", True)) opts.Add(BoolVariable("msdfgen_enabled", "Use MSDFgen library (require FreeType)", True)) +opts.Add(BoolVariable("thorvg_enabled", "Use ThorVG library (require FreeType)", True)) opts.Add(BoolVariable("verbose", "Enable verbose output for the compilation", False)) opts.Update(env) @@ -28,6 +30,79 @@ opts.Update(env) if not env["verbose"]: methods.no_verbose(sys, env) +# ThorVG +if env["thorvg_enabled"] and env["freetype_enabled"]: + env_tvg = env.Clone() + env_tvg.disable_warnings() + + thirdparty_tvg_dir = "../../../thirdparty/thorvg/" + thirdparty_tvg_sources = [ + "src/lib/sw_engine/tvgSwFill.cpp", + "src/lib/sw_engine/tvgSwImage.cpp", + "src/lib/sw_engine/tvgSwMath.cpp", + "src/lib/sw_engine/tvgSwMemPool.cpp", + "src/lib/sw_engine/tvgSwRaster.cpp", + "src/lib/sw_engine/tvgSwRenderer.cpp", + "src/lib/sw_engine/tvgSwRle.cpp", + "src/lib/sw_engine/tvgSwShape.cpp", + "src/lib/sw_engine/tvgSwStroke.cpp", + "src/lib/tvgAccessor.cpp", + "src/lib/tvgBezier.cpp", + "src/lib/tvgCanvas.cpp", + "src/lib/tvgFill.cpp", + "src/lib/tvgGlCanvas.cpp", + "src/lib/tvgInitializer.cpp", + "src/lib/tvgLinearGradient.cpp", + "src/lib/tvgLoader.cpp", + "src/lib/tvgLzw.cpp", + "src/lib/tvgPaint.cpp", + "src/lib/tvgPicture.cpp", + "src/lib/tvgRadialGradient.cpp", + "src/lib/tvgRender.cpp", + "src/lib/tvgSaver.cpp", + "src/lib/tvgScene.cpp", + "src/lib/tvgShape.cpp", + "src/lib/tvgSwCanvas.cpp", + "src/lib/tvgTaskScheduler.cpp", + "src/loaders/external_png/tvgPngLoader.cpp", + "src/loaders/jpg/tvgJpgd.cpp", + "src/loaders/jpg/tvgJpgLoader.cpp", + "src/loaders/raw/tvgRawLoader.cpp", + "src/loaders/svg/tvgSvgCssStyle.cpp", + "src/loaders/svg/tvgSvgLoader.cpp", + "src/loaders/svg/tvgSvgPath.cpp", + "src/loaders/svg/tvgSvgSceneBuilder.cpp", + "src/loaders/svg/tvgSvgUtil.cpp", + "src/loaders/svg/tvgXmlParser.cpp", + "src/loaders/tvg/tvgTvgBinInterpreter.cpp", + "src/loaders/tvg/tvgTvgLoader.cpp", + "src/savers/tvg/tvgTvgSaver.cpp", + ] + thirdparty_tvg_sources = [thirdparty_tvg_dir + file for file in thirdparty_tvg_sources] + + env_tvg.Append( + CPPPATH=[ + "../../../thirdparty/thorvg/inc", + "../../../thirdparty/thorvg/src/lib", + "../../../thirdparty/thorvg/src/lib/sw_engine", + "../../../thirdparty/thorvg/src/loaders/external_png", + "../../../thirdparty/thorvg/src/loaders/jpg", + "../../../thirdparty/thorvg/src/loaders/raw", + "../../../thirdparty/thorvg/src/loaders/svg", + "../../../thirdparty/thorvg/src/loaders/tvg", + "../../../thirdparty/thorvg/src/savers/tvg", + "../../../thirdparty/libpng", + ] + ) + env.Append(CPPPATH=["../../../thirdparty/thorvg/inc", "../../../thirdparty/thorvg/src/lib"]) + env.Append(CPPDEFINES=["MODULE_SVG_ENABLED"]) + + lib = env_tvg.Library( + f'tvg_builtin{env["suffix"]}{env["LIBSUFFIX"]}', + thirdparty_tvg_sources, + ) + env.Append(LIBS=[lib]) + # MSDFGEN if env["msdfgen_enabled"] and env["freetype_enabled"]: env_msdfgen = env.Clone() @@ -62,7 +137,7 @@ if env["msdfgen_enabled"] and env["freetype_enabled"]: env.Append(CPPDEFINES=["MODULE_MSDFGEN_ENABLED"]) lib = env_msdfgen.Library( - f'msdfgen_builtin.{env["platform"]}.{env["target"]}.{env["arch_suffix"]}{env["LIBSUFFIX"]}', + f'msdfgen_builtin{env["suffix"]}{env["LIBSUFFIX"]}', thirdparty_msdfgen_sources, ) env.Append(LIBS=[lib]) @@ -157,6 +232,25 @@ if env["freetype_enabled"]: ] thirdparty_freetype_sources += [thirdparty_zlib_dir + file for file in thirdparty_zlib_sources] + if env["brotli_enabled"]: + thirdparty_brotli_dir = "../../../thirdparty/brotli/" + thirdparty_brotli_sources = [ + "common/constants.c", + "common/context.c", + "common/dictionary.c", + "common/platform.c", + "common/shared_dictionary.c", + "common/transform.c", + "dec/bit_reader.c", + "dec/decode.c", + "dec/huffman.c", + "dec/state.c", + ] + thirdparty_freetype_sources += [thirdparty_brotli_dir + file for file in thirdparty_brotli_sources] + env_freetype.Append(CPPDEFINES=["FT_CONFIG_OPTION_USE_BROTLI"]) + env_freetype.Prepend(CPPPATH=[thirdparty_brotli_dir + "include"]) + env.Append(CPPDEFINES=["FT_CONFIG_OPTION_USE_BROTLI"]) + env_freetype.Append(CPPPATH=[thirdparty_freetype_dir + "/include", thirdparty_zlib_dir, thirdparty_png_dir]) env.Append(CPPPATH=[thirdparty_freetype_dir + "/include"]) @@ -168,13 +262,13 @@ if env["freetype_enabled"]: "FT_CONFIG_OPTION_SYSTEM_ZLIB", ] ) - if env["target"] == "debug": + if env.dev_build: env_freetype.Append(CPPDEFINES=["ZLIB_DEBUG"]) env.Append(CPPDEFINES=["MODULE_FREETYPE_ENABLED"]) lib = env_freetype.Library( - f'freetype_builtin.{env["platform"]}.{env["target"]}.{env["arch_suffix"]}{env["LIBSUFFIX"]}', + f'freetype_builtin{env["suffix"]}{env["LIBSUFFIX"]}', thirdparty_freetype_sources, ) env.Append(LIBS=[lib]) @@ -197,7 +291,7 @@ if env["platform"] == "macos": ) else: library = env.SharedLibrary( - f'./bin/libtextserver_fallback.{env["platform"]}.{env["target"]}.{env["arch_suffix"]}{env["SHLIBSUFFIX"]}', + f'./bin/libtextserver_fallback{env["suffix"]}{env["SHLIBSUFFIX"]}', source=sources, ) diff --git a/modules/text_server_fb/gdextension_build/text_server_fb.gdextension b/modules/text_server_fb/gdextension_build/text_server_fb.gdextension index 9236555d63..58a92e403b 100644 --- a/modules/text_server_fb/gdextension_build/text_server_fb.gdextension +++ b/modules/text_server_fb/gdextension_build/text_server_fb.gdextension @@ -4,9 +4,21 @@ entry_symbol = "textserver_fallback_init" [libraries] -linux.64.debug = "bin/libtextserver_fallback.linux.debug.64.so" -linux.64.release = "bin/libtextserver_fallback.linux.release.64.so" -windows.64.debug = "bin/libtextserver_fallback.windows.debug.64.dll" -windows.64.release = "bin/libtextserver_fallback.windows.release.64.dll" -macos.debug = "bin/libtextserver_fallback.macos.debug.framework" -macos.release = "bin/libtextserver_fallback.macos.release.framework" +linux.x86_64.debug = "bin/libtextserver_fallback.linux.template_debug.x86_64.so" +linux.x86_64.release = "bin/libtextserver_fallback.linux.template_release.x86_64.so" +linux.x86_32.debug = "bin/libtextserver_fallback.linux.template_debug.x86_32.so" +linux.x86_32.release = "bin/libtextserver_fallback.linux.template_release.x86_32.so" +linux.arm64.debug = "bin/libtextserver_fallback.linux.template_debug.arm64.so" +linux.arm64.release = "bin/libtextserver_fallback.linux.template_release.arm64.so" +linux.rv64.debug = "bin/libtextserver_fallback.linux.template_debug.rv64.so" +linux.rv64.release = "bin/libtextserver_fallback.linux.template_release.rv64.so" + +windows.x86_64.debug = "bin/libtextserver_fallback.windows.template_debug.x86_64.dll" +windows.x86_64.release = "bin/libtextserver_fallback.windows.template_release.x86_64.dll" +windows.x86_32.debug = "bin/libtextserver_fallback.windows.template_debug.x86_32.dll" +windows.x86_32.release = "bin/libtextserver_fallback.windows.template_release.x86_32.dll" +windows.arm64.debug = "bin/libtextserver_fallback.windows.template_debug.arm64.dll" +windows.arm64.release = "bin/libtextserver_fallback.windows.template_release.arm64.dll" + +macos.debug = "bin/libtextserver_fallback.macos.template_debug.framework" +macos.release = "bin/libtextserver_fallback.macos.template_release.framework" diff --git a/modules/text_server_fb/text_server_fb.cpp b/modules/text_server_fb/text_server_fb.cpp index 4d599dbcb5..aaef9c9a3d 100644 --- a/modules/text_server_fb/text_server_fb.cpp +++ b/modules/text_server_fb/text_server_fb.cpp @@ -33,7 +33,7 @@ #ifdef GDEXTENSION // Headers for building as GDExtension plug-in. -#include <godot_cpp/classes/file.hpp> +#include <godot_cpp/classes/file_access.hpp> #include <godot_cpp/classes/project_settings.hpp> #include <godot_cpp/classes/rendering_server.hpp> #include <godot_cpp/classes/translation_server.hpp> @@ -41,6 +41,8 @@ using namespace godot; +#define GLOBAL_GET(m_var) ProjectSettings::get_singleton()->get(m_var) + #else // Headers for building as built-in module. @@ -49,7 +51,7 @@ using namespace godot; #include "core/string/print_string.h" #include "core/string/ucaps.h" -#include "modules/modules_enabled.gen.h" // For freetype, msdfgen. +#include "modules/modules_enabled.gen.h" // For freetype, msdfgen, svg. #endif @@ -62,11 +64,15 @@ using namespace godot; #include "msdfgen.h" #endif +#ifdef MODULE_SVG_ENABLED +#include "thorvg_svg_in_ot.h" +#endif + /*************************************************************************/ #define OT_TAG(c1, c2, c3, c4) ((int32_t)((((uint32_t)(c1)&0xff) << 24) | (((uint32_t)(c2)&0xff) << 16) | (((uint32_t)(c3)&0xff) << 8) | ((uint32_t)(c4)&0xff))) -bool TextServerFallback::has_feature(Feature p_feature) const { +bool TextServerFallback::_has_feature(Feature p_feature) const { switch (p_feature) { case FEATURE_SIMPLE_LAYOUT: case FEATURE_FONT_BITMAP: @@ -83,7 +89,7 @@ bool TextServerFallback::has_feature(Feature p_feature) const { return false; } -String TextServerFallback::get_name() const { +String TextServerFallback::_get_name() const { #ifdef GDEXTENSION return "Fallback (GDExtension)"; #else @@ -91,7 +97,7 @@ String TextServerFallback::get_name() const { #endif } -int64_t TextServerFallback::get_features() const { +int64_t TextServerFallback::_get_features() const { int64_t interface_features = FEATURE_SIMPLE_LAYOUT | FEATURE_FONT_BITMAP; #ifdef MODULE_FREETYPE_ENABLED interface_features |= FEATURE_FONT_DYNAMIC; @@ -103,7 +109,7 @@ int64_t TextServerFallback::get_features() const { return interface_features; } -void TextServerFallback::free_rid(const RID &p_rid) { +void TextServerFallback::_free_rid(const RID &p_rid) { _THREAD_SAFE_METHOD_ if (font_owner.owns(p_rid)) { FontFallback *fd = font_owner.get_or_null(p_rid); @@ -116,20 +122,28 @@ void TextServerFallback::free_rid(const RID &p_rid) { } } -bool TextServerFallback::has(const RID &p_rid) { +bool TextServerFallback::_has(const 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) { +String TextServerFallback::_get_support_data_filename() const { + return ""; +}; + +String TextServerFallback::_get_support_data_info() const { + return "Not supported"; +}; + +bool TextServerFallback::_load_support_data(const String &p_filename) { return false; // No extra data used. } -bool TextServerFallback::save_support_data(const String &p_filename) const { +bool TextServerFallback::_save_support_data(const String &p_filename) const { return false; // No extra data used. } -bool TextServerFallback::is_locale_right_to_left(const String &p_locale) const { +bool TextServerFallback::_is_locale_right_to_left(const String &p_locale) const { return false; // No RTL support. } @@ -169,7 +183,7 @@ _FORCE_INLINE_ int32_t ot_tag_from_string(const char *p_str, int p_len) { return OT_TAG(tag[0], tag[1], tag[2], tag[3]); } -int64_t TextServerFallback::name_to_tag(const String &p_name) const { +int64_t TextServerFallback::_name_to_tag(const String &p_name) const { if (feature_sets.has(p_name)) { return feature_sets[p_name]; } @@ -185,7 +199,7 @@ _FORCE_INLINE_ void ot_tag_to_string(int32_t p_tag, char *p_buf) { p_buf[3] = (char)(uint8_t)(p_tag >> 0); } -String TextServerFallback::tag_to_name(int64_t p_tag) const { +String TextServerFallback::_tag_to_name(int64_t p_tag) const { if (feature_sets_inv.has(p_tag)) { return feature_sets_inv[p_tag]; } @@ -203,58 +217,27 @@ String TextServerFallback::tag_to_name(int64_t p_tag) const { _FORCE_INLINE_ TextServerFallback::FontTexturePosition TextServerFallback::find_texture_pos_for_glyph(FontForSizeFallback *p_data, int p_color_size, Image::Format p_image_format, int p_width, int p_height, bool p_msdf) const { FontTexturePosition ret; - ret.index = -1; int mw = p_width; int mh = p_height; - for (int i = 0; i < p_data->textures.size(); i++) { - const FontTexture &ct = p_data->textures[i]; - - if (p_image_format != ct.format) { + ShelfPackTexture *ct = p_data->textures.ptrw(); + for (int32_t i = 0; i < p_data->textures.size(); i++) { + if (p_image_format != ct[i].format) { continue; } - - if (mw > ct.texture_w || mh > ct.texture_h) { // Too big for this texture. + if (mw > ct[i].texture_w || mh > ct[i].texture_h) { // Too big for this texture. continue; } - if (ct.offsets.size() < ct.texture_w) { - continue; + ret = ct[i].pack_rect(i, mh, mw); + if (ret.index != -1) { + break; } - - ret.y = 0x7fffffff; - ret.x = 0; - - for (int j = 0; j < ct.texture_w - 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_h) { - 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.x * p_data->oversampling * 8, 256); #ifdef GDEXTENSION @@ -283,12 +266,9 @@ _FORCE_INLINE_ TextServerFallback::FontTexturePosition TextServerFallback::find_ #endif } - FontTexture tex; - tex.texture_w = texsize; - tex.texture_h = texsize; + ShelfPackTexture tex = ShelfPackTexture(texsize, texsize); tex.format = p_image_format; tex.imgdata.resize(texsize * texsize * p_color_size); - { // Zero texture. uint8_t *w = tex.imgdata.ptrw(); @@ -311,14 +291,10 @@ _FORCE_INLINE_ TextServerFallback::FontTexturePosition TextServerFallback::find_ ERR_FAIL_V(ret); } } - tex.offsets.resize(texsize); - int32_t *offw = tex.offsets.ptrw(); - for (int i = 0; i < texsize; i++) { // Zero offsets. - offw[i] = 0; - } - p_data->textures.push_back(tex); - ret.index = p_data->textures.size() - 1; + + int32_t idx = p_data->textures.size() - 1; + ret = p_data->textures.write[idx].pack_rect(idx, mh, mw); } return ret; @@ -452,7 +428,7 @@ _FORCE_INLINE_ TextServerFallback::FontGlyph TextServerFallback::rasterize_msdf( FontTexturePosition tex_pos = find_texture_pos_for_glyph(p_data, 4, Image::FORMAT_RGBA8, mw, mh, true); ERR_FAIL_COND_V(tex_pos.index < 0, FontGlyph()); - FontTexture &tex = p_data->textures.write[tex_pos.index]; + ShelfPackTexture &tex = p_data->textures.write[tex_pos.index]; edgeColoringSimple(shape, 3.0); // Max. angle. msdfgen::Bitmap<float, 4> image(w, h); // Texture size. @@ -467,8 +443,14 @@ _FORCE_INLINE_ TextServerFallback::FontGlyph TextServerFallback::rasterize_msdf( td.projection = &projection; td.distancePixelConversion = &distancePixelConversion; +#ifdef GDEXTENSION + for (int i = 0; i < h; i++) { + _generateMTSDF_threaded(i, &td); + } +#else WorkerThreadPool::GroupID group_id = WorkerThreadPool::get_singleton()->add_template_group_task(this, &TextServerFallback::_generateMTSDF_threaded, &td, h, -1, true, SNAME("TextServerFBRenderMSDF")); WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_id); +#endif msdfgen::msdfErrorCorrection(image, shape, projection, p_pixel_range, config); @@ -489,12 +471,6 @@ _FORCE_INLINE_ TextServerFallback::FontGlyph TextServerFallback::rasterize_msdf( tex.dirty = true; - // Update height array. - int32_t *offw = tex.offsets.ptrw(); - for (int k = tex_pos.x; k < tex_pos.x + mw; k++) { - offw[k] = tex_pos.y + mh; - } - chr.texture_idx = tex_pos.index; chr.uv_rect = Rect2(tex_pos.x + p_rect_margin, tex_pos.y + p_rect_margin, w + p_rect_margin * 2, h + p_rect_margin * 2); @@ -541,8 +517,7 @@ _FORCE_INLINE_ TextServerFallback::FontGlyph TextServerFallback::rasterize_bitma ERR_FAIL_COND_V(tex_pos.index < 0, FontGlyph()); // Fit character in char texture. - - FontTexture &tex = p_data->textures.write[tex_pos.index]; + ShelfPackTexture &tex = p_data->textures.write[tex_pos.index]; { uint8_t *wr = tex.imgdata.ptrw(); @@ -607,12 +582,6 @@ _FORCE_INLINE_ TextServerFallback::FontGlyph TextServerFallback::rasterize_bitma tex.dirty = true; - // Update height array. - int32_t *offw = tex.offsets.ptrw(); - for (int k = tex_pos.x; k < tex_pos.x + mw; k++) { - offw[k] = tex_pos.y + mh; - } - FontGlyph chr; chr.advance = advance * p_data->scale / p_data->oversampling; chr.texture_idx = tex_pos.index; @@ -804,7 +773,13 @@ _FORCE_INLINE_ bool TextServerFallback::_ensure_cache_for_size(FontFallback *p_f int error = 0; if (!ft_library) { error = FT_Init_FreeType(&ft_library); - ERR_FAIL_COND_V_MSG(error != 0, false, "FreeType: Error initializing library: '" + String(FT_Error_String(error)) + "'."); + if (error != 0) { + memdelete(fd); + ERR_FAIL_V_MSG(false, "FreeType: Error initializing library: '" + String(FT_Error_String(error)) + "'."); + } +#ifdef MODULE_SVG_ENABLED + FT_Property_Set(ft_library, "ot-svg", "svg-hooks", get_tvg_svg_in_ot_hooks()); +#endif } memset(&fd->stream, 0, sizeof(FT_StreamRec)); @@ -833,6 +808,7 @@ _FORCE_INLINE_ bool TextServerFallback::_ensure_cache_for_size(FontFallback *p_f if (error) { FT_Done_Face(fd->face); fd->face = nullptr; + memdelete(fd); ERR_FAIL_V_MSG(false, "FreeType: Error loading font: '" + String(FT_Error_String(error)) + "'."); } @@ -840,7 +816,7 @@ _FORCE_INLINE_ bool TextServerFallback::_ensure_cache_for_size(FontFallback *p_f fd->oversampling = 1.0; fd->size.x = p_font_data->msdf_source_size; } else if (p_font_data->oversampling <= 0.0) { - fd->oversampling = font_get_global_oversampling(); + fd->oversampling = _font_get_global_oversampling(); } else { fd->oversampling = p_font_data->oversampling; } @@ -921,8 +897,8 @@ _FORCE_INLINE_ bool TextServerFallback::_ensure_cache_for_size(FontFallback *p_f coords.write[i] = CLAMP(var_value * 65536.0, amaster->axis[i].minimum, amaster->axis[i].maximum); } - if (p_font_data->variation_coordinates.has(tag_to_name(var_tag))) { - var_value = p_font_data->variation_coordinates[tag_to_name(var_tag)]; + if (p_font_data->variation_coordinates.has(_tag_to_name(var_tag))) { + var_value = p_font_data->variation_coordinates[_tag_to_name(var_tag)]; coords.write[i] = CLAMP(var_value * 65536.0, amaster->axis[i].minimum, amaster->axis[i].maximum); } } @@ -931,6 +907,7 @@ _FORCE_INLINE_ bool TextServerFallback::_ensure_cache_for_size(FontFallback *p_f FT_Done_MM_Var(ft_library, amaster); } #else + memdelete(fd); ERR_FAIL_V_MSG(false, "FreeType: Can't load dynamic font, engine is compiled without FreeType support!"); #endif } @@ -948,7 +925,7 @@ _FORCE_INLINE_ void TextServerFallback::_font_clear_cache(FontFallback *p_font_d p_font_data->supported_varaitions.clear(); } -RID TextServerFallback::create_font() { +RID TextServerFallback::_create_font() { _THREAD_SAFE_METHOD_ FontFallback *fd = memnew(FontFallback); @@ -956,7 +933,7 @@ RID TextServerFallback::create_font() { return font_owner.make_rid(fd); } -void TextServerFallback::font_set_data(const RID &p_font_rid, const PackedByteArray &p_data) { +void TextServerFallback::_font_set_data(const RID &p_font_rid, const PackedByteArray &p_data) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -967,7 +944,7 @@ void TextServerFallback::font_set_data(const RID &p_font_rid, const PackedByteAr fd->data_size = fd->data.size(); } -void TextServerFallback::font_set_data_ptr(const RID &p_font_rid, const uint8_t *p_data_ptr, int64_t p_data_size) { +void TextServerFallback::_font_set_data_ptr(const RID &p_font_rid, const uint8_t *p_data_ptr, int64_t p_data_size) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -978,7 +955,7 @@ void TextServerFallback::font_set_data_ptr(const RID &p_font_rid, const uint8_t fd->data_size = p_data_size; } -void TextServerFallback::font_set_style(const RID &p_font_rid, BitField<FontStyle> p_style) { +void TextServerFallback::_font_set_style(const RID &p_font_rid, BitField<FontStyle> p_style) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -988,7 +965,7 @@ void TextServerFallback::font_set_style(const RID &p_font_rid, BitField<FontStyl fd->style_flags = p_style; } -void TextServerFallback::font_set_face_index(const RID &p_font_rid, int64_t p_face_index) { +void TextServerFallback::_font_set_face_index(const RID &p_font_rid, int64_t p_face_index) { ERR_FAIL_COND(p_face_index < 0); ERR_FAIL_COND(p_face_index >= 0x7FFF); @@ -1002,7 +979,7 @@ void TextServerFallback::font_set_face_index(const RID &p_font_rid, int64_t p_fa } } -int64_t TextServerFallback::font_get_face_index(const RID &p_font_rid) const { +int64_t TextServerFallback::_font_get_face_index(const RID &p_font_rid) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, 0); @@ -1010,7 +987,7 @@ int64_t TextServerFallback::font_get_face_index(const RID &p_font_rid) const { return fd->face_index; } -int64_t TextServerFallback::font_get_face_count(const RID &p_font_rid) const { +int64_t TextServerFallback::_font_get_face_count(const RID &p_font_rid) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, 0); @@ -1024,6 +1001,9 @@ int64_t TextServerFallback::font_get_face_count(const RID &p_font_rid) const { if (!ft_library) { error = FT_Init_FreeType(&ft_library); ERR_FAIL_COND_V_MSG(error != 0, false, "FreeType: Error initializing library: '" + String(FT_Error_String(error)) + "'."); +#ifdef MODULE_SVG_ENABLED + FT_Property_Set(ft_library, "ot-svg", "svg-hooks", get_tvg_svg_in_ot_hooks()); +#endif } FT_StreamRec stream; @@ -1039,19 +1019,19 @@ int64_t TextServerFallback::font_get_face_count(const RID &p_font_rid) const { fargs.flags = FT_OPEN_MEMORY; fargs.stream = &stream; - FT_Face tmp_face; + FT_Face tmp_face = nullptr; error = FT_Open_Face(ft_library, &fargs, -1, &tmp_face); if (error == 0) { face_count = tmp_face->num_faces; + FT_Done_Face(tmp_face); } - FT_Done_Face(tmp_face); #endif } return face_count; } -BitField<TextServer::FontStyle> TextServerFallback::font_get_style(const RID &p_font_rid) const { +BitField<TextServer::FontStyle> TextServerFallback::_font_get_style(const RID &p_font_rid) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, 0); @@ -1061,7 +1041,7 @@ BitField<TextServer::FontStyle> TextServerFallback::font_get_style(const RID &p_ return fd->style_flags; } -void TextServerFallback::font_set_style_name(const RID &p_font_rid, const String &p_name) { +void TextServerFallback::_font_set_style_name(const RID &p_font_rid, const String &p_name) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1071,7 +1051,7 @@ void TextServerFallback::font_set_style_name(const RID &p_font_rid, const String fd->style_name = p_name; } -String TextServerFallback::font_get_style_name(const RID &p_font_rid) const { +String TextServerFallback::_font_get_style_name(const RID &p_font_rid) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, String()); @@ -1081,7 +1061,7 @@ String TextServerFallback::font_get_style_name(const RID &p_font_rid) const { return fd->style_name; } -void TextServerFallback::font_set_name(const RID &p_font_rid, const String &p_name) { +void TextServerFallback::_font_set_name(const RID &p_font_rid, const String &p_name) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1091,7 +1071,7 @@ void TextServerFallback::font_set_name(const RID &p_font_rid, const String &p_na fd->font_name = p_name; } -String TextServerFallback::font_get_name(const RID &p_font_rid) const { +String TextServerFallback::_font_get_name(const RID &p_font_rid) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, String()); @@ -1101,7 +1081,7 @@ String TextServerFallback::font_get_name(const RID &p_font_rid) const { return fd->font_name; } -void TextServerFallback::font_set_antialiasing(RID p_font_rid, TextServer::FontAntialiasing p_antialiasing) { +void TextServerFallback::_font_set_antialiasing(const RID &p_font_rid, TextServer::FontAntialiasing p_antialiasing) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1112,7 +1092,7 @@ void TextServerFallback::font_set_antialiasing(RID p_font_rid, TextServer::FontA } } -TextServer::FontAntialiasing TextServerFallback::font_get_antialiasing(RID p_font_rid) const { +TextServer::FontAntialiasing TextServerFallback::_font_get_antialiasing(const RID &p_font_rid) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, TextServer::FONT_ANTIALIASING_NONE); @@ -1120,7 +1100,7 @@ TextServer::FontAntialiasing TextServerFallback::font_get_antialiasing(RID p_fon return fd->antialiasing; } -void TextServerFallback::font_set_generate_mipmaps(const RID &p_font_rid, bool p_generate_mipmaps) { +void TextServerFallback::_font_set_generate_mipmaps(const RID &p_font_rid, bool p_generate_mipmaps) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1129,13 +1109,14 @@ void TextServerFallback::font_set_generate_mipmaps(const RID &p_font_rid, bool p for (KeyValue<Vector2i, FontForSizeFallback *> &E : fd->cache) { for (int i = 0; i < E.value->textures.size(); i++) { E.value->textures.write[i].dirty = true; + E.value->textures.write[i].texture = Ref<ImageTexture>(); } } fd->mipmaps = p_generate_mipmaps; } } -bool TextServerFallback::font_get_generate_mipmaps(const RID &p_font_rid) const { +bool TextServerFallback::_font_get_generate_mipmaps(const RID &p_font_rid) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, false); @@ -1143,7 +1124,7 @@ bool TextServerFallback::font_get_generate_mipmaps(const RID &p_font_rid) const return fd->mipmaps; } -void TextServerFallback::font_set_multichannel_signed_distance_field(const RID &p_font_rid, bool p_msdf) { +void TextServerFallback::_font_set_multichannel_signed_distance_field(const RID &p_font_rid, bool p_msdf) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1154,7 +1135,7 @@ void TextServerFallback::font_set_multichannel_signed_distance_field(const RID & } } -bool TextServerFallback::font_is_multichannel_signed_distance_field(const RID &p_font_rid) const { +bool TextServerFallback::_font_is_multichannel_signed_distance_field(const RID &p_font_rid) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, false); @@ -1162,7 +1143,7 @@ bool TextServerFallback::font_is_multichannel_signed_distance_field(const RID &p return fd->msdf; } -void TextServerFallback::font_set_msdf_pixel_range(const RID &p_font_rid, int64_t p_msdf_pixel_range) { +void TextServerFallback::_font_set_msdf_pixel_range(const RID &p_font_rid, int64_t p_msdf_pixel_range) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1173,7 +1154,7 @@ void TextServerFallback::font_set_msdf_pixel_range(const RID &p_font_rid, int64_ } } -int64_t TextServerFallback::font_get_msdf_pixel_range(const RID &p_font_rid) const { +int64_t TextServerFallback::_font_get_msdf_pixel_range(const RID &p_font_rid) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, false); @@ -1181,7 +1162,7 @@ int64_t TextServerFallback::font_get_msdf_pixel_range(const RID &p_font_rid) con return fd->msdf_range; } -void TextServerFallback::font_set_msdf_size(const RID &p_font_rid, int64_t p_msdf_size) { +void TextServerFallback::_font_set_msdf_size(const RID &p_font_rid, int64_t p_msdf_size) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1192,7 +1173,7 @@ void TextServerFallback::font_set_msdf_size(const RID &p_font_rid, int64_t p_msd } } -int64_t TextServerFallback::font_get_msdf_size(const RID &p_font_rid) const { +int64_t TextServerFallback::_font_get_msdf_size(const RID &p_font_rid) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, false); @@ -1200,7 +1181,7 @@ int64_t TextServerFallback::font_get_msdf_size(const RID &p_font_rid) const { return fd->msdf_source_size; } -void TextServerFallback::font_set_fixed_size(const RID &p_font_rid, int64_t p_fixed_size) { +void TextServerFallback::_font_set_fixed_size(const RID &p_font_rid, int64_t p_fixed_size) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1208,7 +1189,7 @@ void TextServerFallback::font_set_fixed_size(const RID &p_font_rid, int64_t p_fi fd->fixed_size = p_fixed_size; } -int64_t TextServerFallback::font_get_fixed_size(const RID &p_font_rid) const { +int64_t TextServerFallback::_font_get_fixed_size(const RID &p_font_rid) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, false); @@ -1216,7 +1197,7 @@ int64_t TextServerFallback::font_get_fixed_size(const RID &p_font_rid) const { return fd->fixed_size; } -void TextServerFallback::font_set_force_autohinter(const RID &p_font_rid, bool p_force_autohinter) { +void TextServerFallback::_font_set_force_autohinter(const RID &p_font_rid, bool p_force_autohinter) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1227,7 +1208,7 @@ void TextServerFallback::font_set_force_autohinter(const RID &p_font_rid, bool p } } -bool TextServerFallback::font_is_force_autohinter(const RID &p_font_rid) const { +bool TextServerFallback::_font_is_force_autohinter(const RID &p_font_rid) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, false); @@ -1235,7 +1216,7 @@ bool TextServerFallback::font_is_force_autohinter(const RID &p_font_rid) const { return fd->force_autohinter; } -void TextServerFallback::font_set_hinting(const RID &p_font_rid, TextServer::Hinting p_hinting) { +void TextServerFallback::_font_set_hinting(const RID &p_font_rid, TextServer::Hinting p_hinting) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1246,7 +1227,7 @@ void TextServerFallback::font_set_hinting(const RID &p_font_rid, TextServer::Hin } } -TextServer::Hinting TextServerFallback::font_get_hinting(const RID &p_font_rid) const { +TextServer::Hinting TextServerFallback::_font_get_hinting(const RID &p_font_rid) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, HINTING_NONE); @@ -1254,7 +1235,7 @@ TextServer::Hinting TextServerFallback::font_get_hinting(const RID &p_font_rid) return fd->hinting; } -void TextServerFallback::font_set_subpixel_positioning(const RID &p_font_rid, TextServer::SubpixelPositioning p_subpixel) { +void TextServerFallback::_font_set_subpixel_positioning(const RID &p_font_rid, TextServer::SubpixelPositioning p_subpixel) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1262,7 +1243,7 @@ void TextServerFallback::font_set_subpixel_positioning(const RID &p_font_rid, Te fd->subpixel_positioning = p_subpixel; } -TextServer::SubpixelPositioning TextServerFallback::font_get_subpixel_positioning(const RID &p_font_rid) const { +TextServer::SubpixelPositioning TextServerFallback::_font_get_subpixel_positioning(const RID &p_font_rid) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, SUBPIXEL_POSITIONING_DISABLED); @@ -1270,7 +1251,7 @@ TextServer::SubpixelPositioning TextServerFallback::font_get_subpixel_positionin return fd->subpixel_positioning; } -void TextServerFallback::font_set_embolden(const RID &p_font_rid, double p_strength) { +void TextServerFallback::_font_set_embolden(const RID &p_font_rid, double p_strength) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1281,7 +1262,7 @@ void TextServerFallback::font_set_embolden(const RID &p_font_rid, double p_stren } } -double TextServerFallback::font_get_embolden(const RID &p_font_rid) const { +double TextServerFallback::_font_get_embolden(const RID &p_font_rid) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, 0.0); @@ -1289,7 +1270,7 @@ double TextServerFallback::font_get_embolden(const RID &p_font_rid) const { return fd->embolden; } -void TextServerFallback::font_set_transform(const RID &p_font_rid, const Transform2D &p_transform) { +void TextServerFallback::_font_set_transform(const RID &p_font_rid, const Transform2D &p_transform) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1300,7 +1281,7 @@ void TextServerFallback::font_set_transform(const RID &p_font_rid, const Transfo } } -Transform2D TextServerFallback::font_get_transform(const RID &p_font_rid) const { +Transform2D TextServerFallback::_font_get_transform(const RID &p_font_rid) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Transform2D()); @@ -1308,7 +1289,7 @@ Transform2D TextServerFallback::font_get_transform(const RID &p_font_rid) const return fd->transform; } -void TextServerFallback::font_set_variation_coordinates(const RID &p_font_rid, const Dictionary &p_variation_coordinates) { +void TextServerFallback::_font_set_variation_coordinates(const RID &p_font_rid, const Dictionary &p_variation_coordinates) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1319,7 +1300,7 @@ void TextServerFallback::font_set_variation_coordinates(const RID &p_font_rid, c } } -Dictionary TextServerFallback::font_get_variation_coordinates(const RID &p_font_rid) const { +Dictionary TextServerFallback::_font_get_variation_coordinates(const RID &p_font_rid) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Dictionary()); @@ -1327,7 +1308,7 @@ Dictionary TextServerFallback::font_get_variation_coordinates(const RID &p_font_ return fd->variation_coordinates; } -void TextServerFallback::font_set_oversampling(const RID &p_font_rid, double p_oversampling) { +void TextServerFallback::_font_set_oversampling(const RID &p_font_rid, double p_oversampling) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1338,7 +1319,7 @@ void TextServerFallback::font_set_oversampling(const RID &p_font_rid, double p_o } } -double TextServerFallback::font_get_oversampling(const RID &p_font_rid) const { +double TextServerFallback::_font_get_oversampling(const RID &p_font_rid) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, 0.0); @@ -1346,7 +1327,7 @@ double TextServerFallback::font_get_oversampling(const RID &p_font_rid) const { return fd->oversampling; } -TypedArray<Vector2i> TextServerFallback::font_get_size_cache_list(const RID &p_font_rid) const { +TypedArray<Vector2i> TextServerFallback::_font_get_size_cache_list(const RID &p_font_rid) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, TypedArray<Vector2i>()); @@ -1358,7 +1339,7 @@ TypedArray<Vector2i> TextServerFallback::font_get_size_cache_list(const RID &p_f return ret; } -void TextServerFallback::font_clear_size_cache(const RID &p_font_rid) { +void TextServerFallback::_font_clear_size_cache(const RID &p_font_rid) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1369,7 +1350,7 @@ void TextServerFallback::font_clear_size_cache(const RID &p_font_rid) { fd->cache.clear(); } -void TextServerFallback::font_remove_size_cache(const RID &p_font_rid, const Vector2i &p_size) { +void TextServerFallback::_font_remove_size_cache(const RID &p_font_rid, const Vector2i &p_size) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1380,7 +1361,7 @@ void TextServerFallback::font_remove_size_cache(const RID &p_font_rid, const Vec } } -void TextServerFallback::font_set_ascent(const RID &p_font_rid, int64_t p_size, double p_ascent) { +void TextServerFallback::_font_set_ascent(const RID &p_font_rid, int64_t p_size, double p_ascent) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1391,7 +1372,7 @@ void TextServerFallback::font_set_ascent(const RID &p_font_rid, int64_t p_size, fd->cache[size]->ascent = p_ascent; } -double TextServerFallback::font_get_ascent(const RID &p_font_rid, int64_t p_size) const { +double TextServerFallback::_font_get_ascent(const RID &p_font_rid, int64_t p_size) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, 0.0); @@ -1407,7 +1388,7 @@ double TextServerFallback::font_get_ascent(const RID &p_font_rid, int64_t p_size } } -void TextServerFallback::font_set_descent(const RID &p_font_rid, int64_t p_size, double p_descent) { +void TextServerFallback::_font_set_descent(const RID &p_font_rid, int64_t p_size, double p_descent) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1417,7 +1398,7 @@ void TextServerFallback::font_set_descent(const RID &p_font_rid, int64_t p_size, fd->cache[size]->descent = p_descent; } -double TextServerFallback::font_get_descent(const RID &p_font_rid, int64_t p_size) const { +double TextServerFallback::_font_get_descent(const RID &p_font_rid, int64_t p_size) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, 0.0); @@ -1433,7 +1414,7 @@ double TextServerFallback::font_get_descent(const RID &p_font_rid, int64_t p_siz } } -void TextServerFallback::font_set_underline_position(const RID &p_font_rid, int64_t p_size, double p_underline_position) { +void TextServerFallback::_font_set_underline_position(const RID &p_font_rid, int64_t p_size, double p_underline_position) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1444,7 +1425,7 @@ void TextServerFallback::font_set_underline_position(const RID &p_font_rid, int6 fd->cache[size]->underline_position = p_underline_position; } -double TextServerFallback::font_get_underline_position(const RID &p_font_rid, int64_t p_size) const { +double TextServerFallback::_font_get_underline_position(const RID &p_font_rid, int64_t p_size) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, 0.0); @@ -1460,7 +1441,7 @@ double TextServerFallback::font_get_underline_position(const RID &p_font_rid, in } } -void TextServerFallback::font_set_underline_thickness(const RID &p_font_rid, int64_t p_size, double p_underline_thickness) { +void TextServerFallback::_font_set_underline_thickness(const RID &p_font_rid, int64_t p_size, double p_underline_thickness) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1471,7 +1452,7 @@ void TextServerFallback::font_set_underline_thickness(const RID &p_font_rid, int fd->cache[size]->underline_thickness = p_underline_thickness; } -double TextServerFallback::font_get_underline_thickness(const RID &p_font_rid, int64_t p_size) const { +double TextServerFallback::_font_get_underline_thickness(const RID &p_font_rid, int64_t p_size) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, 0.0); @@ -1487,7 +1468,7 @@ double TextServerFallback::font_get_underline_thickness(const RID &p_font_rid, i } } -void TextServerFallback::font_set_scale(const RID &p_font_rid, int64_t p_size, double p_scale) { +void TextServerFallback::_font_set_scale(const RID &p_font_rid, int64_t p_size, double p_scale) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1503,7 +1484,7 @@ void TextServerFallback::font_set_scale(const RID &p_font_rid, int64_t p_size, d fd->cache[size]->scale = p_scale; } -double TextServerFallback::font_get_scale(const RID &p_font_rid, int64_t p_size) const { +double TextServerFallback::_font_get_scale(const RID &p_font_rid, int64_t p_size) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, 0.0); @@ -1519,7 +1500,7 @@ double TextServerFallback::font_get_scale(const RID &p_font_rid, int64_t p_size) } } -int64_t TextServerFallback::font_get_texture_count(const RID &p_font_rid, const Vector2i &p_size) const { +int64_t TextServerFallback::_font_get_texture_count(const RID &p_font_rid, const Vector2i &p_size) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, 0); @@ -1531,7 +1512,7 @@ int64_t TextServerFallback::font_get_texture_count(const RID &p_font_rid, const return fd->cache[size]->textures.size(); } -void TextServerFallback::font_clear_textures(const RID &p_font_rid, const Vector2i &p_size) { +void TextServerFallback::_font_clear_textures(const RID &p_font_rid, const Vector2i &p_size) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); MutexLock lock(fd->mutex); @@ -1541,7 +1522,7 @@ void TextServerFallback::font_clear_textures(const RID &p_font_rid, const Vector fd->cache[size]->textures.clear(); } -void TextServerFallback::font_remove_texture(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) { +void TextServerFallback::_font_remove_texture(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1553,7 +1534,7 @@ void TextServerFallback::font_remove_texture(const RID &p_font_rid, const Vector fd->cache[size]->textures.remove_at(p_texture_index); } -void TextServerFallback::font_set_texture_image(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index, const Ref<Image> &p_image) { +void TextServerFallback::_font_set_texture_image(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index, const Ref<Image> &p_image) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); ERR_FAIL_COND(p_image.is_null()); @@ -1566,16 +1547,14 @@ void TextServerFallback::font_set_texture_image(const RID &p_font_rid, const Vec fd->cache[size]->textures.resize(p_texture_index + 1); } - FontTexture &tex = fd->cache[size]->textures.write[p_texture_index]; + ShelfPackTexture &tex = fd->cache[size]->textures.write[p_texture_index]; tex.imgdata = p_image->get_data(); tex.texture_w = p_image->get_width(); tex.texture_h = p_image->get_height(); tex.format = p_image->get_format(); - Ref<Image> img; - img.instantiate(); - img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); + Ref<Image> img = Image::create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); if (fd->mipmaps) { img->generate_mipmaps(); } @@ -1584,7 +1563,7 @@ void TextServerFallback::font_set_texture_image(const RID &p_font_rid, const Vec tex.dirty = false; } -Ref<Image> TextServerFallback::font_get_texture_image(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) const { +Ref<Image> TextServerFallback::_font_get_texture_image(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Ref<Image>()); @@ -1593,15 +1572,12 @@ Ref<Image> TextServerFallback::font_get_texture_image(const RID &p_font_rid, con ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), Ref<Image>()); ERR_FAIL_INDEX_V(p_texture_index, fd->cache[size]->textures.size(), Ref<Image>()); - const FontTexture &tex = fd->cache[size]->textures[p_texture_index]; - Ref<Image> img; - img.instantiate(); - img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); - - return img; + const ShelfPackTexture &tex = fd->cache[size]->textures[p_texture_index]; + return Image::create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); } -void TextServerFallback::font_set_texture_offsets(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index, const PackedInt32Array &p_offset) { +void TextServerFallback::_font_set_texture_offsets(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index, const PackedInt32Array &p_offsets) { + ERR_FAIL_COND(p_offsets.size() % 4 != 0); FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1613,11 +1589,14 @@ void TextServerFallback::font_set_texture_offsets(const RID &p_font_rid, const V fd->cache[size]->textures.resize(p_texture_index + 1); } - FontTexture &tex = fd->cache[size]->textures.write[p_texture_index]; - tex.offsets = p_offset; + ShelfPackTexture &tex = fd->cache[size]->textures.write[p_texture_index]; + tex.shelves.clear(); + for (int32_t i = 0; i < p_offsets.size(); i += 4) { + tex.shelves.push_back(Shelf(p_offsets[i], p_offsets[i + 1], p_offsets[i + 2], p_offsets[i + 3])); + } } -PackedInt32Array TextServerFallback::font_get_texture_offsets(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) const { +PackedInt32Array TextServerFallback::_font_get_texture_offsets(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, PackedInt32Array()); @@ -1626,11 +1605,23 @@ PackedInt32Array TextServerFallback::font_get_texture_offsets(const RID &p_font_ ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), PackedInt32Array()); ERR_FAIL_INDEX_V(p_texture_index, fd->cache[size]->textures.size(), PackedInt32Array()); - const FontTexture &tex = fd->cache[size]->textures[p_texture_index]; - return tex.offsets; + const ShelfPackTexture &tex = fd->cache[size]->textures[p_texture_index]; + PackedInt32Array ret; + ret.resize(tex.shelves.size() * 4); + + int32_t *wr = ret.ptrw(); + int32_t i = 0; + for (const Shelf &E : tex.shelves) { + wr[i * 4] = E.x; + wr[i * 4 + 1] = E.y; + wr[i * 4 + 2] = E.w; + wr[i * 4 + 3] = E.h; + i++; + } + return ret; } -PackedInt32Array TextServerFallback::font_get_glyph_list(const RID &p_font_rid, const Vector2i &p_size) const { +PackedInt32Array TextServerFallback::_font_get_glyph_list(const RID &p_font_rid, const Vector2i &p_size) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, PackedInt32Array()); @@ -1646,7 +1637,7 @@ PackedInt32Array TextServerFallback::font_get_glyph_list(const RID &p_font_rid, return ret; } -void TextServerFallback::font_clear_glyphs(const RID &p_font_rid, const Vector2i &p_size) { +void TextServerFallback::_font_clear_glyphs(const RID &p_font_rid, const Vector2i &p_size) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1657,7 +1648,7 @@ void TextServerFallback::font_clear_glyphs(const RID &p_font_rid, const Vector2i fd->cache[size]->glyph_map.clear(); } -void TextServerFallback::font_remove_glyph(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) { +void TextServerFallback::_font_remove_glyph(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1668,7 +1659,7 @@ void TextServerFallback::font_remove_glyph(const RID &p_font_rid, const Vector2i fd->cache[size]->glyph_map.erase(p_glyph); } -Vector2 TextServerFallback::font_get_glyph_advance(const RID &p_font_rid, int64_t p_size, int64_t p_glyph) const { +Vector2 TextServerFallback::_font_get_glyph_advance(const RID &p_font_rid, int64_t p_size, int64_t p_glyph) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Vector2()); @@ -1696,16 +1687,17 @@ Vector2 TextServerFallback::font_get_glyph_advance(const RID &p_font_rid, int64_ ea.x = fd->embolden * double(size.x) / 64.0; } + double scale = _font_get_scale(p_font_rid, p_size); if (fd->msdf) { return (gl[p_glyph | mod].advance + ea) * (double)p_size / (double)fd->msdf_source_size; - } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_DISABLED) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x > SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) { + } else if ((scale == 1.0) && ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_DISABLED) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x > SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE))) { return (gl[p_glyph | mod].advance + ea).round(); } else { return gl[p_glyph | mod].advance + ea; } } -void TextServerFallback::font_set_glyph_advance(const RID &p_font_rid, int64_t p_size, int64_t p_glyph, const Vector2 &p_advance) { +void TextServerFallback::_font_set_glyph_advance(const RID &p_font_rid, int64_t p_size, int64_t p_glyph, const Vector2 &p_advance) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1720,7 +1712,7 @@ void TextServerFallback::font_set_glyph_advance(const RID &p_font_rid, int64_t p gl[p_glyph].found = true; } -Vector2 TextServerFallback::font_get_glyph_offset(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const { +Vector2 TextServerFallback::_font_get_glyph_offset(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Vector2()); @@ -1750,7 +1742,7 @@ Vector2 TextServerFallback::font_get_glyph_offset(const RID &p_font_rid, const V } } -void TextServerFallback::font_set_glyph_offset(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, const Vector2 &p_offset) { +void TextServerFallback::_font_set_glyph_offset(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, const Vector2 &p_offset) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1765,7 +1757,7 @@ void TextServerFallback::font_set_glyph_offset(const RID &p_font_rid, const Vect gl[p_glyph].found = true; } -Vector2 TextServerFallback::font_get_glyph_size(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const { +Vector2 TextServerFallback::_font_get_glyph_size(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Vector2()); @@ -1795,7 +1787,7 @@ Vector2 TextServerFallback::font_get_glyph_size(const RID &p_font_rid, const Vec } } -void TextServerFallback::font_set_glyph_size(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, const Vector2 &p_gl_size) { +void TextServerFallback::_font_set_glyph_size(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, const Vector2 &p_gl_size) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1810,7 +1802,7 @@ void TextServerFallback::font_set_glyph_size(const RID &p_font_rid, const Vector gl[p_glyph].found = true; } -Rect2 TextServerFallback::font_get_glyph_uv_rect(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const { +Rect2 TextServerFallback::_font_get_glyph_uv_rect(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Rect2()); @@ -1835,7 +1827,7 @@ Rect2 TextServerFallback::font_get_glyph_uv_rect(const RID &p_font_rid, const Ve return gl[p_glyph | mod].uv_rect; } -void TextServerFallback::font_set_glyph_uv_rect(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, const Rect2 &p_uv_rect) { +void TextServerFallback::_font_set_glyph_uv_rect(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, const Rect2 &p_uv_rect) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1850,7 +1842,7 @@ void TextServerFallback::font_set_glyph_uv_rect(const RID &p_font_rid, const Vec gl[p_glyph].found = true; } -int64_t TextServerFallback::font_get_glyph_texture_idx(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const { +int64_t TextServerFallback::_font_get_glyph_texture_idx(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, -1); @@ -1875,7 +1867,7 @@ int64_t TextServerFallback::font_get_glyph_texture_idx(const RID &p_font_rid, co return gl[p_glyph | mod].texture_idx; } -void TextServerFallback::font_set_glyph_texture_idx(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, int64_t p_texture_idx) { +void TextServerFallback::_font_set_glyph_texture_idx(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, int64_t p_texture_idx) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -1890,7 +1882,7 @@ void TextServerFallback::font_set_glyph_texture_idx(const RID &p_font_rid, const gl[p_glyph].found = true; } -RID TextServerFallback::font_get_glyph_texture_rid(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const { +RID TextServerFallback::_font_get_glyph_texture_rid(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, RID()); @@ -1917,10 +1909,8 @@ RID TextServerFallback::font_get_glyph_texture_rid(const RID &p_font_rid, const if (RenderingServer::get_singleton() != nullptr) { if (gl[p_glyph | mod].texture_idx != -1) { if (fd->cache[size]->textures[gl[p_glyph | mod].texture_idx].dirty) { - FontTexture &tex = fd->cache[size]->textures.write[gl[p_glyph | mod].texture_idx]; - Ref<Image> img; - img.instantiate(); - img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); + ShelfPackTexture &tex = fd->cache[size]->textures.write[gl[p_glyph | mod].texture_idx]; + Ref<Image> img = Image::create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); if (fd->mipmaps) { img->generate_mipmaps(); } @@ -1938,7 +1928,7 @@ RID TextServerFallback::font_get_glyph_texture_rid(const RID &p_font_rid, const return RID(); } -Size2 TextServerFallback::font_get_glyph_texture_size(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const { +Size2 TextServerFallback::_font_get_glyph_texture_size(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Size2()); @@ -1965,10 +1955,8 @@ Size2 TextServerFallback::font_get_glyph_texture_size(const RID &p_font_rid, con if (RenderingServer::get_singleton() != nullptr) { if (gl[p_glyph | mod].texture_idx != -1) { if (fd->cache[size]->textures[gl[p_glyph | mod].texture_idx].dirty) { - FontTexture &tex = fd->cache[size]->textures.write[gl[p_glyph | mod].texture_idx]; - Ref<Image> img; - img.instantiate(); - img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); + ShelfPackTexture &tex = fd->cache[size]->textures.write[gl[p_glyph | mod].texture_idx]; + Ref<Image> img = Image::create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); if (fd->mipmaps) { img->generate_mipmaps(); } @@ -1986,7 +1974,7 @@ Size2 TextServerFallback::font_get_glyph_texture_size(const RID &p_font_rid, con return Size2(); } -Dictionary TextServerFallback::font_get_glyph_contours(const RID &p_font_rid, int64_t p_size, int64_t p_index) const { +Dictionary TextServerFallback::_font_get_glyph_contours(const RID &p_font_rid, int64_t p_size, int64_t p_index) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Dictionary()); @@ -2036,7 +2024,7 @@ Dictionary TextServerFallback::font_get_glyph_contours(const RID &p_font_rid, in #endif } -TypedArray<Vector2i> TextServerFallback::font_get_kerning_list(const RID &p_font_rid, int64_t p_size) const { +TypedArray<Vector2i> TextServerFallback::_font_get_kerning_list(const RID &p_font_rid, int64_t p_size) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, TypedArray<Vector2i>()); @@ -2052,7 +2040,7 @@ TypedArray<Vector2i> TextServerFallback::font_get_kerning_list(const RID &p_font return ret; } -void TextServerFallback::font_clear_kerning_map(const RID &p_font_rid, int64_t p_size) { +void TextServerFallback::_font_clear_kerning_map(const RID &p_font_rid, int64_t p_size) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2063,7 +2051,7 @@ void TextServerFallback::font_clear_kerning_map(const RID &p_font_rid, int64_t p fd->cache[size]->kerning_map.clear(); } -void TextServerFallback::font_remove_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair) { +void TextServerFallback::_font_remove_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2074,7 +2062,7 @@ void TextServerFallback::font_remove_kerning(const RID &p_font_rid, int64_t p_si fd->cache[size]->kerning_map.erase(p_glyph_pair); } -void TextServerFallback::font_set_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair, const Vector2 &p_kerning) { +void TextServerFallback::_font_set_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair, const Vector2 &p_kerning) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2085,7 +2073,7 @@ void TextServerFallback::font_set_kerning(const RID &p_font_rid, int64_t p_size, fd->cache[size]->kerning_map[p_glyph_pair] = p_kerning; } -Vector2 TextServerFallback::font_get_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair) const { +Vector2 TextServerFallback::_font_get_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Vector2()); @@ -2120,15 +2108,17 @@ Vector2 TextServerFallback::font_get_kerning(const RID &p_font_rid, int64_t p_si return Vector2(); } -int64_t TextServerFallback::font_get_glyph_index(const RID &p_font_rid, int64_t p_size, int64_t p_char, int64_t p_variation_selector) const { +int64_t TextServerFallback::_font_get_glyph_index(const RID &p_font_rid, int64_t p_size, int64_t p_char, int64_t p_variation_selector) const { ERR_FAIL_COND_V_MSG((p_char >= 0xd800 && p_char <= 0xdfff) || (p_char > 0x10ffff), 0, "Unicode parsing error: Invalid unicode codepoint " + String::num_int64(p_char, 16) + "."); return (int64_t)p_char; } -bool TextServerFallback::font_has_char(const RID &p_font_rid, int64_t p_char) const { +bool TextServerFallback::_font_has_char(const RID &p_font_rid, int64_t p_char) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); - ERR_FAIL_COND_V(!fd, false); ERR_FAIL_COND_V_MSG((p_char >= 0xd800 && p_char <= 0xdfff) || (p_char > 0x10ffff), false, "Unicode parsing error: Invalid unicode codepoint " + String::num_int64(p_char, 16) + "."); + if (!fd) { + return false; + } MutexLock lock(fd->mutex); if (fd->cache.is_empty()) { @@ -2144,7 +2134,7 @@ bool TextServerFallback::font_has_char(const RID &p_font_rid, int64_t p_char) co return (at_size) ? at_size->glyph_map.has((int32_t)p_char) : false; } -String TextServerFallback::font_get_supported_chars(const RID &p_font_rid) const { +String TextServerFallback::_font_get_supported_chars(const RID &p_font_rid) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, String()); @@ -2177,7 +2167,7 @@ String TextServerFallback::font_get_supported_chars(const RID &p_font_rid) const return chars; } -void TextServerFallback::font_render_range(const RID &p_font_rid, const Vector2i &p_size, int64_t p_start, int64_t p_end) { +void TextServerFallback::_font_render_range(const RID &p_font_rid, const Vector2i &p_size, int64_t p_start, int64_t p_end) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); ERR_FAIL_COND_MSG((p_start >= 0xd800 && p_start <= 0xdfff) || (p_start > 0x10ffff), "Unicode parsing error: Invalid unicode codepoint " + String::num_int64(p_start, 16) + "."); @@ -2212,7 +2202,7 @@ void TextServerFallback::font_render_range(const RID &p_font_rid, const Vector2i } } -void TextServerFallback::font_render_glyph(const RID &p_font_rid, const Vector2i &p_size, int64_t p_index) { +void TextServerFallback::_font_render_glyph(const RID &p_font_rid, const Vector2i &p_size, int64_t p_index) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2243,7 +2233,7 @@ void TextServerFallback::font_render_glyph(const RID &p_font_rid, const Vector2i #endif } -void TextServerFallback::font_draw_glyph(const RID &p_font_rid, const RID &p_canvas, int64_t p_size, const Vector2 &p_pos, int64_t p_index, const Color &p_color) const { +void TextServerFallback::_font_draw_glyph(const RID &p_font_rid, const RID &p_canvas, int64_t p_size, const Vector2 &p_pos, int64_t p_index, const Color &p_color) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2292,10 +2282,8 @@ void TextServerFallback::font_draw_glyph(const RID &p_font_rid, const RID &p_can #endif if (RenderingServer::get_singleton() != nullptr) { if (fd->cache[size]->textures[gl.texture_idx].dirty) { - FontTexture &tex = fd->cache[size]->textures.write[gl.texture_idx]; - Ref<Image> img; - img.instantiate(); - img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); + ShelfPackTexture &tex = fd->cache[size]->textures.write[gl.texture_idx]; + Ref<Image> img = Image::create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); if (fd->mipmaps) { img->generate_mipmaps(); } @@ -2314,12 +2302,14 @@ void TextServerFallback::font_draw_glyph(const RID &p_font_rid, const RID &p_can RenderingServer::get_singleton()->canvas_item_add_msdf_texture_rect_region(p_canvas, Rect2(cpos, csize), texture, gl.uv_rect, modulate, 0, fd->msdf_range); } else { Point2 cpos = p_pos; - cpos.y = Math::floor(cpos.y); + double scale = _font_get_scale(p_font_rid, p_size); if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) { - cpos.x = ((int)Math::floor(cpos.x + 0.125)); + cpos.x = cpos.x + 0.125; } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) { - cpos.x = ((int)Math::floor(cpos.x + 0.25)); - } else { + cpos.x = cpos.x + 0.25; + } + if (scale == 1.0) { + cpos.y = Math::floor(cpos.y); cpos.x = Math::floor(cpos.x); } cpos += gl.rect.position; @@ -2335,7 +2325,7 @@ void TextServerFallback::font_draw_glyph(const RID &p_font_rid, const RID &p_can } } -void TextServerFallback::font_draw_glyph_outline(const RID &p_font_rid, const RID &p_canvas, int64_t p_size, int64_t p_outline_size, const Vector2 &p_pos, int64_t p_index, const Color &p_color) const { +void TextServerFallback::_font_draw_glyph_outline(const RID &p_font_rid, const RID &p_canvas, int64_t p_size, int64_t p_outline_size, const Vector2 &p_pos, int64_t p_index, const Color &p_color) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2384,10 +2374,8 @@ void TextServerFallback::font_draw_glyph_outline(const RID &p_font_rid, const RI #endif if (RenderingServer::get_singleton() != nullptr) { if (fd->cache[size]->textures[gl.texture_idx].dirty) { - FontTexture &tex = fd->cache[size]->textures.write[gl.texture_idx]; - Ref<Image> img; - img.instantiate(); - img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); + ShelfPackTexture &tex = fd->cache[size]->textures.write[gl.texture_idx]; + Ref<Image> img = Image::create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); if (fd->mipmaps) { img->generate_mipmaps(); } @@ -2406,12 +2394,14 @@ void TextServerFallback::font_draw_glyph_outline(const RID &p_font_rid, const RI RenderingServer::get_singleton()->canvas_item_add_msdf_texture_rect_region(p_canvas, Rect2(cpos, csize), texture, gl.uv_rect, modulate, p_outline_size * 2, fd->msdf_range); } else { Point2 cpos = p_pos; - cpos.y = Math::floor(cpos.y); + double scale = _font_get_scale(p_font_rid, p_size); if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) { - cpos.x = ((int)Math::floor(cpos.x + 0.125)); + cpos.x = cpos.x + 0.125; } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) { - cpos.x = ((int)Math::floor(cpos.x + 0.25)); - } else { + cpos.x = cpos.x + 0.25; + } + if (scale == 1.0) { + cpos.y = Math::floor(cpos.y); cpos.x = Math::floor(cpos.x); } cpos += gl.rect.position; @@ -2427,7 +2417,7 @@ void TextServerFallback::font_draw_glyph_outline(const RID &p_font_rid, const RI } } -bool TextServerFallback::font_is_language_supported(const RID &p_font_rid, const String &p_language) const { +bool TextServerFallback::_font_is_language_supported(const RID &p_font_rid, const String &p_language) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, false); @@ -2439,7 +2429,7 @@ bool TextServerFallback::font_is_language_supported(const RID &p_font_rid, const } } -void TextServerFallback::font_set_language_support_override(const RID &p_font_rid, const String &p_language, bool p_supported) { +void TextServerFallback::_font_set_language_support_override(const RID &p_font_rid, const String &p_language, bool p_supported) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2447,7 +2437,7 @@ void TextServerFallback::font_set_language_support_override(const RID &p_font_ri fd->language_support_overrides[p_language] = p_supported; } -bool TextServerFallback::font_get_language_support_override(const RID &p_font_rid, const String &p_language) { +bool TextServerFallback::_font_get_language_support_override(const RID &p_font_rid, const String &p_language) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, false); @@ -2455,7 +2445,7 @@ bool TextServerFallback::font_get_language_support_override(const RID &p_font_ri return fd->language_support_overrides[p_language]; } -void TextServerFallback::font_remove_language_support_override(const RID &p_font_rid, const String &p_language) { +void TextServerFallback::_font_remove_language_support_override(const RID &p_font_rid, const String &p_language) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2463,7 +2453,7 @@ void TextServerFallback::font_remove_language_support_override(const RID &p_font fd->language_support_overrides.erase(p_language); } -PackedStringArray TextServerFallback::font_get_language_support_overrides(const RID &p_font_rid) { +PackedStringArray TextServerFallback::_font_get_language_support_overrides(const RID &p_font_rid) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, PackedStringArray()); @@ -2475,7 +2465,7 @@ PackedStringArray TextServerFallback::font_get_language_support_overrides(const return out; } -bool TextServerFallback::font_is_script_supported(const RID &p_font_rid, const String &p_script) const { +bool TextServerFallback::_font_is_script_supported(const RID &p_font_rid, const String &p_script) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, false); @@ -2487,7 +2477,7 @@ bool TextServerFallback::font_is_script_supported(const RID &p_font_rid, const S } } -void TextServerFallback::font_set_script_support_override(const RID &p_font_rid, const String &p_script, bool p_supported) { +void TextServerFallback::_font_set_script_support_override(const RID &p_font_rid, const String &p_script, bool p_supported) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2495,7 +2485,7 @@ void TextServerFallback::font_set_script_support_override(const RID &p_font_rid, fd->script_support_overrides[p_script] = p_supported; } -bool TextServerFallback::font_get_script_support_override(const RID &p_font_rid, const String &p_script) { +bool TextServerFallback::_font_get_script_support_override(const RID &p_font_rid, const String &p_script) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, false); @@ -2503,7 +2493,7 @@ bool TextServerFallback::font_get_script_support_override(const RID &p_font_rid, return fd->script_support_overrides[p_script]; } -void TextServerFallback::font_remove_script_support_override(const RID &p_font_rid, const String &p_script) { +void TextServerFallback::_font_remove_script_support_override(const RID &p_font_rid, const String &p_script) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2513,7 +2503,7 @@ void TextServerFallback::font_remove_script_support_override(const RID &p_font_r fd->script_support_overrides.erase(p_script); } -PackedStringArray TextServerFallback::font_get_script_support_overrides(const RID &p_font_rid) { +PackedStringArray TextServerFallback::_font_get_script_support_overrides(const RID &p_font_rid) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, PackedStringArray()); @@ -2525,7 +2515,7 @@ PackedStringArray TextServerFallback::font_get_script_support_overrides(const RI return out; } -void TextServerFallback::font_set_opentype_feature_overrides(const RID &p_font_rid, const Dictionary &p_overrides) { +void TextServerFallback::_font_set_opentype_feature_overrides(const RID &p_font_rid, const Dictionary &p_overrides) { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND(!fd); @@ -2535,7 +2525,7 @@ void TextServerFallback::font_set_opentype_feature_overrides(const RID &p_font_r fd->feature_overrides = p_overrides; } -Dictionary TextServerFallback::font_get_opentype_feature_overrides(const RID &p_font_rid) const { +Dictionary TextServerFallback::_font_get_opentype_feature_overrides(const RID &p_font_rid) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Dictionary()); @@ -2543,11 +2533,11 @@ Dictionary TextServerFallback::font_get_opentype_feature_overrides(const RID &p_ return fd->feature_overrides; } -Dictionary TextServerFallback::font_supported_feature_list(const RID &p_font_rid) const { +Dictionary TextServerFallback::_font_supported_feature_list(const RID &p_font_rid) const { return Dictionary(); } -Dictionary TextServerFallback::font_supported_variation_list(const RID &p_font_rid) const { +Dictionary TextServerFallback::_font_supported_variation_list(const RID &p_font_rid) const { FontFallback *fd = font_owner.get_or_null(p_font_rid); ERR_FAIL_COND_V(!fd, Dictionary()); @@ -2557,11 +2547,11 @@ Dictionary TextServerFallback::font_supported_variation_list(const RID &p_font_r return fd->supported_varaitions; } -double TextServerFallback::font_get_global_oversampling() const { +double TextServerFallback::_font_get_global_oversampling() const { return oversampling; } -void TextServerFallback::font_set_global_oversampling(double p_oversampling) { +void TextServerFallback::_font_set_global_oversampling(double p_oversampling) { _THREAD_SAFE_METHOD_ if (oversampling != p_oversampling) { oversampling = p_oversampling; @@ -2569,8 +2559,8 @@ void TextServerFallback::font_set_global_oversampling(double p_oversampling) { font_owner.get_owned_list(&fonts); bool font_cleared = false; for (const RID &E : fonts) { - if (!font_is_multichannel_signed_distance_field(E) && font_get_oversampling(E) <= 0) { - font_clear_size_cache(E); + if (!_font_is_multichannel_signed_distance_field(E) && _font_get_oversampling(E) <= 0) { + _font_clear_size_cache(E); font_cleared = true; } } @@ -2625,7 +2615,7 @@ void TextServerFallback::full_copy(ShapedTextDataFallback *p_shaped) { p_shaped->parent = RID(); } -RID TextServerFallback::create_shaped_text(TextServer::Direction p_direction, TextServer::Orientation p_orientation) { +RID TextServerFallback::_create_shaped_text(TextServer::Direction p_direction, TextServer::Orientation p_orientation) { _THREAD_SAFE_METHOD_ ShapedTextDataFallback *sd = memnew(ShapedTextDataFallback); @@ -2635,7 +2625,7 @@ RID TextServerFallback::create_shaped_text(TextServer::Direction p_direction, Te return shaped_owner.make_rid(sd); } -void TextServerFallback::shaped_text_clear(const RID &p_shaped) { +void TextServerFallback::_shaped_text_clear(const RID &p_shaped) { ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND(!sd); @@ -2649,21 +2639,21 @@ void TextServerFallback::shaped_text_clear(const RID &p_shaped) { invalidate(sd); } -void TextServerFallback::shaped_text_set_direction(const RID &p_shaped, TextServer::Direction p_direction) { +void TextServerFallback::_shaped_text_set_direction(const 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(const RID &p_shaped) const { +TextServer::Direction TextServerFallback::_shaped_text_get_direction(const RID &p_shaped) const { return TextServer::DIRECTION_LTR; } -TextServer::Direction TextServerFallback::shaped_text_get_inferred_direction(const RID &p_shaped) const { +TextServer::Direction TextServerFallback::_shaped_text_get_inferred_direction(const RID &p_shaped) const { return TextServer::DIRECTION_LTR; } -void TextServerFallback::shaped_text_set_custom_punctuation(const RID &p_shaped, const String &p_punct) { +void TextServerFallback::_shaped_text_set_custom_punctuation(const RID &p_shaped, const String &p_punct) { _THREAD_SAFE_METHOD_ ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND(!sd); @@ -2677,14 +2667,14 @@ void TextServerFallback::shaped_text_set_custom_punctuation(const RID &p_shaped, } } -String TextServerFallback::shaped_text_get_custom_punctuation(const RID &p_shaped) const { +String TextServerFallback::_shaped_text_get_custom_punctuation(const RID &p_shaped) const { _THREAD_SAFE_METHOD_ const ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, String()); return sd->custom_punct; } -void TextServerFallback::shaped_text_set_orientation(const RID &p_shaped, TextServer::Orientation p_orientation) { +void TextServerFallback::_shaped_text_set_orientation(const RID &p_shaped, TextServer::Orientation p_orientation) { ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND(!sd); @@ -2698,11 +2688,11 @@ void TextServerFallback::shaped_text_set_orientation(const RID &p_shaped, TextSe } } -void TextServerFallback::shaped_text_set_bidi_override(const RID &p_shaped, const Array &p_override) { +void TextServerFallback::_shaped_text_set_bidi_override(const RID &p_shaped, const Array &p_override) { // No BiDi support, ignore. } -TextServer::Orientation TextServerFallback::shaped_text_get_orientation(const RID &p_shaped) const { +TextServer::Orientation TextServerFallback::_shaped_text_get_orientation(const RID &p_shaped) const { const ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, TextServer::ORIENTATION_HORIZONTAL); @@ -2710,7 +2700,7 @@ TextServer::Orientation TextServerFallback::shaped_text_get_orientation(const RI return sd->orientation; } -void TextServerFallback::shaped_text_set_preserve_invalid(const RID &p_shaped, bool p_enabled) { +void TextServerFallback::_shaped_text_set_preserve_invalid(const RID &p_shaped, bool p_enabled) { ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); MutexLock lock(sd->mutex); @@ -2724,7 +2714,7 @@ void TextServerFallback::shaped_text_set_preserve_invalid(const RID &p_shaped, b } } -bool TextServerFallback::shaped_text_get_preserve_invalid(const RID &p_shaped) const { +bool TextServerFallback::_shaped_text_get_preserve_invalid(const RID &p_shaped) const { const ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, false); @@ -2732,7 +2722,7 @@ bool TextServerFallback::shaped_text_get_preserve_invalid(const RID &p_shaped) c return sd->preserve_invalid; } -void TextServerFallback::shaped_text_set_preserve_control(const RID &p_shaped, bool p_enabled) { +void TextServerFallback::_shaped_text_set_preserve_control(const RID &p_shaped, bool p_enabled) { ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND(!sd); @@ -2746,7 +2736,7 @@ void TextServerFallback::shaped_text_set_preserve_control(const RID &p_shaped, b } } -bool TextServerFallback::shaped_text_get_preserve_control(const RID &p_shaped) const { +bool TextServerFallback::_shaped_text_get_preserve_control(const RID &p_shaped) const { const ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, false); @@ -2754,7 +2744,7 @@ bool TextServerFallback::shaped_text_get_preserve_control(const RID &p_shaped) c return sd->preserve_control; } -void TextServerFallback::shaped_text_set_spacing(const RID &p_shaped, SpacingType p_spacing, int64_t p_value) { +void TextServerFallback::_shaped_text_set_spacing(const RID &p_shaped, SpacingType p_spacing, int64_t p_value) { ERR_FAIL_INDEX((int)p_spacing, 4); ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND(!sd); @@ -2769,7 +2759,7 @@ void TextServerFallback::shaped_text_set_spacing(const RID &p_shaped, SpacingTyp } } -int64_t TextServerFallback::shaped_text_get_spacing(const RID &p_shaped, SpacingType p_spacing) const { +int64_t TextServerFallback::_shaped_text_get_spacing(const RID &p_shaped, SpacingType p_spacing) const { ERR_FAIL_INDEX_V((int)p_spacing, 4, 0); const ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); @@ -2779,20 +2769,20 @@ int64_t TextServerFallback::shaped_text_get_spacing(const RID &p_shaped, Spacing return sd->extra_spacing[p_spacing]; } -int64_t TextServerFallback::shaped_get_span_count(const RID &p_shaped) const { +int64_t TextServerFallback::_shaped_get_span_count(const RID &p_shaped) const { ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, 0); return sd->spans.size(); } -Variant TextServerFallback::shaped_get_span_meta(const RID &p_shaped, int64_t p_index) const { +Variant TextServerFallback::_shaped_get_span_meta(const RID &p_shaped, int64_t p_index) const { ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, Variant()); ERR_FAIL_INDEX_V(p_index, sd->spans.size(), Variant()); return sd->spans[p_index].meta; } -void TextServerFallback::shaped_set_span_update_font(const RID &p_shaped, int64_t p_index, const TypedArray<RID> &p_fonts, int64_t p_size, const Dictionary &p_opentype_features) { +void TextServerFallback::_shaped_set_span_update_font(const RID &p_shaped, int64_t p_index, const TypedArray<RID> &p_fonts, int64_t p_size, const Dictionary &p_opentype_features) { ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND(!sd); ERR_FAIL_INDEX(p_index, sd->spans.size()); @@ -2803,7 +2793,7 @@ void TextServerFallback::shaped_set_span_update_font(const RID &p_shaped, int64_ Array fonts_no_match; int font_count = p_fonts.size(); for (int i = 0; i < font_count; i++) { - if (font_is_language_supported(p_fonts[i], span.language)) { + if (_font_is_language_supported(p_fonts[i], span.language)) { span.fonts.push_back(p_fonts[i]); } else { fonts_no_match.push_back(p_fonts[i]); @@ -2816,7 +2806,7 @@ void TextServerFallback::shaped_set_span_update_font(const RID &p_shaped, int64_ sd->valid = false; } -bool TextServerFallback::shaped_text_add_string(const RID &p_shaped, const String &p_text, const TypedArray<RID> &p_fonts, int64_t p_size, const Dictionary &p_opentype_features, const String &p_language, const Variant &p_meta) { +bool TextServerFallback::_shaped_text_add_string(const RID &p_shaped, const String &p_text, const TypedArray<RID> &p_fonts, int64_t p_size, const Dictionary &p_opentype_features, const String &p_language, const Variant &p_meta) { ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, false); @@ -2842,8 +2832,11 @@ bool TextServerFallback::shaped_text_add_string(const RID &p_shaped, const Strin // Pre-sort fonts, push fonts with the language support first. Array fonts_no_match; int font_count = p_fonts.size(); - for (int i = 0; i < font_count; i++) { - if (font_is_language_supported(p_fonts[i], p_language)) { + if (font_count > 0) { + span.fonts.push_back(p_fonts[0]); + } + for (int i = 1; i < font_count; i++) { + if (_font_is_language_supported(p_fonts[i], p_language)) { span.fonts.push_back(p_fonts[i]); } else { fonts_no_match.push_back(p_fonts[i]); @@ -2864,7 +2857,7 @@ bool TextServerFallback::shaped_text_add_string(const RID &p_shaped, const Strin return true; } -bool TextServerFallback::shaped_text_add_object(const RID &p_shaped, const Variant &p_key, const Size2 &p_size, InlineAlignment p_inline_align, int64_t p_length) { +bool TextServerFallback::_shaped_text_add_object(const RID &p_shaped, const Variant &p_key, const Size2 &p_size, InlineAlignment p_inline_align, int64_t p_length) { ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, false); @@ -2895,7 +2888,7 @@ bool TextServerFallback::shaped_text_add_object(const RID &p_shaped, const Varia return true; } -bool TextServerFallback::shaped_text_resize_object(const RID &p_shaped, const Variant &p_key, const Size2 &p_size, InlineAlignment p_inline_align) { +bool TextServerFallback::_shaped_text_resize_object(const RID &p_shaped, const Variant &p_key, const Size2 &p_size, InlineAlignment p_inline_align) { ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, false); @@ -2936,14 +2929,14 @@ bool TextServerFallback::shaped_text_resize_object(const RID &p_shaped, const Va } else { if (gl.font_rid.is_valid()) { if (sd->orientation == ORIENTATION_HORIZONTAL) { - sd->ascent = MAX(sd->ascent, font_get_ascent(gl.font_rid, gl.font_size)); - sd->descent = MAX(sd->descent, font_get_descent(gl.font_rid, gl.font_size)); + sd->ascent = MAX(sd->ascent, _font_get_ascent(gl.font_rid, gl.font_size)); + sd->descent = MAX(sd->descent, _font_get_descent(gl.font_rid, gl.font_size)); } else { - sd->ascent = MAX(sd->ascent, Math::round(font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5)); - sd->descent = MAX(sd->descent, Math::round(font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5)); + sd->ascent = MAX(sd->ascent, Math::round(_font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5)); + sd->descent = MAX(sd->descent, Math::round(_font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).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)); + 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) { @@ -3030,7 +3023,7 @@ void TextServerFallback::_realign(ShapedTextDataFallback *p_sd) const { p_sd->descent = full_descent; } -RID TextServerFallback::shaped_text_substr(const RID &p_shaped, int64_t p_start, int64_t p_length) const { +RID TextServerFallback::_shaped_text_substr(const RID &p_shaped, int64_t p_start, int64_t p_length) const { _THREAD_SAFE_METHOD_ const ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); @@ -3038,10 +3031,10 @@ RID TextServerFallback::shaped_text_substr(const RID &p_shaped, int64_t p_start, MutexLock lock(sd->mutex); if (sd->parent != RID()) { - return shaped_text_substr(sd->parent, p_start, p_length); + return _shaped_text_substr(sd->parent, p_start, p_length); } if (!sd->valid) { - const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + 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()); @@ -3096,11 +3089,11 @@ RID TextServerFallback::shaped_text_substr(const RID &p_shaped, int64_t p_start, } else { if (gl.font_rid.is_valid()) { if (new_sd->orientation == ORIENTATION_HORIZONTAL) { - new_sd->ascent = MAX(new_sd->ascent, font_get_ascent(gl.font_rid, gl.font_size)); - new_sd->descent = MAX(new_sd->descent, font_get_descent(gl.font_rid, gl.font_size)); + new_sd->ascent = MAX(new_sd->ascent, _font_get_ascent(gl.font_rid, gl.font_size)); + new_sd->descent = MAX(new_sd->descent, _font_get_descent(gl.font_rid, gl.font_size)); } else { - new_sd->ascent = MAX(new_sd->ascent, Math::round(font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5)); - new_sd->descent = MAX(new_sd->descent, Math::round(font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5)); + new_sd->ascent = MAX(new_sd->ascent, Math::round(_font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5)); + new_sd->descent = MAX(new_sd->descent, Math::round(_font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).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. @@ -3124,7 +3117,7 @@ RID TextServerFallback::shaped_text_substr(const RID &p_shaped, int64_t p_start, return shaped_owner.make_rid(new_sd); } -RID TextServerFallback::shaped_text_get_parent(const RID &p_shaped) const { +RID TextServerFallback::_shaped_text_get_parent(const RID &p_shaped) const { ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, RID()); @@ -3132,16 +3125,16 @@ RID TextServerFallback::shaped_text_get_parent(const RID &p_shaped) const { return sd->parent; } -double TextServerFallback::shaped_text_fit_to_width(const RID &p_shaped, double p_width, BitField<JustificationFlag> p_jst_flags) { +double TextServerFallback::_shaped_text_fit_to_width(const RID &p_shaped, double p_width, BitField<JustificationFlag> p_jst_flags) { ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, 0.0); MutexLock lock(sd->mutex); if (!sd->valid) { - const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + 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); + const_cast<TextServerFallback *>(this)->_shaped_text_update_justification_ops(p_shaped); } int start_pos = 0; @@ -3241,16 +3234,16 @@ double TextServerFallback::shaped_text_fit_to_width(const RID &p_shaped, double return Math::ceil(justification_width); } -double TextServerFallback::shaped_text_tab_align(const RID &p_shaped, const PackedFloat32Array &p_tab_stops) { +double TextServerFallback::_shaped_text_tab_align(const RID &p_shaped, const PackedFloat32Array &p_tab_stops) { ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, 0.0); MutexLock lock(sd->mutex); if (!sd->valid) { - const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + const_cast<TextServerFallback *>(this)->_shaped_text_shape(p_shaped); } if (!sd->line_breaks_valid) { - const_cast<TextServerFallback *>(this)->shaped_text_update_breaks(p_shaped); + const_cast<TextServerFallback *>(this)->_shaped_text_update_breaks(p_shaped); } for (int i = 0; i < p_tab_stops.size(); i++) { @@ -3297,13 +3290,13 @@ double TextServerFallback::shaped_text_tab_align(const RID &p_shaped, const Pack return 0.0; } -bool TextServerFallback::shaped_text_update_breaks(const RID &p_shaped) { +bool TextServerFallback::_shaped_text_update_breaks(const RID &p_shaped) { ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, false); MutexLock lock(sd->mutex); if (!sd->valid) { - shaped_text_shape(p_shaped); + _shaped_text_shape(p_shaped); } if (sd->line_breaks_valid) { @@ -3353,29 +3346,29 @@ bool TextServerFallback::shaped_text_update_breaks(const RID &p_shaped) { return sd->line_breaks_valid; } -bool TextServerFallback::shaped_text_update_justification_ops(const RID &p_shaped) { +bool TextServerFallback::_shaped_text_update_justification_ops(const RID &p_shaped) { ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, false); MutexLock lock(sd->mutex); if (!sd->valid) { - shaped_text_shape(p_shaped); + _shaped_text_shape(p_shaped); } if (!sd->line_breaks_valid) { - shaped_text_update_breaks(p_shaped); + _shaped_text_update_breaks(p_shaped); } sd->justification_ops_valid = true; // Not supported by fallback server. return true; } -void TextServerFallback::shaped_text_overrun_trim_to_width(const RID &p_shaped_line, double p_width, BitField<TextServer::TextOverrunFlag> p_trim_flags) { +void TextServerFallback::_shaped_text_overrun_trim_to_width(const RID &p_shaped_line, double p_width, BitField<TextServer::TextOverrunFlag> p_trim_flags) { ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped_line); ERR_FAIL_COND_MSG(!sd, "ShapedTextDataFallback invalid."); MutexLock lock(sd->mutex); if (!sd->valid) { - shaped_text_shape(p_shaped_line); + _shaped_text_shape(p_shaped_line); } sd->text_trimmed = false; @@ -3414,30 +3407,30 @@ void TextServerFallback::shaped_text_overrun_trim_to_width(const RID &p_shaped_l // Find usable fonts, if fonts from the last glyph do not have required chars. RID dot_gl_font_rid = sd_glyphs[sd_size - 1].font_rid; - if (!font_has_char(dot_gl_font_rid, '.')) { + if (!_font_has_char(dot_gl_font_rid, '.')) { const Array &fonts = spans[spans.size() - 1].fonts; for (int i = 0; i < fonts.size(); i++) { - if (font_has_char(fonts[i], '.')) { + if (_font_has_char(fonts[i], '.')) { dot_gl_font_rid = fonts[i]; break; } } } RID whitespace_gl_font_rid = sd_glyphs[sd_size - 1].font_rid; - if (!font_has_char(whitespace_gl_font_rid, '.')) { + if (!_font_has_char(whitespace_gl_font_rid, '.')) { const Array &fonts = spans[spans.size() - 1].fonts; for (int i = 0; i < fonts.size(); i++) { - if (font_has_char(fonts[i], ' ')) { + if (_font_has_char(fonts[i], ' ')) { whitespace_gl_font_rid = fonts[i]; break; } } } - int32_t dot_gl_idx = dot_gl_font_rid.is_valid() ? font_get_glyph_index(dot_gl_font_rid, last_gl_font_size, '.') : -10; - Vector2 dot_adv = dot_gl_font_rid.is_valid() ? font_get_glyph_advance(dot_gl_font_rid, last_gl_font_size, dot_gl_idx) : Vector2(); - int32_t whitespace_gl_idx = whitespace_gl_font_rid.is_valid() ? font_get_glyph_index(whitespace_gl_font_rid, last_gl_font_size, ' ') : -10; - Vector2 whitespace_adv = whitespace_gl_font_rid.is_valid() ? font_get_glyph_advance(whitespace_gl_font_rid, last_gl_font_size, whitespace_gl_idx) : Vector2(); + int32_t dot_gl_idx = dot_gl_font_rid.is_valid() ? _font_get_glyph_index(dot_gl_font_rid, last_gl_font_size, '.', 0) : -10; + Vector2 dot_adv = dot_gl_font_rid.is_valid() ? _font_get_glyph_advance(dot_gl_font_rid, last_gl_font_size, dot_gl_idx) : Vector2(); + int32_t whitespace_gl_idx = whitespace_gl_font_rid.is_valid() ? _font_get_glyph_index(whitespace_gl_font_rid, last_gl_font_size, ' ', 0) : -10; + Vector2 whitespace_adv = whitespace_gl_font_rid.is_valid() ? _font_get_glyph_advance(whitespace_gl_font_rid, last_gl_font_size, whitespace_gl_idx) : Vector2(); int ellipsis_width = 0; if (add_ellipsis && whitespace_gl_font_rid.is_valid()) { @@ -3453,29 +3446,34 @@ void TextServerFallback::shaped_text_overrun_trim_to_width(const RID &p_shaped_l int last_valid_cut = 0; bool found = false; - for (int i = sd_size - 1; i != -1; i--) { - width -= sd_glyphs[i].advance * sd_glyphs[i].repeat; + if (enforce_ellipsis && (width + ellipsis_width <= p_width)) { + trim_pos = -1; + ellipsis_pos = sd_size; + } else { + for (int i = sd_size - 1; i != -1; i--) { + width -= sd_glyphs[i].advance * sd_glyphs[i].repeat; - if (sd_glyphs[i].count > 0) { - bool above_min_char_threshold = (i >= ell_min_characters); + if (sd_glyphs[i].count > 0) { + bool above_min_char_threshold = (i >= ell_min_characters); - if (width + (((above_min_char_threshold && add_ellipsis) || enforce_ellipsis) ? ellipsis_width : 0) <= p_width) { - if (cut_per_word && above_min_char_threshold) { - if ((sd_glyphs[i].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT) { + if (width + (((above_min_char_threshold && add_ellipsis) || enforce_ellipsis) ? ellipsis_width : 0) <= p_width) { + if (cut_per_word && above_min_char_threshold) { + if ((sd_glyphs[i].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT) { + last_valid_cut = i; + found = true; + } + } else { last_valid_cut = i; found = true; } - } else { - last_valid_cut = i; - found = true; - } - if (found) { - trim_pos = last_valid_cut; + if (found) { + trim_pos = last_valid_cut; - if (add_ellipsis && (above_min_char_threshold || enforce_ellipsis) && width - ellipsis_width <= p_width) { - ellipsis_pos = trim_pos; + if (add_ellipsis && (above_min_char_threshold || enforce_ellipsis) && width - ellipsis_width <= p_width) { + ellipsis_pos = trim_pos; + } + break; } - break; } } } @@ -3521,7 +3519,7 @@ void TextServerFallback::shaped_text_overrun_trim_to_width(const RID &p_shaped_l } } -int64_t TextServerFallback::shaped_text_get_trim_pos(const RID &p_shaped) const { +int64_t TextServerFallback::_shaped_text_get_trim_pos(const RID &p_shaped) const { ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V_MSG(!sd, -1, "ShapedTextDataFallback invalid."); @@ -3529,7 +3527,7 @@ int64_t TextServerFallback::shaped_text_get_trim_pos(const RID &p_shaped) const return sd->overrun_trim_data.trim_pos; } -int64_t TextServerFallback::shaped_text_get_ellipsis_pos(const RID &p_shaped) const { +int64_t TextServerFallback::_shaped_text_get_ellipsis_pos(const RID &p_shaped) const { ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V_MSG(!sd, -1, "ShapedTextDataFallback invalid."); @@ -3537,7 +3535,7 @@ int64_t TextServerFallback::shaped_text_get_ellipsis_pos(const RID &p_shaped) co return sd->overrun_trim_data.ellipsis_pos; } -const Glyph *TextServerFallback::shaped_text_get_ellipsis_glyphs(const RID &p_shaped) const { +const Glyph *TextServerFallback::_shaped_text_get_ellipsis_glyphs(const RID &p_shaped) const { ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V_MSG(!sd, nullptr, "ShapedTextDataFallback invalid."); @@ -3545,7 +3543,7 @@ const Glyph *TextServerFallback::shaped_text_get_ellipsis_glyphs(const RID &p_sh return sd->overrun_trim_data.ellipsis_glyph_buf.ptr(); } -int64_t TextServerFallback::shaped_text_get_ellipsis_glyph_count(const RID &p_shaped) const { +int64_t TextServerFallback::_shaped_text_get_ellipsis_glyph_count(const RID &p_shaped) const { ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V_MSG(!sd, 0, "ShapedTextDataFallback invalid."); @@ -3553,7 +3551,7 @@ int64_t TextServerFallback::shaped_text_get_ellipsis_glyph_count(const RID &p_sh return sd->overrun_trim_data.ellipsis_glyph_buf.size(); } -bool TextServerFallback::shaped_text_shape(const RID &p_shaped) { +bool TextServerFallback::_shaped_text_shape(const RID &p_shaped) { ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, false); @@ -3620,27 +3618,28 @@ bool TextServerFallback::shaped_text_shape(const RID &p_shaped) { } // Select first font which has character (font are already sorted by span language). for (int k = 0; k < span.fonts.size(); k++) { - if (font_has_char(span.fonts[k], gl.index)) { + if (_font_has_char(span.fonts[k], gl.index)) { gl.font_rid = span.fonts[k]; break; } } + double scale = _font_get_scale(gl.font_rid, gl.font_size); if (gl.font_rid.is_valid()) { - bool subpos = (font_get_subpixel_positioning(gl.font_rid) == SUBPIXEL_POSITIONING_ONE_HALF) || (font_get_subpixel_positioning(gl.font_rid) == SUBPIXEL_POSITIONING_ONE_QUARTER) || (font_get_subpixel_positioning(gl.font_rid) == SUBPIXEL_POSITIONING_AUTO && gl.font_size <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE); + bool subpos = (scale != 1.0) || (_font_get_subpixel_positioning(gl.font_rid) == SUBPIXEL_POSITIONING_ONE_HALF) || (_font_get_subpixel_positioning(gl.font_rid) == SUBPIXEL_POSITIONING_ONE_QUARTER) || (_font_get_subpixel_positioning(gl.font_rid) == SUBPIXEL_POSITIONING_AUTO && gl.font_size <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE); if (sd->text[j - sd->start] != 0 && !is_linebreak(sd->text[j - sd->start])) { if (sd->orientation == ORIENTATION_HORIZONTAL) { - gl.advance = Math::round(font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x); + gl.advance = _font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x; gl.x_off = 0; gl.y_off = 0; - sd->ascent = MAX(sd->ascent, font_get_ascent(gl.font_rid, gl.font_size)); - sd->descent = MAX(sd->descent, font_get_descent(gl.font_rid, gl.font_size)); + sd->ascent = MAX(sd->ascent, _font_get_ascent(gl.font_rid, gl.font_size)); + sd->descent = MAX(sd->descent, _font_get_descent(gl.font_rid, gl.font_size)); } else { - gl.advance = Math::round(font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).y); - gl.x_off = -Math::round(font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5); - gl.y_off = font_get_ascent(gl.font_rid, gl.font_size); - sd->ascent = MAX(sd->ascent, Math::round(font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5)); - sd->descent = MAX(sd->descent, Math::round(font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5)); + gl.advance = _font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).y; + gl.x_off = -Math::round(_font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5); + gl.y_off = _font_get_ascent(gl.font_rid, gl.font_size); + sd->ascent = MAX(sd->ascent, Math::round(_font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5)); + sd->descent = MAX(sd->descent, Math::round(_font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5)); } } if (j < sd->end - 1) { @@ -3651,17 +3650,17 @@ bool TextServerFallback::shaped_text_shape(const RID &p_shaped) { gl.advance += sd->extra_spacing[SPACING_GLYPH]; } } - 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)); + 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 += font_get_kerning(gl.font_rid, gl.font_size, Vector2i(prev_gl.index, gl.index)).x; + prev_gl.advance += _font_get_kerning(gl.font_rid, gl.font_size, Vector2i(prev_gl.index, gl.index)).x; } else { - prev_gl.advance += font_get_kerning(gl.font_rid, gl.font_size, Vector2i(prev_gl.index, gl.index)).y; + prev_gl.advance += _font_get_kerning(gl.font_rid, gl.font_size, Vector2i(prev_gl.index, gl.index)).y; } } } @@ -3692,7 +3691,7 @@ bool TextServerFallback::shaped_text_shape(const RID &p_shaped) { return sd->valid; } -bool TextServerFallback::shaped_text_is_ready(const RID &p_shaped) const { +bool TextServerFallback::_shaped_text_is_ready(const RID &p_shaped) const { const ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, false); @@ -3700,41 +3699,41 @@ bool TextServerFallback::shaped_text_is_ready(const RID &p_shaped) const { return sd->valid; } -const Glyph *TextServerFallback::shaped_text_get_glyphs(const RID &p_shaped) const { +const Glyph *TextServerFallback::_shaped_text_get_glyphs(const RID &p_shaped) const { const ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, nullptr); MutexLock lock(sd->mutex); if (!sd->valid) { - const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + const_cast<TextServerFallback *>(this)->_shaped_text_shape(p_shaped); } return sd->glyphs.ptr(); } -int64_t TextServerFallback::shaped_text_get_glyph_count(const RID &p_shaped) const { +int64_t TextServerFallback::_shaped_text_get_glyph_count(const RID &p_shaped) const { const ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, 0); MutexLock lock(sd->mutex); if (!sd->valid) { - const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + const_cast<TextServerFallback *>(this)->_shaped_text_shape(p_shaped); } return sd->glyphs.size(); } -const Glyph *TextServerFallback::shaped_text_sort_logical(const RID &p_shaped) { +const Glyph *TextServerFallback::_shaped_text_sort_logical(const RID &p_shaped) { const ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, nullptr); MutexLock lock(sd->mutex); if (!sd->valid) { - const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + const_cast<TextServerFallback *>(this)->_shaped_text_shape(p_shaped); } return sd->glyphs.ptr(); // Already in the logical order, return as is. } -Vector2i TextServerFallback::shaped_text_get_range(const RID &p_shaped) const { +Vector2i TextServerFallback::_shaped_text_get_range(const RID &p_shaped) const { const ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, Vector2i()); @@ -3742,7 +3741,7 @@ Vector2i TextServerFallback::shaped_text_get_range(const RID &p_shaped) const { return Vector2(sd->start, sd->end); } -Array TextServerFallback::shaped_text_get_objects(const RID &p_shaped) const { +Array TextServerFallback::_shaped_text_get_objects(const RID &p_shaped) const { Array ret; const ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, ret); @@ -3755,25 +3754,25 @@ Array TextServerFallback::shaped_text_get_objects(const RID &p_shaped) const { return ret; } -Rect2 TextServerFallback::shaped_text_get_object_rect(const RID &p_shaped, const Variant &p_key) const { +Rect2 TextServerFallback::_shaped_text_get_object_rect(const RID &p_shaped, const Variant &p_key) const { const ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, Rect2()); MutexLock lock(sd->mutex); ERR_FAIL_COND_V(!sd->objects.has(p_key), Rect2()); if (!sd->valid) { - const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + const_cast<TextServerFallback *>(this)->_shaped_text_shape(p_shaped); } return sd->objects[p_key].rect; } -Size2 TextServerFallback::shaped_text_get_size(const RID &p_shaped) const { +Size2 TextServerFallback::_shaped_text_get_size(const RID &p_shaped) const { const ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, Size2()); MutexLock lock(sd->mutex); if (!sd->valid) { - const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + const_cast<TextServerFallback *>(this)->_shaped_text_shape(p_shaped); } if (sd->orientation == TextServer::ORIENTATION_HORIZONTAL) { return Size2(sd->width, sd->ascent + sd->descent + sd->extra_spacing[SPACING_TOP] + sd->extra_spacing[SPACING_BOTTOM]).ceil(); @@ -3782,64 +3781,64 @@ Size2 TextServerFallback::shaped_text_get_size(const RID &p_shaped) const { } } -double TextServerFallback::shaped_text_get_ascent(const RID &p_shaped) const { +double TextServerFallback::_shaped_text_get_ascent(const RID &p_shaped) const { const ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, 0.0); MutexLock lock(sd->mutex); if (!sd->valid) { - const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + const_cast<TextServerFallback *>(this)->_shaped_text_shape(p_shaped); } return sd->ascent + sd->extra_spacing[SPACING_TOP]; } -double TextServerFallback::shaped_text_get_descent(const RID &p_shaped) const { +double TextServerFallback::_shaped_text_get_descent(const RID &p_shaped) const { const ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, 0.0); MutexLock lock(sd->mutex); if (!sd->valid) { - const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + const_cast<TextServerFallback *>(this)->_shaped_text_shape(p_shaped); } return sd->descent + sd->extra_spacing[SPACING_BOTTOM]; } -double TextServerFallback::shaped_text_get_width(const RID &p_shaped) const { +double TextServerFallback::_shaped_text_get_width(const RID &p_shaped) const { const ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, 0.0); MutexLock lock(sd->mutex); if (!sd->valid) { - const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + const_cast<TextServerFallback *>(this)->_shaped_text_shape(p_shaped); } return Math::ceil(sd->width); } -double TextServerFallback::shaped_text_get_underline_position(const RID &p_shaped) const { +double TextServerFallback::_shaped_text_get_underline_position(const RID &p_shaped) const { const ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, 0.0); MutexLock lock(sd->mutex); if (!sd->valid) { - const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + const_cast<TextServerFallback *>(this)->_shaped_text_shape(p_shaped); } return sd->upos; } -double TextServerFallback::shaped_text_get_underline_thickness(const RID &p_shaped) const { +double TextServerFallback::_shaped_text_get_underline_thickness(const RID &p_shaped) const { const ShapedTextDataFallback *sd = shaped_owner.get_or_null(p_shaped); ERR_FAIL_COND_V(!sd, 0.0); MutexLock lock(sd->mutex); if (!sd->valid) { - const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped); + const_cast<TextServerFallback *>(this)->_shaped_text_shape(p_shaped); } return sd->uthk; } -String TextServerFallback::string_to_upper(const String &p_string, const String &p_language) const { +String TextServerFallback::_string_to_upper(const String &p_string, const String &p_language) const { String upper = p_string; for (int i = 0; i <= upper.length(); i++) { @@ -3853,7 +3852,7 @@ String TextServerFallback::string_to_upper(const String &p_string, const String return upper; } -String TextServerFallback::string_to_lower(const String &p_string, const String &p_language) const { +String TextServerFallback::_string_to_lower(const String &p_string, const String &p_language) const { String lower = p_string; for (int i = 0; i <= lower.length(); i++) { @@ -3867,7 +3866,7 @@ String TextServerFallback::string_to_lower(const String &p_string, const String return lower; } -PackedInt32Array TextServerFallback::string_get_word_breaks(const String &p_string, const String &p_language) const { +PackedInt32Array TextServerFallback::_string_get_word_breaks(const String &p_string, const String &p_language) const { PackedInt32Array ret; for (int i = 0; i < p_string.length(); i++) { char32_t c = p_string[i]; diff --git a/modules/text_server_fb/text_server_fb.h b/modules/text_server_fb/text_server_fb.h index cbb2fb03f2..7e0bc99618 100644 --- a/modules/text_server_fb/text_server_fb.h +++ b/modules/text_server_fb/text_server_fb.h @@ -42,6 +42,7 @@ #include <godot_cpp/godot.hpp> #include <godot_cpp/core/class_db.hpp> +#include <godot_cpp/core/ext_wrappers.gen.inc> #include <godot_cpp/core/mutex_lock.hpp> #include <godot_cpp/variant/array.hpp> @@ -52,6 +53,7 @@ #include <godot_cpp/variant/rect2.hpp> #include <godot_cpp/variant/rid.hpp> #include <godot_cpp/variant/string.hpp> +#include <godot_cpp/variant/typed_array.hpp> #include <godot_cpp/variant/vector2.hpp> #include <godot_cpp/variant/vector2i.hpp> @@ -79,12 +81,13 @@ using namespace godot; #include "servers/text/text_server_extension.h" +#include "core/extension/ext_wrappers.gen.inc" #include "core/object/worker_thread_pool.h" #include "core/templates/hash_map.h" #include "core/templates/rid_owner.h" #include "scene/resources/texture.h" -#include "modules/modules_enabled.gen.h" // For freetype, msdfgen. +#include "modules/modules_enabled.gen.h" // For freetype, msdfgen, svg. #endif @@ -98,6 +101,7 @@ using namespace godot; #include FT_ADVANCES_H #include FT_MULTIPLE_MASTERS_H #include FT_BBOX_H +#include FT_MODULE_H #include FT_CONFIG_OPTIONS_H #if !defined(FT_CONFIG_OPTION_USE_BROTLI) && !defined(_MSC_VER) #warning FreeType is configured without Brotli support, built-in fonts will not be available. @@ -124,20 +128,86 @@ class TextServerFallback : public TextServerExtension { const int rect_range = 1; - struct FontTexture { + struct FontTexturePosition { + int32_t index = -1; + int32_t x = 0; + int32_t y = 0; + + FontTexturePosition() {} + FontTexturePosition(int32_t p_id, int32_t p_x, int32_t p_y) : + index(p_id), x(p_x), y(p_y) {} + }; + + struct Shelf { + int32_t x = 0; + int32_t y = 0; + int32_t w = 0; + int32_t h = 0; + + FontTexturePosition alloc_shelf(int32_t p_id, int32_t p_w, int32_t p_h) { + if (p_w > w || p_h > h) { + return FontTexturePosition(-1, 0, 0); + } + int32_t xx = x; + x += p_w; + w -= p_w; + return FontTexturePosition(p_id, xx, y); + } + + Shelf() {} + Shelf(int32_t p_x, int32_t p_y, int32_t p_w, int32_t p_h) : + x(p_x), y(p_y), w(p_w), h(p_h) {} + }; + + struct ShelfPackTexture { + int32_t texture_w = 1024; + int32_t texture_h = 1024; + Image::Format format; PackedByteArray imgdata; - int texture_w = 0; - int texture_h = 0; - PackedInt32Array offsets; Ref<ImageTexture> texture; bool dirty = true; - }; - struct FontTexturePosition { - int index = 0; - int x = 0; - int y = 0; + List<Shelf> shelves; + + FontTexturePosition pack_rect(int32_t p_id, int32_t p_h, int32_t p_w) { + int32_t y = 0; + int32_t waste = 0; + Shelf *best_shelf = nullptr; + int32_t best_waste = std::numeric_limits<std::int32_t>::max(); + + for (Shelf &E : shelves) { + y += E.h; + if (p_w > E.w) { + continue; + } + if (p_h == E.h) { + return E.alloc_shelf(p_id, p_w, p_h); + } + if (p_h > E.h) { + continue; + } + if (p_h < E.h) { + waste = (E.h - p_h) * p_w; + if (waste < best_waste) { + best_waste = waste; + best_shelf = &E; + } + } + } + if (best_shelf) { + return best_shelf->alloc_shelf(p_id, p_w, p_h); + } + if (p_h <= (texture_h - y) && p_w <= texture_w) { + List<Shelf>::Element *E = shelves.push_back(Shelf(0, y, texture_w, p_h)); + return E->get().alloc_shelf(p_id, p_w, p_h); + } + return FontTexturePosition(-1, 0, 0); + } + + ShelfPackTexture() {} + ShelfPackTexture(int32_t p_w, int32_t p_h) : + texture_w(p_w), texture_h(p_h) {} }; struct FontGlyph { @@ -158,7 +228,7 @@ class TextServerFallback : public TextServerExtension { Vector2i size; - Vector<FontTexture> textures; + Vector<ShelfPackTexture> textures; HashMap<int32_t, FontGlyph> glyph_map; HashMap<Vector2i, Vector2> kerning_map; @@ -337,251 +407,249 @@ protected: void invalidate(ShapedTextDataFallback *p_shaped); public: - virtual bool has_feature(Feature p_feature) const override; - virtual String get_name() const override; - virtual int64_t get_features() const override; + MODBIND1RC(bool, has_feature, Feature); + MODBIND0RC(String, get_name); + MODBIND0RC(int64_t, get_features); - virtual void free_rid(const RID &p_rid) override; - virtual bool has(const RID &p_rid) override; - virtual bool load_support_data(const String &p_filename) override; + MODBIND1(free_rid, const RID &); + MODBIND1R(bool, has, const RID &); + MODBIND1R(bool, load_support_data, const String &); - virtual String get_support_data_filename() const override { - return ""; - }; - virtual String get_support_data_info() const override { - return "Not supported"; - }; - virtual bool save_support_data(const String &p_filename) const override; + MODBIND0RC(String, get_support_data_filename); + MODBIND0RC(String, get_support_data_info); + MODBIND1RC(bool, save_support_data, const String &); - virtual bool is_locale_right_to_left(const String &p_locale) const override; + MODBIND1RC(bool, is_locale_right_to_left, const String &); - virtual int64_t name_to_tag(const String &p_name) const override; - virtual String tag_to_name(int64_t p_tag) const override; + MODBIND1RC(int64_t, name_to_tag, const String &); + MODBIND1RC(String, tag_to_name, int64_t); /* Font interface */ - virtual RID create_font() override; - virtual void font_set_data(const RID &p_font_rid, const PackedByteArray &p_data) override; - virtual void font_set_data_ptr(const RID &p_font_rid, const uint8_t *p_data_ptr, int64_t p_data_size) override; + MODBIND0R(RID, create_font); + + MODBIND2(font_set_data, const RID &, const PackedByteArray &); + MODBIND3(font_set_data_ptr, const RID &, const uint8_t *, int64_t); + + MODBIND2(font_set_face_index, const RID &, int64_t); + MODBIND1RC(int64_t, font_get_face_index, const RID &); - virtual void font_set_face_index(const RID &p_font_rid, int64_t p_index) override; - virtual int64_t font_get_face_index(const RID &p_font_rid) const override; + MODBIND1RC(int64_t, font_get_face_count, const RID &); - virtual int64_t font_get_face_count(const RID &p_font_rid) const override; + MODBIND2(font_set_style, const RID &, BitField<FontStyle>); + MODBIND1RC(BitField<FontStyle>, font_get_style, const RID &); - virtual void font_set_style(const RID &p_font_rid, BitField<FontStyle> p_style) override; - virtual BitField<FontStyle> font_get_style(const RID &p_font_rid) const override; + MODBIND2(font_set_style_name, const RID &, const String &); + MODBIND1RC(String, font_get_style_name, const RID &); - virtual void font_set_style_name(const RID &p_font_rid, const String &p_name) override; - virtual String font_get_style_name(const RID &p_font_rid) const override; + MODBIND2(font_set_name, const RID &, const String &); + MODBIND1RC(String, font_get_name, const RID &); - virtual void font_set_name(const RID &p_font_rid, const String &p_name) override; - virtual String font_get_name(const RID &p_font_rid) const override; + MODBIND2(font_set_antialiasing, const RID &, TextServer::FontAntialiasing); + MODBIND1RC(TextServer::FontAntialiasing, font_get_antialiasing, const RID &); - virtual void font_set_antialiasing(RID p_font_rid, TextServer::FontAntialiasing p_antialiasing) override; - virtual TextServer::FontAntialiasing font_get_antialiasing(RID p_font_rid) const override; + MODBIND2(font_set_generate_mipmaps, const RID &, bool); + MODBIND1RC(bool, font_get_generate_mipmaps, const RID &); - virtual void font_set_generate_mipmaps(const RID &p_font_rid, bool p_generate_mipmaps) override; - virtual bool font_get_generate_mipmaps(const RID &p_font_rid) const override; + MODBIND2(font_set_multichannel_signed_distance_field, const RID &, bool); + MODBIND1RC(bool, font_is_multichannel_signed_distance_field, const RID &); - virtual void font_set_multichannel_signed_distance_field(const RID &p_font_rid, bool p_msdf) override; - virtual bool font_is_multichannel_signed_distance_field(const RID &p_font_rid) const override; + MODBIND2(font_set_msdf_pixel_range, const RID &, int64_t); + MODBIND1RC(int64_t, font_get_msdf_pixel_range, const RID &); - virtual void font_set_msdf_pixel_range(const RID &p_font_rid, int64_t p_msdf_pixel_range) override; - virtual int64_t font_get_msdf_pixel_range(const RID &p_font_rid) const override; + MODBIND2(font_set_msdf_size, const RID &, int64_t); + MODBIND1RC(int64_t, font_get_msdf_size, const RID &); - virtual void font_set_msdf_size(const RID &p_font_rid, int64_t p_msdf_size) override; - virtual int64_t font_get_msdf_size(const RID &p_font_rid) const override; + MODBIND2(font_set_fixed_size, const RID &, int64_t); + MODBIND1RC(int64_t, font_get_fixed_size, const RID &); - virtual void font_set_fixed_size(const RID &p_font_rid, int64_t p_fixed_size) override; - virtual int64_t font_get_fixed_size(const RID &p_font_rid) const override; + MODBIND2(font_set_force_autohinter, const RID &, bool); + MODBIND1RC(bool, font_is_force_autohinter, const RID &); - virtual void font_set_force_autohinter(const RID &p_font_rid, bool p_force_autohinter) override; - virtual bool font_is_force_autohinter(const RID &p_font_rid) const override; + MODBIND2(font_set_subpixel_positioning, const RID &, SubpixelPositioning); + MODBIND1RC(SubpixelPositioning, font_get_subpixel_positioning, const RID &); - virtual void font_set_hinting(const RID &p_font_rid, TextServer::Hinting p_hinting) override; - virtual TextServer::Hinting font_get_hinting(const RID &p_font_rid) const override; + MODBIND2(font_set_embolden, const RID &, double); + MODBIND1RC(double, font_get_embolden, const RID &); - virtual void font_set_subpixel_positioning(const RID &p_font_rid, SubpixelPositioning p_subpixel) override; - virtual SubpixelPositioning font_get_subpixel_positioning(const RID &p_font_rid) const override; + MODBIND2(font_set_transform, const RID &, const Transform2D &); + MODBIND1RC(Transform2D, font_get_transform, const RID &); - virtual void font_set_embolden(const RID &p_font_rid, double p_strength) override; - virtual double font_get_embolden(const RID &p_font_rid) const override; + MODBIND2(font_set_variation_coordinates, const RID &, const Dictionary &); + MODBIND1RC(Dictionary, font_get_variation_coordinates, const RID &); - virtual void font_set_transform(const RID &p_font_rid, const Transform2D &p_transform) override; - virtual Transform2D font_get_transform(const RID &p_font_rid) const override; + MODBIND2(font_set_hinting, const RID &, TextServer::Hinting); + MODBIND1RC(TextServer::Hinting, font_get_hinting, const RID &); - virtual void font_set_variation_coordinates(const RID &p_font_rid, const Dictionary &p_variation_coordinates) override; - virtual Dictionary font_get_variation_coordinates(const RID &p_font_rid) const override; + MODBIND2(font_set_oversampling, const RID &, double); + MODBIND1RC(double, font_get_oversampling, const RID &); - virtual void font_set_oversampling(const RID &p_font_rid, double p_oversampling) override; - virtual double font_get_oversampling(const RID &p_font_rid) const override; + MODBIND1RC(TypedArray<Vector2i>, font_get_size_cache_list, const RID &); + MODBIND1(font_clear_size_cache, const RID &); + MODBIND2(font_remove_size_cache, const RID &, const Vector2i &); - virtual TypedArray<Vector2i> font_get_size_cache_list(const RID &p_font_rid) const override; - virtual void font_clear_size_cache(const RID &p_font_rid) override; - virtual void font_remove_size_cache(const RID &p_font_rid, const Vector2i &p_size) override; + MODBIND3(font_set_ascent, const RID &, int64_t, double); + MODBIND2RC(double, font_get_ascent, const RID &, int64_t); - virtual void font_set_ascent(const RID &p_font_rid, int64_t p_size, double p_ascent) override; - virtual double font_get_ascent(const RID &p_font_rid, int64_t p_size) const override; + MODBIND3(font_set_descent, const RID &, int64_t, double); + MODBIND2RC(double, font_get_descent, const RID &, int64_t); - virtual void font_set_descent(const RID &p_font_rid, int64_t p_size, double p_descent) override; - virtual double font_get_descent(const RID &p_font_rid, int64_t p_size) const override; + MODBIND3(font_set_underline_position, const RID &, int64_t, double); + MODBIND2RC(double, font_get_underline_position, const RID &, int64_t); - virtual void font_set_underline_position(const RID &p_font_rid, int64_t p_size, double p_underline_position) override; - virtual double font_get_underline_position(const RID &p_font_rid, int64_t p_size) const override; + MODBIND3(font_set_underline_thickness, const RID &, int64_t, double); + MODBIND2RC(double, font_get_underline_thickness, const RID &, int64_t); - virtual void font_set_underline_thickness(const RID &p_font_rid, int64_t p_size, double p_underline_thickness) override; - virtual double font_get_underline_thickness(const RID &p_font_rid, int64_t p_size) const override; + MODBIND3(font_set_scale, const RID &, int64_t, double); + MODBIND2RC(double, font_get_scale, const RID &, int64_t); - virtual void font_set_scale(const RID &p_font_rid, int64_t p_size, double p_scale) override; - virtual double font_get_scale(const RID &p_font_rid, int64_t p_size) const override; + MODBIND2RC(int64_t, font_get_texture_count, const RID &, const Vector2i &); + MODBIND2(font_clear_textures, const RID &, const Vector2i &); + MODBIND3(font_remove_texture, const RID &, const Vector2i &, int64_t); - virtual int64_t font_get_texture_count(const RID &p_font_rid, const Vector2i &p_size) const override; - virtual void font_clear_textures(const RID &p_font_rid, const Vector2i &p_size) override; - virtual void font_remove_texture(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) override; + MODBIND4(font_set_texture_image, const RID &, const Vector2i &, int64_t, const Ref<Image> &); + MODBIND3RC(Ref<Image>, font_get_texture_image, const RID &, const Vector2i &, int64_t); - virtual void font_set_texture_image(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index, const Ref<Image> &p_image) override; - virtual Ref<Image> font_get_texture_image(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) const override; + MODBIND4(font_set_texture_offsets, const RID &, const Vector2i &, int64_t, const PackedInt32Array &); + MODBIND3RC(PackedInt32Array, font_get_texture_offsets, const RID &, const Vector2i &, int64_t); - virtual void font_set_texture_offsets(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index, const PackedInt32Array &p_offset) override; - virtual PackedInt32Array font_get_texture_offsets(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) const override; + MODBIND2RC(PackedInt32Array, font_get_glyph_list, const RID &, const Vector2i &); + MODBIND2(font_clear_glyphs, const RID &, const Vector2i &); + MODBIND3(font_remove_glyph, const RID &, const Vector2i &, int64_t); - virtual PackedInt32Array font_get_glyph_list(const RID &p_font_rid, const Vector2i &p_size) const override; - virtual void font_clear_glyphs(const RID &p_font_rid, const Vector2i &p_size) override; - virtual void font_remove_glyph(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) override; + MODBIND3RC(Vector2, font_get_glyph_advance, const RID &, int64_t, int64_t); + MODBIND4(font_set_glyph_advance, const RID &, int64_t, int64_t, const Vector2 &); - virtual Vector2 font_get_glyph_advance(const RID &p_font_rid, int64_t p_size, int64_t p_glyph) const override; - virtual void font_set_glyph_advance(const RID &p_font_rid, int64_t p_size, int64_t p_glyph, const Vector2 &p_advance) override; + MODBIND3RC(Vector2, font_get_glyph_offset, const RID &, const Vector2i &, int64_t); + MODBIND4(font_set_glyph_offset, const RID &, const Vector2i &, int64_t, const Vector2 &); - virtual Vector2 font_get_glyph_offset(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const override; - virtual void font_set_glyph_offset(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, const Vector2 &p_offset) override; + MODBIND3RC(Vector2, font_get_glyph_size, const RID &, const Vector2i &, int64_t); + MODBIND4(font_set_glyph_size, const RID &, const Vector2i &, int64_t, const Vector2 &); - virtual Vector2 font_get_glyph_size(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const override; - virtual void font_set_glyph_size(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, const Vector2 &p_gl_size) override; + MODBIND3RC(Rect2, font_get_glyph_uv_rect, const RID &, const Vector2i &, int64_t); + MODBIND4(font_set_glyph_uv_rect, const RID &, const Vector2i &, int64_t, const Rect2 &); - virtual Rect2 font_get_glyph_uv_rect(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const override; - virtual void font_set_glyph_uv_rect(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, const Rect2 &p_uv_rect) override; + MODBIND3RC(int64_t, font_get_glyph_texture_idx, const RID &, const Vector2i &, int64_t); + MODBIND4(font_set_glyph_texture_idx, const RID &, const Vector2i &, int64_t, int64_t); - virtual int64_t font_get_glyph_texture_idx(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const override; - virtual void font_set_glyph_texture_idx(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, int64_t p_texture_idx) override; - virtual RID font_get_glyph_texture_rid(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const override; - virtual Size2 font_get_glyph_texture_size(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const override; + MODBIND3RC(RID, font_get_glyph_texture_rid, const RID &, const Vector2i &, int64_t); + MODBIND3RC(Size2, font_get_glyph_texture_size, const RID &, const Vector2i &, int64_t); - virtual Dictionary font_get_glyph_contours(const RID &p_font, int64_t p_size, int64_t p_index) const override; + MODBIND3RC(Dictionary, font_get_glyph_contours, const RID &, int64_t, int64_t); - virtual TypedArray<Vector2i> font_get_kerning_list(const RID &p_font_rid, int64_t p_size) const override; - virtual void font_clear_kerning_map(const RID &p_font_rid, int64_t p_size) override; - virtual void font_remove_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair) override; + MODBIND2RC(TypedArray<Vector2i>, font_get_kerning_list, const RID &, int64_t); + MODBIND2(font_clear_kerning_map, const RID &, int64_t); + MODBIND3(font_remove_kerning, const RID &, int64_t, const Vector2i &); - virtual void font_set_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair, const Vector2 &p_kerning) override; - virtual Vector2 font_get_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair) const override; + MODBIND4(font_set_kerning, const RID &, int64_t, const Vector2i &, const Vector2 &); + MODBIND3RC(Vector2, font_get_kerning, const RID &, int64_t, const Vector2i &); - virtual int64_t font_get_glyph_index(const RID &p_font_rid, int64_t p_size, int64_t p_char, int64_t p_variation_selector = 0) const override; + MODBIND4RC(int64_t, font_get_glyph_index, const RID &, int64_t, int64_t, int64_t); - virtual bool font_has_char(const RID &p_font_rid, int64_t p_char) const override; - virtual String font_get_supported_chars(const RID &p_font_rid) const override; + MODBIND2RC(bool, font_has_char, const RID &, int64_t); + MODBIND1RC(String, font_get_supported_chars, const RID &); - virtual void font_render_range(const RID &p_font, const Vector2i &p_size, int64_t p_start, int64_t p_end) override; - virtual void font_render_glyph(const RID &p_font_rid, const Vector2i &p_size, int64_t p_index) override; + MODBIND4(font_render_range, const RID &, const Vector2i &, int64_t, int64_t); + MODBIND3(font_render_glyph, const RID &, const Vector2i &, int64_t); - virtual void font_draw_glyph(const RID &p_font, const RID &p_canvas, int64_t p_size, const Vector2 &p_pos, int64_t p_index, const Color &p_color = Color(1, 1, 1)) const override; - virtual void font_draw_glyph_outline(const RID &p_font, const RID &p_canvas, int64_t p_size, int64_t p_outline_size, const Vector2 &p_pos, int64_t p_index, const Color &p_color = Color(1, 1, 1)) const override; + MODBIND6C(font_draw_glyph, const RID &, const RID &, int64_t, const Vector2 &, int64_t, const Color &); + MODBIND7C(font_draw_glyph_outline, const RID &, const RID &, int64_t, int64_t, const Vector2 &, int64_t, const Color &); - virtual bool font_is_language_supported(const RID &p_font_rid, const String &p_language) const override; - virtual void font_set_language_support_override(const RID &p_font_rid, const String &p_language, bool p_supported) override; - virtual bool font_get_language_support_override(const RID &p_font_rid, const String &p_language) override; - virtual void font_remove_language_support_override(const RID &p_font_rid, const String &p_language) override; - virtual PackedStringArray font_get_language_support_overrides(const RID &p_font_rid) override; + MODBIND2RC(bool, font_is_language_supported, const RID &, const String &); + MODBIND3(font_set_language_support_override, const RID &, const String &, bool); + MODBIND2R(bool, font_get_language_support_override, const RID &, const String &); + MODBIND2(font_remove_language_support_override, const RID &, const String &); + MODBIND1R(PackedStringArray, font_get_language_support_overrides, const RID &); - virtual bool font_is_script_supported(const RID &p_font_rid, const String &p_script) const override; - virtual void font_set_script_support_override(const RID &p_font_rid, const String &p_script, bool p_supported) override; - virtual bool font_get_script_support_override(const RID &p_font_rid, const String &p_script) override; - virtual void font_remove_script_support_override(const RID &p_font_rid, const String &p_script) override; - virtual PackedStringArray font_get_script_support_overrides(const RID &p_font_rid) override; + MODBIND2RC(bool, font_is_script_supported, const RID &, const String &); + MODBIND3(font_set_script_support_override, const RID &, const String &, bool); + MODBIND2R(bool, font_get_script_support_override, const RID &, const String &); + MODBIND2(font_remove_script_support_override, const RID &, const String &); + MODBIND1R(PackedStringArray, font_get_script_support_overrides, const RID &); - virtual void font_set_opentype_feature_overrides(const RID &p_font_rid, const Dictionary &p_overrides) override; - virtual Dictionary font_get_opentype_feature_overrides(const RID &p_font_rid) const override; + MODBIND2(font_set_opentype_feature_overrides, const RID &, const Dictionary &); + MODBIND1RC(Dictionary, font_get_opentype_feature_overrides, const RID &); - virtual Dictionary font_supported_feature_list(const RID &p_font_rid) const override; - virtual Dictionary font_supported_variation_list(const RID &p_font_rid) const override; + MODBIND1RC(Dictionary, font_supported_feature_list, const RID &); + MODBIND1RC(Dictionary, font_supported_variation_list, const RID &); - virtual double font_get_global_oversampling() const override; - virtual void font_set_global_oversampling(double p_oversampling) override; + MODBIND0RC(double, font_get_global_oversampling); + MODBIND1(font_set_global_oversampling, double); /* Shaped text buffer interface */ - virtual RID create_shaped_text(Direction p_direction = DIRECTION_AUTO, Orientation p_orientation = ORIENTATION_HORIZONTAL) override; + MODBIND2R(RID, create_shaped_text, Direction, Orientation); - virtual void shaped_text_clear(const RID &p_shaped) override; + MODBIND1(shaped_text_clear, const RID &); - virtual void shaped_text_set_direction(const RID &p_shaped, Direction p_direction = DIRECTION_AUTO) override; - virtual Direction shaped_text_get_direction(const RID &p_shaped) const override; - virtual Direction shaped_text_get_inferred_direction(const RID &p_shaped) const override; + MODBIND2(shaped_text_set_direction, const RID &, Direction); + MODBIND1RC(Direction, shaped_text_get_direction, const RID &); + MODBIND1RC(Direction, shaped_text_get_inferred_direction, const RID &); - virtual void shaped_text_set_bidi_override(const RID &p_shaped, const Array &p_override) override; + MODBIND2(shaped_text_set_bidi_override, const RID &, const Array &); - virtual void shaped_text_set_custom_punctuation(const RID &p_shaped, const String &p_punct) override; - virtual String shaped_text_get_custom_punctuation(const RID &p_shaped) const override; + MODBIND2(shaped_text_set_custom_punctuation, const RID &, const String &); + MODBIND1RC(String, shaped_text_get_custom_punctuation, const RID &); - virtual void shaped_text_set_orientation(const RID &p_shaped, Orientation p_orientation = ORIENTATION_HORIZONTAL) override; - virtual Orientation shaped_text_get_orientation(const RID &p_shaped) const override; + MODBIND2(shaped_text_set_orientation, const RID &, Orientation); + MODBIND1RC(Orientation, shaped_text_get_orientation, const RID &); - virtual void shaped_text_set_preserve_invalid(const RID &p_shaped, bool p_enabled) override; - virtual bool shaped_text_get_preserve_invalid(const RID &p_shaped) const override; + MODBIND2(shaped_text_set_preserve_invalid, const RID &, bool); + MODBIND1RC(bool, shaped_text_get_preserve_invalid, const RID &); - virtual void shaped_text_set_preserve_control(const RID &p_shaped, bool p_enabled) override; - virtual bool shaped_text_get_preserve_control(const RID &p_shaped) const override; + MODBIND2(shaped_text_set_preserve_control, const RID &, bool); + MODBIND1RC(bool, shaped_text_get_preserve_control, const RID &); - virtual void shaped_text_set_spacing(const RID &p_shaped, SpacingType p_spacing, int64_t p_value) override; - virtual int64_t shaped_text_get_spacing(const RID &p_shaped, SpacingType p_spacing) const override; + MODBIND3(shaped_text_set_spacing, const RID &, SpacingType, int64_t); + MODBIND2RC(int64_t, shaped_text_get_spacing, const RID &, SpacingType); - virtual bool shaped_text_add_string(const RID &p_shaped, const String &p_text, const TypedArray<RID> &p_fonts, int64_t p_size, const Dictionary &p_opentype_features = Dictionary(), const String &p_language = "", const Variant &p_meta = Variant()) override; - virtual bool shaped_text_add_object(const RID &p_shaped, const Variant &p_key, const Size2 &p_size, InlineAlignment p_inline_align = INLINE_ALIGNMENT_CENTER, int64_t p_length = 1) override; - virtual bool shaped_text_resize_object(const RID &p_shaped, const Variant &p_key, const Size2 &p_size, InlineAlignment p_inline_align = INLINE_ALIGNMENT_CENTER) override; + MODBIND7R(bool, shaped_text_add_string, const RID &, const String &, const TypedArray<RID> &, int64_t, const Dictionary &, const String &, const Variant &); + MODBIND5R(bool, shaped_text_add_object, const RID &, const Variant &, const Size2 &, InlineAlignment, int64_t); + MODBIND4R(bool, shaped_text_resize_object, const RID &, const Variant &, const Size2 &, InlineAlignment); - virtual int64_t shaped_get_span_count(const RID &p_shaped) const override; - virtual Variant shaped_get_span_meta(const RID &p_shaped, int64_t p_index) const override; - virtual void shaped_set_span_update_font(const RID &p_shaped, int64_t p_index, const TypedArray<RID> &p_fonts, int64_t p_size, const Dictionary &p_opentype_features = Dictionary()) override; + MODBIND1RC(int64_t, shaped_get_span_count, const RID &); + MODBIND2RC(Variant, shaped_get_span_meta, const RID &, int64_t); + MODBIND5(shaped_set_span_update_font, const RID &, int64_t, const TypedArray<RID> &, int64_t, const Dictionary &); - virtual RID shaped_text_substr(const RID &p_shaped, int64_t p_start, int64_t p_length) const override; - virtual RID shaped_text_get_parent(const RID &p_shaped) const override; + MODBIND3RC(RID, shaped_text_substr, const RID &, int64_t, int64_t); + MODBIND1RC(RID, shaped_text_get_parent, const RID &); - virtual double shaped_text_fit_to_width(const RID &p_shaped, double p_width, BitField<TextServer::JustificationFlag> p_jst_flags = JUSTIFICATION_WORD_BOUND | JUSTIFICATION_KASHIDA) override; - virtual double shaped_text_tab_align(const RID &p_shaped, const PackedFloat32Array &p_tab_stops) override; + MODBIND3R(double, shaped_text_fit_to_width, const RID &, double, BitField<TextServer::JustificationFlag>); + MODBIND2R(double, shaped_text_tab_align, const RID &, const PackedFloat32Array &); - virtual bool shaped_text_shape(const RID &p_shaped) override; - virtual bool shaped_text_update_breaks(const RID &p_shaped) override; - virtual bool shaped_text_update_justification_ops(const RID &p_shaped) override; + MODBIND1R(bool, shaped_text_shape, const RID &); + MODBIND1R(bool, shaped_text_update_breaks, const RID &); + MODBIND1R(bool, shaped_text_update_justification_ops, const RID &); - virtual int64_t shaped_text_get_trim_pos(const RID &p_shaped) const override; - virtual int64_t shaped_text_get_ellipsis_pos(const RID &p_shaped) const override; - virtual const Glyph *shaped_text_get_ellipsis_glyphs(const RID &p_shaped) const override; - virtual int64_t shaped_text_get_ellipsis_glyph_count(const RID &p_shaped) const override; + MODBIND1RC(int64_t, shaped_text_get_trim_pos, const RID &); + MODBIND1RC(int64_t, shaped_text_get_ellipsis_pos, const RID &); + MODBIND1RC(const Glyph *, shaped_text_get_ellipsis_glyphs, const RID &); + MODBIND1RC(int64_t, shaped_text_get_ellipsis_glyph_count, const RID &); - virtual void shaped_text_overrun_trim_to_width(const RID &p_shaped, double p_width, BitField<TextServer::TextOverrunFlag> p_trim_flags) override; + MODBIND3(shaped_text_overrun_trim_to_width, const RID &, double, BitField<TextServer::TextOverrunFlag>); - virtual bool shaped_text_is_ready(const RID &p_shaped) const override; + MODBIND1RC(bool, shaped_text_is_ready, const RID &); - virtual const Glyph *shaped_text_get_glyphs(const RID &p_shaped) const override; - virtual const Glyph *shaped_text_sort_logical(const RID &p_shaped) override; - virtual int64_t shaped_text_get_glyph_count(const RID &p_shaped) const override; + MODBIND1RC(const Glyph *, shaped_text_get_glyphs, const RID &); + MODBIND1R(const Glyph *, shaped_text_sort_logical, const RID &); + MODBIND1RC(int64_t, shaped_text_get_glyph_count, const RID &); - virtual Vector2i shaped_text_get_range(const RID &p_shaped) const override; + MODBIND1RC(Vector2i, shaped_text_get_range, const RID &); - virtual Array shaped_text_get_objects(const RID &p_shaped) const override; - virtual Rect2 shaped_text_get_object_rect(const RID &p_shaped, const Variant &p_key) const override; + MODBIND1RC(Array, shaped_text_get_objects, const RID &); + MODBIND2RC(Rect2, shaped_text_get_object_rect, const RID &, const Variant &); - virtual Size2 shaped_text_get_size(const RID &p_shaped) const override; - virtual double shaped_text_get_ascent(const RID &p_shaped) const override; - virtual double shaped_text_get_descent(const RID &p_shaped) const override; - virtual double shaped_text_get_width(const RID &p_shaped) const override; - virtual double shaped_text_get_underline_position(const RID &p_shaped) const override; - virtual double shaped_text_get_underline_thickness(const RID &p_shaped) const override; + MODBIND1RC(Size2, shaped_text_get_size, const RID &); + MODBIND1RC(double, shaped_text_get_ascent, const RID &); + MODBIND1RC(double, shaped_text_get_descent, const RID &); + MODBIND1RC(double, shaped_text_get_width, const RID &); + MODBIND1RC(double, shaped_text_get_underline_position, const RID &); + MODBIND1RC(double, shaped_text_get_underline_thickness, const RID &); - virtual PackedInt32Array string_get_word_breaks(const String &p_string, const String &p_language = "") const override; + MODBIND2RC(PackedInt32Array, string_get_word_breaks, const String &, const String &); - virtual String string_to_upper(const String &p_string, const String &p_language = "") const override; - virtual String string_to_lower(const String &p_string, const String &p_language = "") const override; + MODBIND2RC(String, string_to_upper, const String &, const String &); + MODBIND2RC(String, string_to_lower, const String &, const String &); TextServerFallback(); ~TextServerFallback(); diff --git a/modules/text_server_fb/thorvg_bounds_iterator.cpp b/modules/text_server_fb/thorvg_bounds_iterator.cpp new file mode 100644 index 0000000000..54a6136134 --- /dev/null +++ b/modules/text_server_fb/thorvg_bounds_iterator.cpp @@ -0,0 +1,70 @@ +/*************************************************************************/ +/* thorvg_bounds_iterator.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 GDEXTENSION +// Headers for building as GDExtension plug-in. + +#include <godot_cpp/godot.hpp> + +using namespace godot; + +#else +// Headers for building as built-in module. + +#include "core/typedefs.h" + +#include "modules/modules_enabled.gen.h" // For svg. +#endif + +#ifdef MODULE_SVG_ENABLED + +#include "thorvg_bounds_iterator.h" + +#include <tvgIteratorAccessor.h> +#include <tvgPaint.h> + +// This function uses private ThorVG API to get bounding box of top level children elements. + +void tvg_get_bounds(tvg::Picture *p_picture, float &r_min_x, float &r_min_y, float &r_max_x, float &r_max_y) { + tvg::IteratorAccessor itrAccessor; + if (tvg::Iterator *it = itrAccessor.iterator(p_picture)) { + while (const tvg::Paint *child = it->next()) { + float x = 0, y = 0, w = 0, h = 0; + child->bounds(&x, &y, &w, &h, true); + r_min_x = MIN(x, r_min_x); + r_min_y = MIN(y, r_min_y); + r_max_x = MAX(x + w, r_max_x); + r_max_y = MAX(y + h, r_max_y); + } + delete (it); + } +} + +#endif // MODULE_SVG_ENABLED diff --git a/modules/text_server_fb/thorvg_bounds_iterator.h b/modules/text_server_fb/thorvg_bounds_iterator.h new file mode 100644 index 0000000000..e54e30eaa2 --- /dev/null +++ b/modules/text_server_fb/thorvg_bounds_iterator.h @@ -0,0 +1,58 @@ +/*************************************************************************/ +/* thorvg_bounds_iterator.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 THORVG_BOUNDS_ITERATOR_H +#define THORVG_BOUNDS_ITERATOR_H + +#ifdef GDEXTENSION +// Headers for building as GDExtension plug-in. + +#include <godot_cpp/core/mutex_lock.hpp> +#include <godot_cpp/godot.hpp> + +using namespace godot; + +#else +// Headers for building as built-in module. + +#include "core/typedefs.h" + +#include "modules/modules_enabled.gen.h" // For svg. +#endif + +#ifdef MODULE_SVG_ENABLED + +#include <thorvg.h> + +void tvg_get_bounds(tvg::Picture *p_picture, float &r_min_x, float &r_min_y, float &r_max_x, float &r_max_y); + +#endif // MODULE_SVG_ENABLED + +#endif // THORVG_BOUNDS_ITERATOR_H diff --git a/modules/text_server_fb/thorvg_svg_in_ot.cpp b/modules/text_server_fb/thorvg_svg_in_ot.cpp new file mode 100644 index 0000000000..7863ab67fa --- /dev/null +++ b/modules/text_server_fb/thorvg_svg_in_ot.cpp @@ -0,0 +1,320 @@ +/*************************************************************************/ +/* thorvg_svg_in_ot.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 GDEXTENSION +// Headers for building as GDExtension plug-in. + +#include <godot_cpp/classes/xml_parser.hpp> +#include <godot_cpp/core/mutex_lock.hpp> +#include <godot_cpp/godot.hpp> +#include <godot_cpp/templates/vector.hpp> + +using namespace godot; + +#else +// Headers for building as built-in module. + +#include "core/error/error_macros.h" +#include "core/io/xml_parser.h" +#include "core/os/memory.h" +#include "core/os/os.h" +#include "core/string/ustring.h" +#include "core/typedefs.h" +#include "core/variant/variant.h" + +#include "modules/modules_enabled.gen.h" // For svg. +#endif + +#ifdef MODULE_SVG_ENABLED + +#include "thorvg_bounds_iterator.h" +#include "thorvg_svg_in_ot.h" + +#include <freetype/otsvg.h> +#include <ft2build.h> + +#include <math.h> +#include <stdlib.h> + +FT_Error tvg_svg_in_ot_init(FT_Pointer *p_state) { + *p_state = memnew(TVG_State); + + return FT_Err_Ok; +} + +void tvg_svg_in_ot_free(FT_Pointer *p_state) { + TVG_State *state = *reinterpret_cast<TVG_State **>(p_state); + memdelete(state); +} + +FT_Error tvg_svg_in_ot_preset_slot(FT_GlyphSlot p_slot, FT_Bool p_cache, FT_Pointer *p_state) { + TVG_State *state = *reinterpret_cast<TVG_State **>(p_state); + if (!state) { + ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "SVG in OT state not initialized."); + } + MutexLock lock(state->mutex); + + FT_SVG_Document document = (FT_SVG_Document)p_slot->other; + FT_Size_Metrics metrics = document->metrics; + + GL_State &gl_state = state->glyph_map[p_slot->glyph_index]; + if (!gl_state.ready) { + Ref<XMLParser> parser; + parser.instantiate(); +#ifdef GDEXTENSION + PackedByteArray data; + data.resize(document->svg_document_length); + memcpy(data.ptrw(), document->svg_document, document->svg_document_length); + parser->open_buffer(data); +#else + parser->_open_buffer((const uint8_t *)document->svg_document, document->svg_document_length); +#endif + + float aspect = 1.0f; + String xml_body; + while (parser->read() == OK) { + if (parser->has_attribute("id")) { +#ifdef GDEXTENSION + const String &gl_name = parser->get_named_attribute_value("id"); +#else + const String &gl_name = parser->get_attribute_value("id"); +#endif + if (gl_name.begins_with("glyph")) { + int dot_pos = gl_name.find("."); + int64_t gl_idx = gl_name.substr(5, (dot_pos > 0) ? dot_pos - 5 : -1).to_int(); + if (p_slot->glyph_index != gl_idx) { + parser->skip_section(); + continue; + } + } + } + if (parser->get_node_type() == XMLParser::NODE_ELEMENT && parser->get_node_name() == "svg") { + if (parser->has_attribute("viewBox")) { +#ifdef GDEXTENSION + PackedStringArray vb = parser->get_named_attribute_value("viewBox").split(" "); +#else + Vector<String> vb = parser->get_attribute_value("viewBox").split(" "); +#endif + + if (vb.size() == 4) { + aspect = vb[2].to_float() / vb[3].to_float(); + } + } + continue; + } +#ifdef GDEXTENSION + if (parser->get_node_type() == XMLParser::NODE_ELEMENT) { + xml_body = xml_body + "<" + parser->get_node_name(); + for (int i = 0; i < parser->get_attribute_count(); i++) { + xml_body = xml_body + " " + parser->get_attribute_name(i) + "=\"" + parser->get_attribute_value(i) + "\""; + } + xml_body = xml_body + ">"; + } else if (parser->get_node_type() == XMLParser::NODE_TEXT) { + xml_body = xml_body + parser->get_node_data(); + } else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END) { + xml_body = xml_body + "</" + parser->get_node_name() + ">"; + } +#else + if (parser->get_node_type() == XMLParser::NODE_ELEMENT) { + xml_body += vformat("<%s", parser->get_node_name()); + for (int i = 0; i < parser->get_attribute_count(); i++) { + xml_body += vformat(" %s=\"%s\"", parser->get_attribute_name(i), parser->get_attribute_value(i)); + } + xml_body += ">"; + } else if (parser->get_node_type() == XMLParser::NODE_TEXT) { + xml_body += parser->get_node_data(); + } else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END) { + xml_body += vformat("</%s>", parser->get_node_name()); + } +#endif + } + String temp_xml = "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 0 0\">" + xml_body; + + std::unique_ptr<tvg::Picture> picture = tvg::Picture::gen(); + tvg::Result result = picture->load(temp_xml.utf8().get_data(), temp_xml.utf8().length(), "svg+xml", false); + if (result != tvg::Result::Success) { + ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to load SVG document (bounds detection)."); + } + + float min_x = INFINITY, min_y = INFINITY, max_x = -INFINITY, max_y = -INFINITY; + tvg_get_bounds(picture.get(), min_x, min_y, max_x, max_y); + + float new_h = (max_y - min_y); + float new_w = (max_x - min_x); + + if (new_h * aspect >= new_w) { + new_w = (new_h * aspect); + } else { + new_h = (new_w / aspect); + } + +#ifdef GDEXTENSION + gl_state.xml_code = "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"" + rtos(min_x) + " " + rtos(min_y) + " " + rtos(new_w) + " " + rtos(new_h) + "\">" + xml_body; +#else + gl_state.xml_code = vformat("<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"%f %f %f %f\">", min_x, min_y, new_w, new_h) + xml_body; +#endif + + picture = tvg::Picture::gen(); + result = picture->load(gl_state.xml_code.utf8().get_data(), gl_state.xml_code.utf8().length(), "svg+xml", false); + if (result != tvg::Result::Success) { + ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to load SVG document (glyph metrics)."); + } + + float x_svg_to_out, y_svg_to_out; + x_svg_to_out = (float)metrics.x_ppem / new_w; + y_svg_to_out = (float)metrics.y_ppem / new_h; + + gl_state.m.e11 = (double)document->transform.xx / (1 << 16) * x_svg_to_out; + gl_state.m.e12 = -(double)document->transform.xy / (1 << 16) * x_svg_to_out; + gl_state.m.e21 = -(double)document->transform.yx / (1 << 16) * y_svg_to_out; + gl_state.m.e22 = (double)document->transform.yy / (1 << 16) * y_svg_to_out; + gl_state.m.e13 = (double)document->delta.x / 64 * new_w / metrics.x_ppem; + gl_state.m.e23 = -(double)document->delta.y / 64 * new_h / metrics.y_ppem; + gl_state.m.e31 = 0; + gl_state.m.e32 = 0; + gl_state.m.e33 = 1; + + result = picture->transform(gl_state.m); + if (result != tvg::Result::Success) { + ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to apply transform to SVG document."); + } + + result = picture->bounds(&gl_state.x, &gl_state.y, &gl_state.w, &gl_state.h, true); + if (result != tvg::Result::Success) { + ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to get SVG bounds."); + } + + gl_state.bmp_y = -min_y * gl_state.h / new_h; + gl_state.bmp_x = min_x * gl_state.w / new_w; + + gl_state.ready = true; + } + + p_slot->bitmap_left = (FT_Int)gl_state.bmp_x; + p_slot->bitmap_top = (FT_Int)gl_state.bmp_y; + + float tmp = ceil(gl_state.h); + p_slot->bitmap.rows = (unsigned int)tmp; + tmp = ceil(gl_state.w); + p_slot->bitmap.width = (unsigned int)tmp; + p_slot->bitmap.pitch = (int)p_slot->bitmap.width * 4; + p_slot->bitmap.pixel_mode = FT_PIXEL_MODE_BGRA; + + float metrics_width, metrics_height; + float horiBearingX, horiBearingY; + float vertBearingX, vertBearingY; + + metrics_width = (float)gl_state.w; + metrics_height = (float)gl_state.h; + horiBearingX = (float)gl_state.x; + horiBearingY = (float)-gl_state.y; + vertBearingX = p_slot->metrics.horiBearingX / 64.0f - p_slot->metrics.horiAdvance / 64.0f / 2; + vertBearingY = (p_slot->metrics.vertAdvance / 64.0f - p_slot->metrics.height / 64.0f) / 2; + + tmp = roundf(metrics_width * 64); + p_slot->metrics.width = (FT_Pos)tmp; + tmp = roundf(metrics_height * 64); + p_slot->metrics.height = (FT_Pos)tmp; + + p_slot->metrics.horiBearingX = (FT_Pos)(horiBearingX * 64); + p_slot->metrics.horiBearingY = (FT_Pos)(horiBearingY * 64); + p_slot->metrics.vertBearingX = (FT_Pos)(vertBearingX * 64); + p_slot->metrics.vertBearingY = (FT_Pos)(vertBearingY * 64); + + if (p_slot->metrics.vertAdvance == 0) { + p_slot->metrics.vertAdvance = (FT_Pos)(metrics_height * 1.2f * 64); + } + + return FT_Err_Ok; +} + +FT_Error tvg_svg_in_ot_render(FT_GlyphSlot p_slot, FT_Pointer *p_state) { + TVG_State *state = *reinterpret_cast<TVG_State **>(p_state); + if (!state) { + ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "SVG in OT state not initialized."); + } + MutexLock lock(state->mutex); + + if (!state->glyph_map.has(p_slot->glyph_index)) { + ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "SVG glyph not loaded."); + } + + GL_State &gl_state = state->glyph_map[p_slot->glyph_index]; + ERR_FAIL_COND_V_MSG(!gl_state.ready, FT_Err_Invalid_SVG_Document, "SVG glyph not ready."); + + std::unique_ptr<tvg::Picture> picture = tvg::Picture::gen(); + tvg::Result res = picture->load(gl_state.xml_code.utf8().get_data(), gl_state.xml_code.utf8().length(), "svg+xml", false); + if (res != tvg::Result::Success) { + ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to load SVG document (glyph rendering)."); + } + res = picture->transform(gl_state.m); + if (res != tvg::Result::Success) { + ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to apply transform to SVG document."); + } + + std::unique_ptr<tvg::SwCanvas> sw_canvas = tvg::SwCanvas::gen(); + res = sw_canvas->target((uint32_t *)p_slot->bitmap.buffer, (int)p_slot->bitmap.width, (int)p_slot->bitmap.width, (int)p_slot->bitmap.rows, tvg::SwCanvas::ARGB8888_STRAIGHT); + if (res != tvg::Result::Success) { + ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to create SVG canvas."); + } + res = sw_canvas->push(std::move(picture)); + if (res != tvg::Result::Success) { + ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to set SVG canvas source."); + } + res = sw_canvas->draw(); + if (res != tvg::Result::Success) { + ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to draw to SVG canvas."); + } + res = sw_canvas->sync(); + if (res != tvg::Result::Success) { + ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to sync SVG canvas."); + } + + state->glyph_map.erase(p_slot->glyph_index); + + p_slot->bitmap.pixel_mode = FT_PIXEL_MODE_BGRA; + p_slot->bitmap.num_grays = 256; + p_slot->format = FT_GLYPH_FORMAT_BITMAP; + + return FT_Err_Ok; +} + +SVG_RendererHooks tvg_svg_in_ot_hooks = { + (SVG_Lib_Init_Func)tvg_svg_in_ot_init, + (SVG_Lib_Free_Func)tvg_svg_in_ot_free, + (SVG_Lib_Render_Func)tvg_svg_in_ot_render, + (SVG_Lib_Preset_Slot_Func)tvg_svg_in_ot_preset_slot, +}; + +SVG_RendererHooks *get_tvg_svg_in_ot_hooks() { + return &tvg_svg_in_ot_hooks; +} + +#endif // MODULE_SVG_ENABLED diff --git a/modules/text_server_fb/thorvg_svg_in_ot.h b/modules/text_server_fb/thorvg_svg_in_ot.h new file mode 100644 index 0000000000..b2816193d9 --- /dev/null +++ b/modules/text_server_fb/thorvg_svg_in_ot.h @@ -0,0 +1,86 @@ +/*************************************************************************/ +/* thorvg_svg_in_ot.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 THORVG_SVG_IN_OT_H +#define THORVG_SVG_IN_OT_H + +#ifdef GDEXTENSION +// Headers for building as GDExtension plug-in. + +#include <godot_cpp/core/mutex_lock.hpp> +#include <godot_cpp/godot.hpp> +#include <godot_cpp/templates/hash_map.hpp> + +using namespace godot; + +#else +// Headers for building as built-in module. + +#include "core/os/mutex.h" +#include "core/templates/hash_map.h" +#include "core/typedefs.h" + +#include "modules/modules_enabled.gen.h" // For svg. +#endif + +#ifdef MODULE_SVG_ENABLED + +#include <freetype/freetype.h> +#include <freetype/otsvg.h> +#include <ft2build.h> +#include <thorvg.h> + +struct GL_State { + bool ready = false; + float bmp_x = 0; + float bmp_y = 0; + float x = 0; + float y = 0; + float w = 0; + float h = 0; + String xml_code; + tvg::Matrix m; +}; + +struct TVG_State { + Mutex mutex; + HashMap<uint32_t, GL_State> glyph_map; +}; + +FT_Error tvg_svg_in_ot_init(FT_Pointer *p_state); +void tvg_svg_in_ot_free(FT_Pointer *p_state); +FT_Error tvg_svg_in_ot_preset_slot(FT_GlyphSlot p_slot, FT_Bool p_cache, FT_Pointer *p_state); +FT_Error tvg_svg_in_ot_render(FT_GlyphSlot p_slot, FT_Pointer *p_state); + +SVG_RendererHooks *get_tvg_svg_in_ot_hooks(); + +#endif // MODULE_SVG_ENABLED + +#endif // THORVG_SVG_IN_OT_H diff --git a/modules/tga/image_loader_tga.cpp b/modules/tga/image_loader_tga.cpp index 16d9bf7b93..8adde3c5d3 100644 --- a/modules/tga/image_loader_tga.cpp +++ b/modules/tga/image_loader_tga.cpp @@ -100,7 +100,7 @@ Error ImageLoaderTGA::convert_to_image(Ref<Image> p_image, const uint8_t *p_buff uint32_t width = p_header.image_width; uint32_t height = p_header.image_height; tga_origin_e origin = static_cast<tga_origin_e>((p_header.image_descriptor & TGA_ORIGIN_MASK) >> TGA_ORIGIN_SHIFT); - + uint8_t alpha_bits = p_header.image_descriptor & TGA_IMAGE_DESCRIPTOR_ALPHA_MASK; uint32_t x_start; int32_t x_step; uint32_t x_end; @@ -184,6 +184,27 @@ Error ImageLoaderTGA::convert_to_image(Ref<Image> p_image, const uint8_t *p_buff y += y_step; } } + } else if (p_header.pixel_depth == 16) { + while (y != y_end) { + while (x != x_end) { + if (i + 1 >= p_input_size) { + return ERR_PARSE_ERROR; + } + + // Always stored as RGBA5551 + uint8_t r = (p_buffer[i + 1] & 0x7c) << 1; + uint8_t g = ((p_buffer[i + 1] & 0x03) << 6) | ((p_buffer[i + 0] & 0xe0) >> 2); + uint8_t b = (p_buffer[i + 0] & 0x1f) << 3; + uint8_t a = (p_buffer[i + 1] & 0x80) ? 0xff : 0; + + TGA_PUT_PIXEL(r, g, b, alpha_bits ? a : 0xff); + + x += x_step; + i += 2; + } + x = x_start; + y += y_step; + } } else if (p_header.pixel_depth == 24) { while (y != y_end) { while (x != x_end) { @@ -225,12 +246,12 @@ Error ImageLoaderTGA::convert_to_image(Ref<Image> p_image, const uint8_t *p_buff } } - p_image->create(width, height, false, Image::FORMAT_RGBA8, image_data); + p_image->initialize_data(width, height, false, Image::FORMAT_RGBA8, image_data); return OK; } -Error ImageLoaderTGA::load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale) { +Error ImageLoaderTGA::load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale) { Vector<uint8_t> src_image; uint64_t src_image_len = f->get_length(); ERR_FAIL_COND_V(src_image_len == 0, ERR_FILE_CORRUPT); @@ -263,21 +284,28 @@ Error ImageLoaderTGA::load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t err = FAILED; } + uint64_t color_map_size; if (has_color_map) { if (tga_header.color_map_length > 256 || (tga_header.color_map_depth != 24) || tga_header.color_map_type != 1) { err = FAILED; } + color_map_size = tga_header.color_map_length * (tga_header.color_map_depth >> 3); } else { if (tga_header.color_map_type) { err = FAILED; } + color_map_size = 0; + } + + if ((src_image_len - f->get_position()) < (tga_header.id_length + color_map_size)) { + err = FAILED; // TGA data appears to be truncated (fewer bytes than expected). } if (tga_header.image_width <= 0 || tga_header.image_height <= 0) { err = FAILED; } - if (!(tga_header.pixel_depth == 8 || tga_header.pixel_depth == 24 || tga_header.pixel_depth == 32)) { + if (!(tga_header.pixel_depth == 8 || tga_header.pixel_depth == 16 || tga_header.pixel_depth == 24 || tga_header.pixel_depth == 32)) { err = FAILED; } @@ -287,7 +315,6 @@ Error ImageLoaderTGA::load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t Vector<uint8_t> palette; if (has_color_map) { - size_t color_map_size = tga_header.color_map_length * (tga_header.color_map_depth >> 3); err = palette.resize(color_map_size); if (err == OK) { uint8_t *palette_w = palette.ptrw(); diff --git a/modules/tga/image_loader_tga.h b/modules/tga/image_loader_tga.h index d95c5ff30b..de964373ed 100644 --- a/modules/tga/image_loader_tga.h +++ b/modules/tga/image_loader_tga.h @@ -33,6 +33,8 @@ #include "core/io/image_loader.h" +#define TGA_IMAGE_DESCRIPTOR_ALPHA_MASK 0xf + class ImageLoaderTGA : public ImageFormatLoader { enum tga_type_e { TGA_TYPE_NO_DATA = 0, @@ -73,7 +75,7 @@ class ImageLoaderTGA : public ImageFormatLoader { static Error convert_to_image(Ref<Image> p_image, const uint8_t *p_buffer, const tga_header_s &p_header, const uint8_t *p_palette, const bool p_is_monochrome, size_t p_input_size); public: - virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale); + virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale); virtual void get_recognized_extensions(List<String> *p_extensions) const; ImageLoaderTGA(); }; diff --git a/modules/tga/register_types.cpp b/modules/tga/register_types.cpp index 520ed5f799..3a9d2324e7 100644 --- a/modules/tga/register_types.cpp +++ b/modules/tga/register_types.cpp @@ -32,14 +32,14 @@ #include "image_loader_tga.h" -static ImageLoaderTGA *image_loader_tga = nullptr; +static Ref<ImageLoaderTGA> image_loader_tga; void initialize_tga_module(ModuleInitializationLevel p_level) { if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) { return; } - image_loader_tga = memnew(ImageLoaderTGA); + image_loader_tga.instantiate(); ImageLoader::add_image_format_loader(image_loader_tga); } @@ -48,5 +48,6 @@ void uninitialize_tga_module(ModuleInitializationLevel p_level) { return; } - memdelete(image_loader_tga); + ImageLoader::remove_image_format_loader(image_loader_tga); + image_loader_tga.unref(); } diff --git a/modules/theora/video_stream_theora.cpp b/modules/theora/video_stream_theora.cpp index c4462ba687..83833d8253 100644 --- a/modules/theora/video_stream_theora.cpp +++ b/modules/theora/video_stream_theora.cpp @@ -33,8 +33,17 @@ #include "core/config/project_settings.h" #include "core/os/os.h" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4127) +#endif + #include "thirdparty/misc/yuv2rgb.h" +#ifdef _MSC_VER +#pragma warning(pop) +#endif + int VideoStreamPlaybackTheora::buffer_data() { char *buffer = ogg_sync_buffer(&oy, 4096); @@ -91,8 +100,6 @@ void VideoStreamPlaybackTheora::video_write() { uint8_t *w = frame_data.ptrw(); char *dst = (char *)w; - //uv_offset=(ti.pic_x/2)+(yuv[1].stride)*(ti.pic_y/2); - if (px_fmt == TH_PF_444) { yuv444_2_rgb8888((uint8_t *)dst, (uint8_t *)yuv[0].data, (uint8_t *)yuv[1].data, (uint8_t *)yuv[2].data, size.x, size.y, yuv[0].stride, yuv[1].stride, size.x << 2); @@ -101,7 +108,7 @@ void VideoStreamPlaybackTheora::video_write() { } else if (px_fmt == TH_PF_420) { yuv420_2_rgb8888((uint8_t *)dst, (uint8_t *)yuv[0].data, (uint8_t *)yuv[1].data, (uint8_t *)yuv[2].data, size.x, size.y, yuv[0].stride, yuv[1].stride, size.x << 2); - }; + } format = Image::FORMAT_RGBA8; } @@ -123,7 +130,7 @@ void VideoStreamPlaybackTheora::clear() { if (vorbis_p >= 3) { vorbis_block_clear(&vb); vorbis_dsp_clear(&vd); - }; + } vorbis_comment_clear(&vc); vorbis_info_clear(&vi); vorbis_p = 0; @@ -154,7 +161,7 @@ void VideoStreamPlaybackTheora::clear() { file.unref(); playing = false; -}; +} void VideoStreamPlaybackTheora::set_file(const String &p_file) { ERR_FAIL_COND(playing); @@ -174,7 +181,6 @@ void VideoStreamPlaybackTheora::set_file(const String &p_file) { ring_buffer.write(read_buffer.ptr(), read); thread.start(_streaming_thread, this); - #endif ogg_sync_init(&oy); @@ -245,10 +251,9 @@ void VideoStreamPlaybackTheora::set_file(const String &p_file) { /* we're expecting more header packets. */ while ((theora_p && theora_p < 3) || (vorbis_p && vorbis_p < 3)) { - int ret; - /* look for further theora headers */ - while (theora_p && (theora_p < 3) && (ret = ogg_stream_packetout(&to, &op))) { + int ret = ogg_stream_packetout(&to, &op); + while (theora_p && theora_p < 3 && ret) { if (ret < 0) { fprintf(stderr, "Error parsing Theora stream headers; corrupt stream?\n"); clear(); @@ -259,11 +264,13 @@ void VideoStreamPlaybackTheora::set_file(const String &p_file) { clear(); return; } + ret = ogg_stream_packetout(&to, &op); theora_p++; } /* look for more vorbis header packets */ - while (vorbis_p && (vorbis_p < 3) && (ret = ogg_stream_packetout(&vo, &op))) { + ret = ogg_stream_packetout(&vo, &op); + while (vorbis_p && vorbis_p < 3 && ret) { if (ret < 0) { fprintf(stderr, "Error parsing Vorbis stream headers; corrupt stream?\n"); clear(); @@ -279,6 +286,7 @@ void VideoStreamPlaybackTheora::set_file(const String &p_file) { if (vorbis_p == 3) { break; } + ret = ogg_stream_packetout(&vo, &op); } /* The header pages/packets will arrive before anything else we @@ -328,9 +336,7 @@ void VideoStreamPlaybackTheora::set_file(const String &p_file) { size.x = w; size.y = h; - Ref<Image> img; - img.instantiate(); - img->create(w, h, false, Image::FORMAT_RGBA8); + Ref<Image> img = Image::create_empty(w, h, false, Image::FORMAT_RGBA8); texture->set_image(img); } else { @@ -355,20 +361,20 @@ void VideoStreamPlaybackTheora::set_file(const String &p_file) { buffering = true; time = 0; audio_frames_wrote = 0; -}; +} -float VideoStreamPlaybackTheora::get_time() const { +double VideoStreamPlaybackTheora::get_time() const { // FIXME: AudioServer output latency was fixed in af9bb0e, previously it used to // systematically return 0. Now that it gives a proper latency, it broke this // code where the delay compensation likely never really worked. return time - /* AudioServer::get_singleton()->get_output_latency() - */ delay_compensation; -}; +} Ref<Texture2D> VideoStreamPlaybackTheora::get_texture() const { return texture; } -void VideoStreamPlaybackTheora::update(float p_delta) { +void VideoStreamPlaybackTheora::update(double p_delta) { if (file.is_null()) { return; } @@ -376,7 +382,7 @@ void VideoStreamPlaybackTheora::update(float p_delta) { if (!playing || paused) { //printf("not playing\n"); return; - }; + } #ifdef THEORA_USE_THREAD_STREAMING thread_sem->post(); @@ -444,7 +450,7 @@ void VideoStreamPlaybackTheora::update(float p_delta) { } } else { /* we need more data; break out to suck in another page */ break; - }; + } } audio_done = videobuf_time < (audio_frames_wrote / float(vi.rate)); @@ -457,12 +463,6 @@ void VideoStreamPlaybackTheora::update(float p_delta) { while (theora_p && !frame_done) { /* theora is one in, one out... */ if (ogg_stream_packetout(&to, &op) > 0) { - if (false && pp_inc) { - pp_level += pp_inc; - th_decode_ctl(td, TH_DECCTL_SET_PPLEVEL, &pp_level, - sizeof(pp_level)); - pp_inc = 0; - } /*HACK: This should be set after a seek or a gap, but we might not have a granulepos for the first packet (we only have them for the last packet on a page), so we just set it as often as we get it. @@ -507,7 +507,7 @@ void VideoStreamPlaybackTheora::update(float p_delta) { //printf("video done, stopping\n"); stop(); return; - }; + } if (!frame_done || !audio_done) { //what's the point of waiting for audio to grab a page? @@ -529,7 +529,7 @@ void VideoStreamPlaybackTheora::update(float p_delta) { //printf("frame at %f not ready (time %f), ready %i\n", (float)videobuf_time, get_time(), videobuf_ready); } - float tdiff = videobuf_time - get_time(); + double tdiff = videobuf_time - get_time(); /*If we have lots of extra time, increase the post-processing level.*/ if (tdiff > ti.fps_denominator * 0.25 / ti.fps_numerator) { pp_inc = pp_level < pp_level_max ? 1 : 0; @@ -539,7 +539,7 @@ void VideoStreamPlaybackTheora::update(float p_delta) { } video_write(); -}; +} void VideoStreamPlaybackTheora::play() { if (!playing) { @@ -549,9 +549,9 @@ void VideoStreamPlaybackTheora::play() { } playing = true; - delay_compensation = ProjectSettings::get_singleton()->get("audio/video/video_delay_compensation_ms"); + delay_compensation = GLOBAL_GET("audio/video/video_delay_compensation_ms"); delay_compensation /= 1000.0; -}; +} void VideoStreamPlaybackTheora::stop() { if (playing) { @@ -560,44 +560,44 @@ void VideoStreamPlaybackTheora::stop() { } playing = false; time = 0; -}; +} bool VideoStreamPlaybackTheora::is_playing() const { return playing; -}; +} void VideoStreamPlaybackTheora::set_paused(bool p_paused) { paused = p_paused; -}; +} bool VideoStreamPlaybackTheora::is_paused() const { return paused; -}; +} void VideoStreamPlaybackTheora::set_loop(bool p_enable) { } bool VideoStreamPlaybackTheora::has_loop() const { return false; -}; +} -float VideoStreamPlaybackTheora::get_length() const { +double VideoStreamPlaybackTheora::get_length() const { return 0; -}; +} String VideoStreamPlaybackTheora::get_stream_name() const { return ""; -}; +} int VideoStreamPlaybackTheora::get_loop_count() const { return 0; -}; +} -float VideoStreamPlaybackTheora::get_playback_position() const { +double VideoStreamPlaybackTheora::get_playback_position() const { return get_time(); -}; +} -void VideoStreamPlaybackTheora::seek(float p_time) { +void VideoStreamPlaybackTheora::seek(double p_time) { WARN_PRINT_ONCE("Seeking in Theora videos is not implemented yet (it's only supported for GDExtension-provided video streams)."); } @@ -650,15 +650,14 @@ VideoStreamPlaybackTheora::VideoStreamPlaybackTheora() { thread_sem = Semaphore::create(); #endif -}; +} VideoStreamPlaybackTheora::~VideoStreamPlaybackTheora() { #ifdef THEORA_USE_THREAD_STREAMING - memdelete(thread_sem); #endif clear(); -}; +} void VideoStreamTheora::_bind_methods() { ClassDB::bind_method(D_METHOD("set_file", "file"), &VideoStreamTheora::set_file); diff --git a/modules/theora/video_stream_theora.h b/modules/theora/video_stream_theora.h index 00d799dc24..9e096ec8b7 100644 --- a/modules/theora/video_stream_theora.h +++ b/modules/theora/video_stream_theora.h @@ -64,7 +64,7 @@ class VideoStreamPlaybackTheora : public VideoStreamPlayback { int buffer_data(); int queue_page(ogg_page *page); void video_write(); - float get_time() const; + double get_time() const; bool theora_eos = false; bool vorbis_eos = false; @@ -76,7 +76,7 @@ class VideoStreamPlaybackTheora : public VideoStreamPlayback { th_info ti; th_comment tc; th_dec_ctx *td = nullptr; - vorbis_info vi; + vorbis_info vi = {}; vorbis_dsp_state vd; vorbis_block vb; vorbis_comment vc; @@ -136,19 +136,19 @@ public: virtual void set_loop(bool p_enable) override; virtual bool has_loop() const override; - virtual float get_length() const override; + virtual double get_length() const override; virtual String get_stream_name() const; virtual int get_loop_count() const; - virtual float get_playback_position() const override; - virtual void seek(float p_time) override; + virtual double get_playback_position() const override; + virtual void seek(double p_time) override; void set_file(const String &p_file); virtual Ref<Texture2D> get_texture() const override; - virtual void update(float p_delta) override; + virtual void update(double p_delta) override; virtual void set_mix_callback(AudioMixCallback p_callback, void *p_userdata) override; virtual int get_channels() const override; diff --git a/modules/tinyexr/config.py b/modules/tinyexr/config.py index 53b8f2f2e3..eb565b85b9 100644 --- a/modules/tinyexr/config.py +++ b/modules/tinyexr/config.py @@ -1,5 +1,5 @@ def can_build(env, platform): - return env["tools"] + return env.editor_build def configure(env): diff --git a/modules/tinyexr/image_loader_tinyexr.cpp b/modules/tinyexr/image_loader_tinyexr.cpp index 6f61251f9b..c5aa110fe6 100644 --- a/modules/tinyexr/image_loader_tinyexr.cpp +++ b/modules/tinyexr/image_loader_tinyexr.cpp @@ -37,7 +37,7 @@ #include "thirdparty/tinyexr/tinyexr.h" -Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale) { +Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale) { Vector<uint8_t> src_image; uint64_t src_image_len = f->get_length(); ERR_FAIL_COND_V(src_image_len == 0, ERR_FILE_CORRUPT); @@ -280,7 +280,7 @@ Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, Ref<FileAccess> f, uint } } - p_image->create(exr_image.width, exr_image.height, false, format, imgdata); + p_image->set_data(exr_image.width, exr_image.height, false, format, imgdata); FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); diff --git a/modules/tinyexr/image_loader_tinyexr.h b/modules/tinyexr/image_loader_tinyexr.h index 8da2a0d4af..ab34a59da5 100644 --- a/modules/tinyexr/image_loader_tinyexr.h +++ b/modules/tinyexr/image_loader_tinyexr.h @@ -35,7 +35,7 @@ class ImageLoaderTinyEXR : public ImageFormatLoader { public: - virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale); + virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale); virtual void get_recognized_extensions(List<String> *p_extensions) const; ImageLoaderTinyEXR(); }; diff --git a/modules/tinyexr/register_types.cpp b/modules/tinyexr/register_types.cpp index c5897f37c3..b1a9f18e3b 100644 --- a/modules/tinyexr/register_types.cpp +++ b/modules/tinyexr/register_types.cpp @@ -33,14 +33,14 @@ #include "image_loader_tinyexr.h" #include "image_saver_tinyexr.h" -static ImageLoaderTinyEXR *image_loader_tinyexr = nullptr; +static Ref<ImageLoaderTinyEXR> image_loader_tinyexr; void initialize_tinyexr_module(ModuleInitializationLevel p_level) { if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) { return; } - image_loader_tinyexr = memnew(ImageLoaderTinyEXR); + image_loader_tinyexr.instantiate(); ImageLoader::add_image_format_loader(image_loader_tinyexr); Image::save_exr_func = save_exr; @@ -52,7 +52,8 @@ void uninitialize_tinyexr_module(ModuleInitializationLevel p_level) { return; } - memdelete(image_loader_tinyexr); + ImageLoader::remove_image_format_loader(image_loader_tinyexr); + image_loader_tinyexr.unref(); Image::save_exr_func = nullptr; } diff --git a/modules/upnp/doc_classes/UPNP.xml b/modules/upnp/doc_classes/UPNP.xml index 4888dca822..92e25efbe0 100644 --- a/modules/upnp/doc_classes/UPNP.xml +++ b/modules/upnp/doc_classes/UPNP.xml @@ -41,7 +41,7 @@ func _ready(): thread = Thread.new() - thread.start(self, "_upnp_setup", SERVER_PORT) + thread.start(_upnp_setup.bind(SERVER_PORT)) func _exit_tree(): # Wait for thread finish here to handle game exit while the thread is running. @@ -74,7 +74,7 @@ <param index="3" name="proto" type="String" default=""UDP"" /> <param index="4" name="duration" type="int" default="0" /> <description> - Adds a mapping to forward the external [code]port[/code] (between 1 and 65535, although recommended to use port 1024 or above) on the default gateway (see [method get_gateway]) to the [code]internal_port[/code] on the local machine for the given protocol [code]proto[/code] (either [code]TCP[/code] or [code]UDP[/code], with UDP being the default). If a port mapping for the given port and protocol combination already exists on that gateway device, this method tries to overwrite it. If that is not desired, you can retrieve the gateway manually with [method get_gateway] and call [method add_port_mapping] on it, if any. Note that forwarding a well-known port (below 1024) with UPnP may fail depending on the device. + Adds a mapping to forward the external [code]port[/code] (between 1 and 65535, although recommended to use port 1024 or above) on the default gateway (see [method get_gateway]) to the [code]internal_port[/code] on the local machine for the given protocol [code]proto[/code] (either [code]"TCP"[/code] or [code]"UDP"[/code], with UDP being the default). If a port mapping for the given port and protocol combination already exists on that gateway device, this method tries to overwrite it. If that is not desired, you can retrieve the gateway manually with [method get_gateway] and call [method add_port_mapping] on it, if any. Note that forwarding a well-known port (below 1024) with UPnP may fail depending on the device. Depending on the gateway device, if a mapping for that port already exists, it will either be updated or it will refuse this command due to that conflict, especially if the existing mapping for that port wasn't created via UPnP or points to a different network address (or device) than this one. If [code]internal_port[/code] is [code]0[/code] (the default), the same port number is used for both the external and the internal port (the [code]port[/code] value). The description ([code]desc[/code]) is shown in some routers management UIs and can be used to point out which application added the mapping. @@ -93,7 +93,7 @@ <param index="0" name="port" type="int" /> <param index="1" name="proto" type="String" default=""UDP"" /> <description> - Deletes the port mapping for the given port and protocol combination on the default gateway (see [method get_gateway]) if one exists. [code]port[/code] must be a valid port between 1 and 65535, [code]proto[/code] can be either [code]TCP[/code] or [code]UDP[/code]. May be refused for mappings pointing to addresses other than this one, for well-known ports (below 1024), or for mappings not added via UPnP. See [enum UPNPResult] for possible return values. + Deletes the port mapping for the given port and protocol combination on the default gateway (see [method get_gateway]) if one exists. [code]port[/code] must be a valid port between 1 and 65535, [code]proto[/code] can be either [code]"TCP"[/code] or [code]"UDP"[/code]. May be refused for mappings pointing to addresses other than this one, for well-known ports (below 1024), or for mappings not added via UPnP. See [enum UPNPResult] for possible return values. </description> </method> <method name="discover"> diff --git a/modules/vorbis/audio_stream_ogg_vorbis.cpp b/modules/vorbis/audio_stream_ogg_vorbis.cpp index 8315eea614..792103cd31 100644 --- a/modules/vorbis/audio_stream_ogg_vorbis.cpp +++ b/modules/vorbis/audio_stream_ogg_vorbis.cpp @@ -74,7 +74,7 @@ int AudioStreamPlaybackOggVorbis::_mix_internal(AudioFrame *p_buffer, int p_fram if (beat_length_frames >= 0) { /** * Length determined by beat length - * This code is commented out because, in practice, it is prefered that the fade + * This code is commented out because, in practice, it is preferred that the fade * is done by the transitioner and this stream just goes on until it ends while fading out. * * End fade implementation is left here for reference in case at some point this feature @@ -153,8 +153,11 @@ int AudioStreamPlaybackOggVorbis::_mix_frames_vorbis(AudioFrame *p_buffer, int p return -1; } - ERR_FAIL_COND_V_MSG((err = vorbis_synthesis(&block, packet)), 0, "Error during vorbis synthesis " + itos(err)); - ERR_FAIL_COND_V_MSG((err = vorbis_synthesis_blockin(&dsp_state, &block)), 0, "Error during vorbis block processing " + itos(err)); + err = vorbis_synthesis(&block, packet); + ERR_FAIL_COND_V_MSG(err != 0, 0, "Error during vorbis synthesis " + itos(err)); + + err = vorbis_synthesis_blockin(&dsp_state, &block); + ERR_FAIL_COND_V_MSG(err != 0, 0, "Error during vorbis block processing " + itos(err)); have_packets_left = !packet->e_o_s; } @@ -223,7 +226,7 @@ bool AudioStreamPlaybackOggVorbis::_alloc_vorbis() { return true; } -void AudioStreamPlaybackOggVorbis::start(float p_from_pos) { +void AudioStreamPlaybackOggVorbis::start(double p_from_pos) { ERR_FAIL_COND(!ready); loop_fade_remaining = FADE_SIZE; active = true; @@ -244,15 +247,15 @@ int AudioStreamPlaybackOggVorbis::get_loop_count() const { return loops; } -float AudioStreamPlaybackOggVorbis::get_playback_position() const { - return float(frames_mixed) / vorbis_data->get_sampling_rate(); +double AudioStreamPlaybackOggVorbis::get_playback_position() const { + return double(frames_mixed) / (double)vorbis_data->get_sampling_rate(); } void AudioStreamPlaybackOggVorbis::tag_used_streams() { vorbis_stream->tag_used(get_playback_position()); } -void AudioStreamPlaybackOggVorbis::seek(float p_time) { +void AudioStreamPlaybackOggVorbis::seek(double p_time) { ERR_FAIL_COND(!ready); ERR_FAIL_COND(vorbis_stream.is_null()); if (!active) { @@ -290,11 +293,15 @@ void AudioStreamPlaybackOggVorbis::seek(float p_time) { headers_remaining = 3; } if (!headers_remaining) { - ERR_FAIL_COND_MSG((err = vorbis_synthesis(&block, packet)), "Error during vorbis synthesis " + itos(err)); - ERR_FAIL_COND_MSG((err = vorbis_synthesis_blockin(&dsp_state, &block)), "Error during vorbis block processing " + itos(err)); + err = vorbis_synthesis(&block, packet); + ERR_FAIL_COND_MSG(err != 0, "Error during vorbis synthesis " + itos(err)); + + err = vorbis_synthesis_blockin(&dsp_state, &block); + ERR_FAIL_COND_MSG(err != 0, "Error during vorbis block processing " + itos(err)); int samples_out = vorbis_synthesis_pcmout(&dsp_state, nullptr); - ERR_FAIL_COND_MSG((err = vorbis_synthesis_read(&dsp_state, samples_out)), "Error during vorbis read updating " + itos(err)); + err = vorbis_synthesis_read(&dsp_state, samples_out); + ERR_FAIL_COND_MSG(err != 0, "Error during vorbis read updating " + itos(err)); samples_in_page += samples_out; @@ -341,12 +348,16 @@ void AudioStreamPlaybackOggVorbis::seek(float p_time) { headers_remaining = 3; } if (!headers_remaining) { - ERR_FAIL_COND_MSG((err = vorbis_synthesis(&block, packet)), "Error during vorbis synthesis " + itos(err)); - ERR_FAIL_COND_MSG((err = vorbis_synthesis_blockin(&dsp_state, &block)), "Error during vorbis block processing " + itos(err)); + err = vorbis_synthesis(&block, packet); + ERR_FAIL_COND_MSG(err != 0, "Error during vorbis synthesis " + itos(err)); + + err = vorbis_synthesis_blockin(&dsp_state, &block); + ERR_FAIL_COND_MSG(err != 0, "Error during vorbis block processing " + itos(err)); int samples_out = vorbis_synthesis_pcmout(&dsp_state, nullptr); int read_samples = samples_to_burn > samples_out ? samples_out : samples_to_burn; - ERR_FAIL_COND_MSG((err = vorbis_synthesis_read(&dsp_state, samples_out)), "Error during vorbis read updating " + itos(err)); + err = vorbis_synthesis_read(&dsp_state, samples_out); + ERR_FAIL_COND_MSG(err != 0, "Error during vorbis read updating " + itos(err)); samples_to_burn -= read_samples; if (samples_to_burn <= 0) { @@ -462,15 +473,15 @@ bool AudioStreamOggVorbis::has_loop() const { return loop; } -void AudioStreamOggVorbis::set_loop_offset(float p_seconds) { +void AudioStreamOggVorbis::set_loop_offset(double p_seconds) { loop_offset = p_seconds; } -float AudioStreamOggVorbis::get_loop_offset() const { +double AudioStreamOggVorbis::get_loop_offset() const { return loop_offset; } -float AudioStreamOggVorbis::get_length() const { +double AudioStreamOggVorbis::get_length() const { ERR_FAIL_COND_V(packet_sequence.is_null(), 0); return packet_sequence->get_length(); } diff --git a/modules/vorbis/audio_stream_ogg_vorbis.h b/modules/vorbis/audio_stream_ogg_vorbis.h index 0350e1f761..3aa99971be 100644 --- a/modules/vorbis/audio_stream_ogg_vorbis.h +++ b/modules/vorbis/audio_stream_ogg_vorbis.h @@ -83,14 +83,14 @@ protected: virtual float get_stream_sampling_rate() override; public: - virtual void start(float p_from_pos = 0.0) override; + virtual void start(double p_from_pos = 0.0) override; virtual void stop() override; virtual bool is_playing() const override; virtual int get_loop_count() const override; //times it looped - virtual float get_playback_position() const override; - virtual void seek(float p_time) override; + virtual double get_playback_position() const override; + virtual void seek(double p_time) override; virtual void tag_used_streams() override; @@ -127,8 +127,8 @@ public: void set_loop(bool p_enable); virtual bool has_loop() const override; - void set_loop_offset(float p_seconds); - float get_loop_offset() const; + void set_loop_offset(double p_seconds); + double get_loop_offset() const; void set_bpm(double p_bpm); virtual double get_bpm() const override; @@ -145,7 +145,7 @@ public: void set_packet_sequence(Ref<OggPacketSequence> p_packet_sequence); Ref<OggPacketSequence> get_packet_sequence() const; - virtual float get_length() const override; //if supported, otherwise return 0 + virtual double get_length() const override; //if supported, otherwise return 0 virtual bool is_monophonic() const override; diff --git a/modules/vorbis/resource_importer_ogg_vorbis.cpp b/modules/vorbis/resource_importer_ogg_vorbis.cpp index bf5f7206b8..a491c3d3fb 100644 --- a/modules/vorbis/resource_importer_ogg_vorbis.cpp +++ b/modules/vorbis/resource_importer_ogg_vorbis.cpp @@ -110,15 +110,18 @@ Ref<AudioStreamOggVorbis> ResourceImporterOggVorbis::import_ogg_vorbis(const Str size_t packet_count = 0; bool done = false; while (!done) { - ERR_FAIL_COND_V_MSG((err = ogg_sync_check(&sync_state)), Ref<AudioStreamOggVorbis>(), "Ogg sync error " + itos(err)); + err = ogg_sync_check(&sync_state); + ERR_FAIL_COND_V_MSG(err != 0, Ref<AudioStreamOggVorbis>(), "Ogg sync error " + itos(err)); while (ogg_sync_pageout(&sync_state, &page) != 1) { if (cursor >= len) { done = true; break; } - ERR_FAIL_COND_V_MSG((err = ogg_sync_check(&sync_state)), Ref<AudioStreamOggVorbis>(), "Ogg sync error " + itos(err)); + err = ogg_sync_check(&sync_state); + ERR_FAIL_COND_V_MSG(err != 0, Ref<AudioStreamOggVorbis>(), "Ogg sync error " + itos(err)); char *sync_buf = ogg_sync_buffer(&sync_state, OGG_SYNC_BUFFER_SIZE); - ERR_FAIL_COND_V_MSG((err = ogg_sync_check(&sync_state)), Ref<AudioStreamOggVorbis>(), "Ogg sync error " + itos(err)); + err = ogg_sync_check(&sync_state); + ERR_FAIL_COND_V_MSG(err != 0, Ref<AudioStreamOggVorbis>(), "Ogg sync error " + itos(err)); ERR_FAIL_COND_V(cursor > len, Ref<AudioStreamOggVorbis>()); size_t copy_size = len - cursor; if (copy_size > OGG_SYNC_BUFFER_SIZE) { @@ -127,12 +130,14 @@ Ref<AudioStreamOggVorbis> ResourceImporterOggVorbis::import_ogg_vorbis(const Str memcpy(sync_buf, &file_data[cursor], copy_size); ogg_sync_wrote(&sync_state, copy_size); cursor += copy_size; - ERR_FAIL_COND_V_MSG((err = ogg_sync_check(&sync_state)), Ref<AudioStreamOggVorbis>(), "Ogg sync error " + itos(err)); + err = ogg_sync_check(&sync_state); + ERR_FAIL_COND_V_MSG(err != 0, Ref<AudioStreamOggVorbis>(), "Ogg sync error " + itos(err)); } if (done) { break; } - ERR_FAIL_COND_V_MSG((err = ogg_sync_check(&sync_state)), Ref<AudioStreamOggVorbis>(), "Ogg sync error " + itos(err)); + err = ogg_sync_check(&sync_state); + ERR_FAIL_COND_V_MSG(err != 0, Ref<AudioStreamOggVorbis>(), "Ogg sync error " + itos(err)); // Have a page now. if (!initialized_stream) { @@ -142,7 +147,8 @@ Ref<AudioStreamOggVorbis> ResourceImporterOggVorbis::import_ogg_vorbis(const Str initialized_stream = true; } ogg_stream_pagein(&stream_state, &page); - ERR_FAIL_COND_V_MSG((err = ogg_stream_check(&stream_state)), Ref<AudioStreamOggVorbis>(), "Ogg stream error " + itos(err)); + err = ogg_stream_check(&stream_state); + ERR_FAIL_COND_V_MSG(err != 0, Ref<AudioStreamOggVorbis>(), "Ogg stream error " + itos(err)); int desync_iters = 0; Vector<Vector<uint8_t>> packet_data; diff --git a/modules/webp/image_loader_webp.cpp b/modules/webp/image_loader_webp.cpp index 705ab508ab..dd387db554 100644 --- a/modules/webp/image_loader_webp.cpp +++ b/modules/webp/image_loader_webp.cpp @@ -48,7 +48,7 @@ static Ref<Image> _webp_mem_loader_func(const uint8_t *p_png, int p_size) { return img; } -Error ImageLoaderWebP::load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale) { +Error ImageLoaderWebP::load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale) { Vector<uint8_t> src_image; uint64_t src_image_len = f->get_length(); ERR_FAIL_COND_V(src_image_len == 0, ERR_FILE_CORRUPT); diff --git a/modules/webp/image_loader_webp.h b/modules/webp/image_loader_webp.h index d868ae3f7f..0522e4ef91 100644 --- a/modules/webp/image_loader_webp.h +++ b/modules/webp/image_loader_webp.h @@ -35,7 +35,7 @@ class ImageLoaderWebP : public ImageFormatLoader { public: - virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale); + virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale); virtual void get_recognized_extensions(List<String> *p_extensions) const; ImageLoaderWebP(); }; diff --git a/modules/webp/register_types.cpp b/modules/webp/register_types.cpp index 29f633743e..e523f43cfe 100644 --- a/modules/webp/register_types.cpp +++ b/modules/webp/register_types.cpp @@ -33,7 +33,7 @@ #include "image_loader_webp.h" #include "resource_saver_webp.h" -static ImageLoaderWebP *image_loader_webp = nullptr; +static Ref<ImageLoaderWebP> image_loader_webp; static Ref<ResourceSaverWebP> resource_saver_webp; void initialize_webp_module(ModuleInitializationLevel p_level) { @@ -41,9 +41,10 @@ void initialize_webp_module(ModuleInitializationLevel p_level) { return; } - image_loader_webp = memnew(ImageLoaderWebP); - resource_saver_webp.instantiate(); + image_loader_webp.instantiate(); ImageLoader::add_image_format_loader(image_loader_webp); + + resource_saver_webp.instantiate(); ResourceSaver::add_resource_format_saver(resource_saver_webp); } @@ -52,7 +53,9 @@ void uninitialize_webp_module(ModuleInitializationLevel p_level) { return; } - memdelete(image_loader_webp); + ImageLoader::remove_image_format_loader(image_loader_webp); + image_loader_webp.unref(); + ResourceSaver::remove_resource_format_saver(resource_saver_webp); resource_saver_webp.unref(); } diff --git a/modules/webp/resource_saver_webp.cpp b/modules/webp/resource_saver_webp.cpp index bd71c2869a..56ff8097b4 100644 --- a/modules/webp/resource_saver_webp.cpp +++ b/modules/webp/resource_saver_webp.cpp @@ -38,8 +38,8 @@ Error ResourceSaverWebP::save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags) { Ref<ImageTexture> texture = p_resource; - ERR_FAIL_COND_V_MSG(!texture.is_valid(), ERR_INVALID_PARAMETER, "Can't save invalid texture as WEBP."); - ERR_FAIL_COND_V_MSG(!texture->get_width(), ERR_INVALID_PARAMETER, "Can't save empty texture as WEBP."); + ERR_FAIL_COND_V_MSG(!texture.is_valid(), ERR_INVALID_PARAMETER, "Can't save invalid texture as WebP."); + ERR_FAIL_COND_V_MSG(!texture->get_width(), ERR_INVALID_PARAMETER, "Can't save empty texture as WebP."); Ref<Image> img = texture->get_image(); @@ -52,7 +52,7 @@ Error ResourceSaverWebP::save_image(const String &p_path, const Ref<Image> &p_im Vector<uint8_t> buffer = save_image_to_buffer(p_img, p_lossy, p_quality); Error err; Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err); - ERR_FAIL_COND_V_MSG(err, err, vformat("Can't save WEBP at path: '%s'.", p_path)); + ERR_FAIL_COND_V_MSG(err, err, vformat("Can't save WebP at path: '%s'.", p_path)); const uint8_t *reader = buffer.ptr(); diff --git a/modules/webp/webp_common.cpp b/modules/webp/webp_common.cpp index 8657a98853..af98788420 100644 --- a/modules/webp/webp_common.cpp +++ b/modules/webp/webp_common.cpp @@ -73,7 +73,7 @@ Vector<uint8_t> _webp_lossy_pack(const Ref<Image> &p_image, float p_quality) { Vector<uint8_t> _webp_lossless_pack(const Ref<Image> &p_image) { ERR_FAIL_COND_V(p_image.is_null() || p_image->is_empty(), Vector<uint8_t>()); - int compression_level = ProjectSettings::get_singleton()->get("rendering/textures/lossless_compression/webp_compression_level"); + int compression_level = GLOBAL_GET("rendering/textures/lossless_compression/webp_compression_level"); compression_level = CLAMP(compression_level, 0, 9); Ref<Image> img = p_image->duplicate(); @@ -139,7 +139,7 @@ Ref<Image> _webp_unpack(const Vector<uint8_t> &p_buffer) { ERR_FAIL_COND_V(r[0] != 'R' || r[1] != 'I' || r[2] != 'F' || r[3] != 'F' || r[8] != 'W' || r[9] != 'E' || r[10] != 'B' || r[11] != 'P', Ref<Image>()); WebPBitstreamFeatures features; if (WebPGetFeatures(r, size, &features) != VP8_STATUS_OK) { - ERR_FAIL_V_MSG(Ref<Image>(), "Error unpacking WEBP image."); + ERR_FAIL_V_MSG(Ref<Image>(), "Error unpacking WebP image."); } Vector<uint8_t> dst_image; @@ -183,7 +183,7 @@ Error webp_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p ERR_FAIL_COND_V_MSG(errdec, ERR_FILE_CORRUPT, "Failed decoding WebP image."); - p_image->create(features.width, features.height, false, features.has_alpha ? Image::FORMAT_RGBA8 : Image::FORMAT_RGB8, dst_image); + p_image->set_data(features.width, features.height, false, features.has_alpha ? Image::FORMAT_RGBA8 : Image::FORMAT_RGB8, dst_image); return OK; } diff --git a/modules/webrtc/doc_classes/WebRTCMultiplayerPeer.xml b/modules/webrtc/doc_classes/WebRTCMultiplayerPeer.xml index 927888fe21..5266a36637 100644 --- a/modules/webrtc/doc_classes/WebRTCMultiplayerPeer.xml +++ b/modules/webrtc/doc_classes/WebRTCMultiplayerPeer.xml @@ -6,7 +6,7 @@ <description> This class constructs a full mesh of [WebRTCPeerConnection] (one connection for each peer) that can be used as a [member MultiplayerAPI.multiplayer_peer]. You can add each [WebRTCPeerConnection] via [method add_peer] or remove them via [method remove_peer]. Peers must be added in [constant WebRTCPeerConnection.STATE_NEW] state to allow it to create the appropriate channels. This class will not create offers nor set descriptions, it will only poll them, and notify connections and disconnections. - [signal MultiplayerPeer.connection_succeeded] and [signal MultiplayerPeer.server_disconnected] will not be emitted unless [code]server_compatibility[/code] is [code]true[/code] in [method initialize]. Beside that data transfer works like in a [MultiplayerPeer]. + When creating the peer via [method create_client] or [method create_server] the [method MultiplayerPeer.is_server_relay_supported] method will return [code]true[/code] enabling peer exchange and packet relaying when supported by the [MultiplayerAPI] implementation. [b]Note:[/b] When exporting to Android, make sure to enable the [code]INTERNET[/code] permission in the Android export preset before exporting the project or using one-click deploy. Otherwise, network communication of any kind will be blocked by Android. </description> <tutorials> @@ -22,10 +22,29 @@ Three channels will be created for reliable, unreliable, and ordered transport. The value of [code]unreliable_lifetime[/code] will be passed to the [code]maxPacketLifetime[/code] option when creating unreliable and ordered channels (see [method WebRTCPeerConnection.create_data_channel]). </description> </method> - <method name="close"> - <return type="void" /> + <method name="create_client"> + <return type="int" enum="Error" /> + <param index="0" name="peer_id" type="int" /> + <param index="1" name="channels_config" type="Array" default="[]" /> + <description> + Initialize the multiplayer peer as a client with the given [code]peer_id[/code] (must be between 2 and 2147483647). In this mode, you should only call [method add_peer] once and with [code]peer_id[/code] of [code]1[/code]. This mode enables [method MultiplayerPeer.is_server_relay_supported], allowing the upper [MultiplayerAPI] layer to perform peer exchange and packet relaying. + You can optionally specify a [code]channels_config[/code] array of [enum MultiplayerPeer.TransferMode] which will be used to create extra channels (WebRTC only supports one transfer mode per channel). + </description> + </method> + <method name="create_mesh"> + <return type="int" enum="Error" /> + <param index="0" name="peer_id" type="int" /> + <param index="1" name="channels_config" type="Array" default="[]" /> + <description> + Initialize the multiplayer peer as a mesh (i.e. all peers connect to each other) with the given [code]peer_id[/code] (must be between 1 and 2147483647). + </description> + </method> + <method name="create_server"> + <return type="int" enum="Error" /> + <param index="0" name="channels_config" type="Array" default="[]" /> <description> - Close all the add peer connections and channels, freeing all resources. + Initialize the multiplayer peer as a server (with unique ID of [code]1[/code]). This mode enables [method MultiplayerPeer.is_server_relay_supported], allowing the upper [MultiplayerAPI] layer to perform peer exchange and packet relaying. + You can optionally specify a [code]channels_config[/code] array of [enum MultiplayerPeer.TransferMode] which will be used to create extra channels (WebRTC only supports one transfer mode per channel). </description> </method> <method name="get_peer"> @@ -48,18 +67,6 @@ Returns [code]true[/code] if the given [code]peer_id[/code] is in the peers map (it might not be connected though). </description> </method> - <method name="initialize"> - <return type="int" enum="Error" /> - <param index="0" name="peer_id" type="int" /> - <param index="1" name="server_compatibility" type="bool" default="false" /> - <param index="2" name="channels_config" type="Array" default="[]" /> - <description> - Initialize the multiplayer peer with the given [code]peer_id[/code] (must be between 1 and 2147483647). - If [code]server_compatibilty[/code] is [code]false[/code] (default), the multiplayer peer will be immediately in state [constant MultiplayerPeer.CONNECTION_CONNECTED] and [signal MultiplayerPeer.connection_succeeded] will not be emitted. - If [code]server_compatibilty[/code] is [code]true[/code] the peer will suppress all [signal MultiplayerPeer.peer_connected] signals until a peer with id [constant MultiplayerPeer.TARGET_PEER_SERVER] connects and then emit [signal MultiplayerPeer.connection_succeeded]. After that the signal [signal MultiplayerPeer.peer_connected] will be emitted for every already connected peer, and any new peer that might connect. If the server peer disconnects after that, signal [signal MultiplayerPeer.server_disconnected] will be emitted and state will become [constant MultiplayerPeer.CONNECTION_CONNECTED]. - You can optionally specify a [code]channels_config[/code] array of [enum MultiplayerPeer.TransferMode] which will be used to create extra channels (WebRTC only supports one transfer mode per channel). - </description> - </method> <method name="remove_peer"> <return type="void" /> <param index="0" name="peer_id" type="int" /> diff --git a/modules/webrtc/doc_classes/WebRTCPeerConnection.xml b/modules/webrtc/doc_classes/WebRTCPeerConnection.xml index e99aeb4f51..4ecc71ddbb 100644 --- a/modules/webrtc/doc_classes/WebRTCPeerConnection.xml +++ b/modules/webrtc/doc_classes/WebRTCPeerConnection.xml @@ -67,6 +67,18 @@ Returns the connection state. See [enum ConnectionState]. </description> </method> + <method name="get_gathering_state" qualifiers="const"> + <return type="int" enum="WebRTCPeerConnection.GatheringState" /> + <description> + Returns the ICE [enum GatheringState] of the connection. This lets you detect, for example, when collection of ICE candidates has finished. + </description> + </method> + <method name="get_signaling_state" qualifiers="const"> + <return type="int" enum="WebRTCPeerConnection.SignalingState" /> + <description> + Returns the [enum SignalingState] on the local end of the connection while connecting or reconnecting to another peer. + </description> + </method> <method name="initialize"> <return type="int" enum="Error" /> <param index="0" name="configuration" type="Dictionary" default="{}" /> @@ -165,5 +177,32 @@ <constant name="STATE_CLOSED" value="5" enum="ConnectionState"> The peer connection is closed (after calling [method close] for example). </constant> + <constant name="GATHERING_STATE_NEW" value="0" enum="GatheringState"> + The peer connection was just created and hasn't done any networking yet. + </constant> + <constant name="GATHERING_STATE_GATHERING" value="1" enum="GatheringState"> + The ICE agent is in the process of gathering candidates for the connection. + </constant> + <constant name="GATHERING_STATE_COMPLETE" value="2" enum="GatheringState"> + The ICE agent has finished gathering candidates. If something happens that requires collecting new candidates, such as a new interface being added or the addition of a new ICE server, the state will revert to gathering to gather those candidates. + </constant> + <constant name="SIGNALING_STATE_STABLE" value="0" enum="SignalingState"> + There is no ongoing exchange of offer and answer underway. This may mean that the [WebRTCPeerConnection] is new ([constant STATE_NEW]) or that negotiation is complete and a connection has been established ([constant STATE_CONNECTED]). + </constant> + <constant name="SIGNALING_STATE_HAVE_LOCAL_OFFER" value="1" enum="SignalingState"> + The local peer has called [method set_local_description], passing in SDP representing an offer (usually created by calling [method create_offer]), and the offer has been applied successfully. + </constant> + <constant name="SIGNALING_STATE_HAVE_REMOTE_OFFER" value="2" enum="SignalingState"> + The remote peer has created an offer and used the signaling server to deliver it to the local peer, which has set the offer as the remote description by calling [method set_remote_description]. + </constant> + <constant name="SIGNALING_STATE_HAVE_LOCAL_PRANSWER" value="3" enum="SignalingState"> + The offer sent by the remote peer has been applied and an answer has been created and applied by calling [method set_local_description]. This provisional answer describes the supported media formats and so forth, but may not have a complete set of ICE candidates included. Further candidates will be delivered separately later. + </constant> + <constant name="SIGNALING_STATE_HAVE_REMOTE_PRANSWER" value="4" enum="SignalingState"> + A provisional answer has been received and successfully applied in response to an offer previously sent and established by calling [method set_local_description]. + </constant> + <constant name="SIGNALING_STATE_CLOSED" value="5" enum="SignalingState"> + The [WebRTCPeerConnection] has been closed. + </constant> </constants> </class> diff --git a/modules/webrtc/doc_classes/WebRTCPeerConnectionExtension.xml b/modules/webrtc/doc_classes/WebRTCPeerConnectionExtension.xml index 3c4bf18a76..474d2f6a89 100644 --- a/modules/webrtc/doc_classes/WebRTCPeerConnectionExtension.xml +++ b/modules/webrtc/doc_classes/WebRTCPeerConnectionExtension.xml @@ -37,6 +37,16 @@ <description> </description> </method> + <method name="_get_gathering_state" qualifiers="virtual const"> + <return type="int" enum="WebRTCPeerConnection.GatheringState" /> + <description> + </description> + </method> + <method name="_get_signaling_state" qualifiers="virtual const"> + <return type="int" enum="WebRTCPeerConnection.SignalingState" /> + <description> + </description> + </method> <method name="_initialize" qualifiers="virtual"> <return type="int" enum="Error" /> <param index="0" name="p_config" type="Dictionary" /> diff --git a/modules/webrtc/library_godot_webrtc.js b/modules/webrtc/library_godot_webrtc.js index e57e4299e0..e6604eecd7 100644 --- a/modules/webrtc/library_godot_webrtc.js +++ b/modules/webrtc/library_godot_webrtc.js @@ -220,64 +220,123 @@ mergeInto(LibraryManager.library, GodotRTCDataChannel); const GodotRTCPeerConnection = { $GodotRTCPeerConnection__deps: ['$IDHandler', '$GodotRuntime', '$GodotRTCDataChannel'], $GodotRTCPeerConnection: { - onstatechange: function (p_id, p_conn, callback, event) { - const ref = IDHandler.get(p_id); - if (!ref) { - return; - } - 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); + // Enums + ConnectionState: { + 'new': 0, + 'connecting': 1, + 'connected': 2, + 'disconnected': 3, + 'failed': 4, + 'closed': 5, }, - onicecandidate: function (p_id, callback, event) { - const ref = IDHandler.get(p_id); - if (!ref || !event.candidate) { - return; + ConnectionStateCompat: { + // Using values from IceConnectionState for browsers that do not support ConnectionState (notably Firefox). + 'new': 0, + 'checking': 1, + 'connected': 2, + 'completed': 2, + 'disconnected': 3, + 'failed': 4, + 'closed': 5, + }, + + IceGatheringState: { + 'new': 0, + 'gathering': 1, + 'complete': 2, + }, + + SignalingState: { + 'stable': 0, + 'have-local-offer': 1, + 'have-remote-offer': 2, + 'have-local-pranswer': 3, + 'have-remote-pranswer': 4, + 'closed': 5, + }, + + // Callbacks + create: function (config, onConnectionChange, onSignalingChange, onIceGatheringChange, onIceCandidate, onDataChannel) { + let conn = null; + try { + conn = new RTCPeerConnection(config); + } catch (e) { + GodotRuntime.error(e); + return 0; } - 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); - GodotRuntime.free(candidate_str); - GodotRuntime.free(mid_str); + const id = IDHandler.add(conn); + + if ('connectionState' in conn && conn['connectionState'] !== undefined) { + // Use "connectionState" if supported + conn.onconnectionstatechange = function (event) { + if (!IDHandler.get(id)) { + return; + } + onConnectionChange(GodotRTCPeerConnection.ConnectionState[conn.connectionState] || 0); + }; + } else { + // Fall back to using "iceConnectionState" when "connectionState" is not supported (notably Firefox). + conn.oniceconnectionstatechange = function (event) { + if (!IDHandler.get(id)) { + return; + } + onConnectionChange(GodotRTCPeerConnection.ConnectionStateCompat[conn.iceConnectionState] || 0); + }; + } + conn.onicegatheringstatechange = function (event) { + if (!IDHandler.get(id)) { + return; + } + onIceGatheringChange(GodotRTCPeerConnection.IceGatheringState[conn.iceGatheringState] || 0); + }; + conn.onsignalingstatechange = function (event) { + if (!IDHandler.get(id)) { + return; + } + onSignalingChange(GodotRTCPeerConnection.SignalingState[conn.signalingState] || 0); + }; + conn.onicecandidate = function (event) { + if (!IDHandler.get(id)) { + return; + } + const c = event.candidate; + if (!c || !c.candidate) { + return; + } + const candidate_str = GodotRuntime.allocString(c.candidate); + const mid_str = GodotRuntime.allocString(c.sdpMid); + onIceCandidate(mid_str, c.sdpMLineIndex, candidate_str); + GodotRuntime.free(candidate_str); + GodotRuntime.free(mid_str); + }; + conn.ondatachannel = function (event) { + if (!IDHandler.get(id)) { + return; + } + const cid = IDHandler.add(event.channel); + onDataChannel(cid); + }; + return id; }, - ondatachannel: function (p_id, callback, event) { - const ref = IDHandler.get(p_id); - if (!ref) { + destroy: function (p_id) { + const conn = IDHandler.get(p_id); + if (!conn) { return; } - - const cid = IDHandler.add(event.channel); - callback(cid); + conn.onconnectionstatechange = null; + conn.oniceconnectionstatechange = null; + conn.onicegatheringstatechange = null; + conn.onsignalingstatechange = null; + conn.onicecandidate = null; + conn.ondatachannel = null; + IDHandler.remove(p_id); }, onsession: function (p_id, callback, session) { - const ref = IDHandler.get(p_id); - if (!ref) { + if (!IDHandler.get(p_id)) { return; } const type_str = GodotRuntime.allocString(session.type); @@ -297,27 +356,19 @@ const GodotRTCPeerConnection = { }, }, - godot_js_rtc_pc_create__sig: 'iiiiii', - 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); - - const config = JSON.parse(GodotRuntime.parseString(p_config)); - let conn = null; - try { - conn = new RTCPeerConnection(config); - } catch (e) { - GodotRuntime.error(e); - return 0; - } - - const base = GodotRTCPeerConnection; - const id = IDHandler.add(conn); - conn.oniceconnectionstatechange = base.onstatechange.bind(null, id, conn, onstatechange); - conn.onicecandidate = base.onicecandidate.bind(null, id, oncandidate); - conn.ondatachannel = base.ondatachannel.bind(null, id, ondatachannel); - return id; + godot_js_rtc_pc_create__sig: 'iiiiiiii', + godot_js_rtc_pc_create: function (p_config, p_ref, p_on_connection_state_change, p_on_ice_gathering_state_change, p_on_signaling_state_change, p_on_ice_candidate, p_on_datachannel) { + const wrap = function (p_func) { + return GodotRuntime.get_func(p_func).bind(null, p_ref); + }; + return GodotRTCPeerConnection.create( + JSON.parse(GodotRuntime.parseString(p_config)), + wrap(p_on_connection_state_change), + wrap(p_on_signaling_state_change), + wrap(p_on_ice_gathering_state_change), + wrap(p_on_ice_candidate), + wrap(p_on_datachannel) + ); }, godot_js_rtc_pc_close__sig: 'vi', @@ -331,14 +382,7 @@ const GodotRTCPeerConnection = { godot_js_rtc_pc_destroy__sig: 'vi', godot_js_rtc_pc_destroy: function (p_id) { - const ref = IDHandler.get(p_id); - if (!ref) { - return; - } - ref.oniceconnectionstatechange = null; - ref.onicecandidate = null; - ref.ondatachannel = null; - IDHandler.remove(p_id); + GodotRTCPeerConnection.destroy(p_id); }, godot_js_rtc_pc_offer_create__sig: 'viiii', diff --git a/modules/webrtc/webrtc_multiplayer_peer.cpp b/modules/webrtc/webrtc_multiplayer_peer.cpp index e03b6b2473..38c33a2dbc 100644 --- a/modules/webrtc/webrtc_multiplayer_peer.cpp +++ b/modules/webrtc/webrtc_multiplayer_peer.cpp @@ -34,13 +34,14 @@ #include "core/os/os.h" void WebRTCMultiplayerPeer::_bind_methods() { - ClassDB::bind_method(D_METHOD("initialize", "peer_id", "server_compatibility", "channels_config"), &WebRTCMultiplayerPeer::initialize, DEFVAL(false), DEFVAL(Array())); + ClassDB::bind_method(D_METHOD("create_server", "channels_config"), &WebRTCMultiplayerPeer::create_server, DEFVAL(Array())); + ClassDB::bind_method(D_METHOD("create_client", "peer_id", "channels_config"), &WebRTCMultiplayerPeer::create_client, DEFVAL(Array())); + ClassDB::bind_method(D_METHOD("create_mesh", "peer_id", "channels_config"), &WebRTCMultiplayerPeer::create_mesh, DEFVAL(Array())); ClassDB::bind_method(D_METHOD("add_peer", "peer", "peer_id", "unreliable_lifetime"), &WebRTCMultiplayerPeer::add_peer, DEFVAL(1)); ClassDB::bind_method(D_METHOD("remove_peer", "peer_id"), &WebRTCMultiplayerPeer::remove_peer); ClassDB::bind_method(D_METHOD("has_peer", "peer_id"), &WebRTCMultiplayerPeer::has_peer); ClassDB::bind_method(D_METHOD("get_peer", "peer_id"), &WebRTCMultiplayerPeer::get_peer); ClassDB::bind_method(D_METHOD("get_peers"), &WebRTCMultiplayerPeer::get_peers); - ClassDB::bind_method(D_METHOD("close"), &WebRTCMultiplayerPeer::close); } void WebRTCMultiplayerPeer::set_target_peer(int p_peer_id) { @@ -52,6 +53,15 @@ int WebRTCMultiplayerPeer::get_packet_peer() const { return next_packet_peer; } +int WebRTCMultiplayerPeer::get_packet_channel() const { + return next_packet_channel < CH_RESERVED_MAX ? 0 : next_packet_channel - CH_RESERVED_MAX + 1; +} + +MultiplayerPeer::TransferMode WebRTCMultiplayerPeer::get_packet_mode() const { + ERR_FAIL_INDEX_V(next_packet_channel, channels_modes.size(), TRANSFER_MODE_RELIABLE); + return channels_modes[next_packet_channel]; +} + bool WebRTCMultiplayerPeer::is_server() const { return unique_id == TARGET_PEER_SERVER; } @@ -113,24 +123,14 @@ void WebRTCMultiplayerPeer::poll() { // Signal newly connected peers for (int &E : add) { // Already connected to server: simply notify new peer. - // NOTE: Mesh is always connected. - if (connection_status == CONNECTION_CONNECTED) { - emit_signal(SNAME("peer_connected"), E); - } - - // Server emulation mode suppresses peer_conencted until server connects. - if (server_compat && E == TARGET_PEER_SERVER) { + if (network_mode == MODE_CLIENT) { + ERR_CONTINUE(E != TARGET_PEER_SERVER); // Bug. // Server connected. connection_status = CONNECTION_CONNECTED; emit_signal(SNAME("peer_connected"), TARGET_PEER_SERVER); emit_signal(SNAME("connection_succeeded")); - // Notify of all previously connected peers - for (const KeyValue<int, Ref<ConnectedPeer>> &F : peer_map) { - if (F.key != 1 && F.value->connected) { - emit_signal(SNAME("peer_connected"), F.key); - } - } - break; // Because we already notified of all newly added peers. + } else { + emit_signal(SNAME("peer_connected"), E); } } // Fetch next packet @@ -150,11 +150,14 @@ void WebRTCMultiplayerPeer::_find_next_peer() { ++E; continue; } + int idx = 0; for (const Ref<WebRTCDataChannel> &F : E->value->channels) { if (F->get_available_packet_count()) { + next_packet_channel = idx; next_packet_peer = E->key; return; } + idx++; } ++E; } @@ -165,11 +168,14 @@ void WebRTCMultiplayerPeer::_find_next_peer() { ++E; continue; } + int idx = 0; for (const Ref<WebRTCDataChannel> &F : E->value->channels) { if (F->get_available_packet_count()) { + next_packet_channel = idx; next_packet_peer = E->key; return; } + idx++; } if (E->key == (int)next_packet_peer) { break; @@ -177,6 +183,7 @@ void WebRTCMultiplayerPeer::_find_next_peer() { ++E; } // No packet found + next_packet_channel = 0; next_packet_peer = 0; } @@ -184,11 +191,28 @@ MultiplayerPeer::ConnectionStatus WebRTCMultiplayerPeer::get_connection_status() return connection_status; } -Error WebRTCMultiplayerPeer::initialize(int p_self_id, bool p_server_compat, Array p_channels_config) { +Error WebRTCMultiplayerPeer::create_server(Array p_channels_config) { + return _initialize(1, MODE_SERVER, p_channels_config); +} + +Error WebRTCMultiplayerPeer::create_client(int p_self_id, Array p_channels_config) { + ERR_FAIL_COND_V_MSG(p_self_id == 1, ERR_INVALID_PARAMETER, "Clients cannot have ID 1."); + return _initialize(p_self_id, MODE_CLIENT, p_channels_config); +} + +Error WebRTCMultiplayerPeer::create_mesh(int p_self_id, Array p_channels_config) { + return _initialize(p_self_id, MODE_MESH, p_channels_config); +} + +Error WebRTCMultiplayerPeer::_initialize(int p_self_id, NetworkMode p_mode, Array p_channels_config) { ERR_FAIL_COND_V(p_self_id < 1 || p_self_id > ~(1 << 31), ERR_INVALID_PARAMETER); channels_config.clear(); + channels_modes.clear(); + channels_modes.push_back(TRANSFER_MODE_RELIABLE); + channels_modes.push_back(TRANSFER_MODE_UNRELIABLE_ORDERED); + channels_modes.push_back(TRANSFER_MODE_UNRELIABLE); for (int i = 0; i < p_channels_config.size(); i++) { - ERR_FAIL_COND_V_MSG(p_channels_config[i].get_type() != Variant::INT, ERR_INVALID_PARAMETER, "The 'channels_config' array must contain only enum values from 'MultiplayerPeer.Multiplayer::TransferMode'"); + ERR_FAIL_COND_V_MSG(p_channels_config[i].get_type() != Variant::INT, ERR_INVALID_PARAMETER, "The 'channels_config' array must contain only enum values from 'MultiplayerPeer.TransferMode'"); int mode = p_channels_config[i].operator int(); // Initialize data channel configurations. Dictionary cfg; @@ -207,16 +231,17 @@ Error WebRTCMultiplayerPeer::initialize(int p_self_id, bool p_server_compat, Arr case TRANSFER_MODE_RELIABLE: break; default: - ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, vformat("The 'channels_config' array must contain only enum values from 'MultiplayerPeer.Multiplayer::TransferMode'. Got: %d", mode)); + ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, vformat("The 'channels_config' array must contain only enum values from 'MultiplayerPeer.TransferMode'. Got: %d", mode)); } channels_config.push_back(cfg); + channels_modes.push_back((TransferMode)mode); } unique_id = p_self_id; - server_compat = p_server_compat; + network_mode = p_mode; // Mesh and server are always connected - if (!server_compat || p_self_id == 1) { + if (p_mode != MODE_CLIENT) { connection_status = CONNECTION_CONNECTED; } else { connection_status = CONNECTION_CONNECTING; @@ -224,6 +249,10 @@ Error WebRTCMultiplayerPeer::initialize(int p_self_id, bool p_server_compat, Arr return OK; } +bool WebRTCMultiplayerPeer::is_server_relay_supported() const { + return network_mode == MODE_SERVER || network_mode == MODE_CLIENT; +} + int WebRTCMultiplayerPeer::get_unique_id() const { ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, 1); return unique_id; @@ -261,7 +290,10 @@ Dictionary WebRTCMultiplayerPeer::get_peers() { } Error WebRTCMultiplayerPeer::add_peer(Ref<WebRTCPeerConnection> p_peer, int p_peer_id, int p_unreliable_lifetime) { - ERR_FAIL_COND_V(p_peer_id < 0 || p_peer_id > ~(1 << 31), ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(network_mode == MODE_NONE, ERR_UNCONFIGURED); + ERR_FAIL_COND_V(network_mode == MODE_CLIENT && p_peer_id != 1, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(network_mode == MODE_SERVER && p_peer_id == 1, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_peer_id < 1 || p_peer_id > ~(1 << 31), ERR_INVALID_PARAMETER); ERR_FAIL_COND_V(p_unreliable_lifetime < 0, ERR_INVALID_PARAMETER); ERR_FAIL_COND_V(is_refusing_new_connections(), ERR_UNAUTHORIZED); // Peer must be valid, and in new state (to create data channels) @@ -308,10 +340,21 @@ void WebRTCMultiplayerPeer::remove_peer(int p_peer_id) { if (peer->connected) { peer->connected = false; emit_signal(SNAME("peer_disconnected"), p_peer_id); - if (server_compat && p_peer_id == TARGET_PEER_SERVER) { - emit_signal(SNAME("server_disconnected")); + if (network_mode == MODE_CLIENT && p_peer_id == TARGET_PEER_SERVER) { + connection_status = CONNECTION_DISCONNECTED; + } + } +} + +void WebRTCMultiplayerPeer::disconnect_peer(int p_peer_id, bool p_force) { + ERR_FAIL_COND(!peer_map.has(p_peer_id)); + if (p_force) { + peer_map.erase(p_peer_id); + if (network_mode == MODE_CLIENT && p_peer_id == TARGET_PEER_SERVER) { connection_status = CONNECTION_DISCONNECTED; } + } else { + peer_map[p_peer_id]->connection->close(); // Will be removed during next poll. } } @@ -403,7 +446,9 @@ void WebRTCMultiplayerPeer::close() { channels_config.clear(); unique_id = 0; next_packet_peer = 0; + next_packet_channel = 0; target_peer = 0; + network_mode = MODE_NONE; connection_status = CONNECTION_DISCONNECTED; } diff --git a/modules/webrtc/webrtc_multiplayer_peer.h b/modules/webrtc/webrtc_multiplayer_peer.h index ea7c60036b..0556ef029c 100644 --- a/modules/webrtc/webrtc_multiplayer_peer.h +++ b/modules/webrtc/webrtc_multiplayer_peer.h @@ -48,6 +48,13 @@ private: CH_RESERVED_MAX = 3 }; + enum NetworkMode { + MODE_NONE, + MODE_SERVER, + MODE_CLIENT, + MODE_MESH, + }; + class ConnectedPeer : public RefCounted { public: Ref<WebRTCPeerConnection> connection; @@ -67,43 +74,53 @@ private: int client_count = 0; ConnectionStatus connection_status = CONNECTION_DISCONNECTED; int next_packet_peer = 0; - bool server_compat = false; + int next_packet_channel = 0; + NetworkMode network_mode = MODE_NONE; HashMap<int, Ref<ConnectedPeer>> peer_map; + List<TransferMode> channels_modes; List<Dictionary> channels_config; void _peer_to_dict(Ref<ConnectedPeer> p_connected_peer, Dictionary &r_dict); void _find_next_peer(); + Ref<ConnectedPeer> _get_next_peer(); + Error _initialize(int p_self_id, NetworkMode p_mode, Array p_channels_config = Array()); public: WebRTCMultiplayerPeer() {} ~WebRTCMultiplayerPeer(); - Error initialize(int p_self_id, bool p_server_compat = false, Array p_channels_config = Array()); + Error create_server(Array p_channels_config = Array()); + Error create_client(int p_self_id, Array p_channels_config = Array()); + Error create_mesh(int p_self_id, Array p_channels_config = Array()); Error add_peer(Ref<WebRTCPeerConnection> p_peer, int p_peer_id, int p_unreliable_lifetime = 1); void remove_peer(int p_peer_id); bool has_peer(int p_peer_id); Dictionary get_peer(int p_peer_id); Dictionary get_peers(); - void close(); // PacketPeer - Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) override; ///< buffer is GONE after next get_packet - Error put_packet(const uint8_t *p_buffer, int p_buffer_size) override; - int get_available_packet_count() const override; - int get_max_packet_size() const override; + virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) override; ///< buffer is GONE after next get_packet + virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) override; + virtual int get_available_packet_count() const override; + virtual int get_max_packet_size() const override; // MultiplayerPeer - void set_target_peer(int p_peer_id) override; + virtual void set_target_peer(int p_peer_id) override; - int get_unique_id() const override; - int get_packet_peer() const override; + virtual int get_unique_id() const override; + virtual int get_packet_peer() const override; + virtual int get_packet_channel() const override; + virtual TransferMode get_packet_mode() const override; - bool is_server() const override; + virtual bool is_server() const override; + virtual bool is_server_relay_supported() const override; - void poll() override; + virtual void poll() override; + virtual void close() override; + virtual void disconnect_peer(int p_peer_id, bool p_force = false) override; - ConnectionStatus get_connection_status() const override; + virtual ConnectionStatus get_connection_status() const override; }; #endif // WEBRTC_MULTIPLAYER_PEER_H diff --git a/modules/webrtc/webrtc_peer_connection.cpp b/modules/webrtc/webrtc_peer_connection.cpp index d885b9262b..5aa891d35c 100644 --- a/modules/webrtc/webrtc_peer_connection.cpp +++ b/modules/webrtc/webrtc_peer_connection.cpp @@ -69,6 +69,8 @@ void WebRTCPeerConnection::_bind_methods() { ClassDB::bind_method(D_METHOD("close"), &WebRTCPeerConnection::close); ClassDB::bind_method(D_METHOD("get_connection_state"), &WebRTCPeerConnection::get_connection_state); + ClassDB::bind_method(D_METHOD("get_gathering_state"), &WebRTCPeerConnection::get_gathering_state); + ClassDB::bind_method(D_METHOD("get_signaling_state"), &WebRTCPeerConnection::get_signaling_state); ADD_SIGNAL(MethodInfo("session_description_created", PropertyInfo(Variant::STRING, "type"), PropertyInfo(Variant::STRING, "sdp"))); ADD_SIGNAL(MethodInfo("ice_candidate_created", PropertyInfo(Variant::STRING, "media"), PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::STRING, "name"))); @@ -80,6 +82,17 @@ void WebRTCPeerConnection::_bind_methods() { BIND_ENUM_CONSTANT(STATE_DISCONNECTED); BIND_ENUM_CONSTANT(STATE_FAILED); BIND_ENUM_CONSTANT(STATE_CLOSED); + + BIND_ENUM_CONSTANT(GATHERING_STATE_NEW); + BIND_ENUM_CONSTANT(GATHERING_STATE_GATHERING); + BIND_ENUM_CONSTANT(GATHERING_STATE_COMPLETE); + + BIND_ENUM_CONSTANT(SIGNALING_STATE_STABLE); + BIND_ENUM_CONSTANT(SIGNALING_STATE_HAVE_LOCAL_OFFER); + BIND_ENUM_CONSTANT(SIGNALING_STATE_HAVE_REMOTE_OFFER); + BIND_ENUM_CONSTANT(SIGNALING_STATE_HAVE_LOCAL_PRANSWER); + BIND_ENUM_CONSTANT(SIGNALING_STATE_HAVE_REMOTE_PRANSWER); + BIND_ENUM_CONSTANT(SIGNALING_STATE_CLOSED); } WebRTCPeerConnection::WebRTCPeerConnection() { diff --git a/modules/webrtc/webrtc_peer_connection.h b/modules/webrtc/webrtc_peer_connection.h index 122ea3d00f..76f29f9d68 100644 --- a/modules/webrtc/webrtc_peer_connection.h +++ b/modules/webrtc/webrtc_peer_connection.h @@ -47,6 +47,21 @@ public: STATE_CLOSED }; + enum GatheringState { + GATHERING_STATE_NEW, + GATHERING_STATE_GATHERING, + GATHERING_STATE_COMPLETE, + }; + + enum SignalingState { + SIGNALING_STATE_STABLE, + SIGNALING_STATE_HAVE_LOCAL_OFFER, + SIGNALING_STATE_HAVE_REMOTE_OFFER, + SIGNALING_STATE_HAVE_LOCAL_PRANSWER, + SIGNALING_STATE_HAVE_REMOTE_PRANSWER, + SIGNALING_STATE_CLOSED, + }; + private: static StringName default_extension; @@ -57,6 +72,8 @@ public: static void set_default_extension(const StringName &p_name); virtual ConnectionState get_connection_state() const = 0; + virtual GatheringState get_gathering_state() const = 0; + virtual SignalingState get_signaling_state() const = 0; virtual Error initialize(Dictionary p_config = Dictionary()) = 0; virtual Ref<WebRTCDataChannel> create_data_channel(String p_label, Dictionary p_options = Dictionary()) = 0; @@ -74,5 +91,7 @@ public: }; VARIANT_ENUM_CAST(WebRTCPeerConnection::ConnectionState); +VARIANT_ENUM_CAST(WebRTCPeerConnection::GatheringState); +VARIANT_ENUM_CAST(WebRTCPeerConnection::SignalingState); #endif // WEBRTC_PEER_CONNECTION_H diff --git a/modules/webrtc/webrtc_peer_connection_extension.cpp b/modules/webrtc/webrtc_peer_connection_extension.cpp index 54143e4b79..592a1f8a97 100644 --- a/modules/webrtc/webrtc_peer_connection_extension.cpp +++ b/modules/webrtc/webrtc_peer_connection_extension.cpp @@ -32,6 +32,8 @@ void WebRTCPeerConnectionExtension::_bind_methods() { GDVIRTUAL_BIND(_get_connection_state); + GDVIRTUAL_BIND(_get_gathering_state); + GDVIRTUAL_BIND(_get_signaling_state); GDVIRTUAL_BIND(_initialize, "p_config"); GDVIRTUAL_BIND(_create_data_channel, "p_label", "p_config"); GDVIRTUAL_BIND(_create_offer); diff --git a/modules/webrtc/webrtc_peer_connection_extension.h b/modules/webrtc/webrtc_peer_connection_extension.h index 0c324ca45f..085069debb 100644 --- a/modules/webrtc/webrtc_peer_connection_extension.h +++ b/modules/webrtc/webrtc_peer_connection_extension.h @@ -53,6 +53,8 @@ public: /** GDExtension **/ EXBIND0RC(ConnectionState, get_connection_state); + EXBIND0RC(GatheringState, get_gathering_state); + EXBIND0RC(SignalingState, get_signaling_state); EXBIND1R(Error, initialize, Dictionary); EXBIND0R(Error, create_offer); EXBIND2R(Error, set_remote_description, String, String); diff --git a/modules/webrtc/webrtc_peer_connection_js.cpp b/modules/webrtc/webrtc_peer_connection_js.cpp index f48705253b..a371312ae9 100644 --- a/modules/webrtc/webrtc_peer_connection_js.cpp +++ b/modules/webrtc/webrtc_peer_connection_js.cpp @@ -51,6 +51,16 @@ void WebRTCPeerConnectionJS::_on_connection_state_changed(void *p_obj, int p_sta peer->_conn_state = (ConnectionState)p_state; } +void WebRTCPeerConnectionJS::_on_gathering_state_changed(void *p_obj, int p_state) { + WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(p_obj); + peer->_gathering_state = (GatheringState)p_state; +} + +void WebRTCPeerConnectionJS::_on_signaling_state_changed(void *p_obj, int p_state) { + WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(p_obj); + peer->_signaling_state = (SignalingState)p_state; +} + void WebRTCPeerConnectionJS::_on_error(void *p_obj) { ERR_PRINT("RTCPeerConnection error!"); } @@ -100,7 +110,7 @@ Error WebRTCPeerConnectionJS::initialize(Dictionary p_config) { _conn_state = STATE_NEW; String config = Variant(p_config).to_json_string(); - _js_id = godot_js_rtc_pc_create(config.utf8().get_data(), this, &_on_connection_state_changed, &_on_ice_candidate, &_on_data_channel); + _js_id = godot_js_rtc_pc_create(config.utf8().get_data(), this, &_on_connection_state_changed, &_on_gathering_state_changed, &_on_signaling_state_changed, &_on_ice_candidate, &_on_data_channel); return _js_id ? OK : FAILED; } @@ -117,14 +127,19 @@ Error WebRTCPeerConnectionJS::poll() { return OK; } +WebRTCPeerConnection::GatheringState WebRTCPeerConnectionJS::get_gathering_state() const { + return _gathering_state; +} + +WebRTCPeerConnection::SignalingState WebRTCPeerConnectionJS::get_signaling_state() const { + return _signaling_state; +} + WebRTCPeerConnection::ConnectionState WebRTCPeerConnectionJS::get_connection_state() const { return _conn_state; } WebRTCPeerConnectionJS::WebRTCPeerConnectionJS() { - _conn_state = STATE_NEW; - _js_id = 0; - Dictionary config; initialize(config); } diff --git a/modules/webrtc/webrtc_peer_connection_js.h b/modules/webrtc/webrtc_peer_connection_js.h index 50266129e4..e62ad6af28 100644 --- a/modules/webrtc/webrtc_peer_connection_js.h +++ b/modules/webrtc/webrtc_peer_connection_js.h @@ -37,11 +37,13 @@ extern "C" { typedef void (*RTCOnIceConnectionStateChange)(void *p_obj, int p_state); +typedef void (*RTCOnIceGatheringStateChange)(void *p_obj, int p_state); +typedef void (*RTCOnSignalingStateChange)(void *p_obj, int p_state); typedef void (*RTCOnIceCandidate)(void *p_obj, const char *p_mid, int p_mline_idx, const char *p_candidate); typedef void (*RTCOnDataChannel)(void *p_obj, int p_id); typedef void (*RTCOnSession)(void *p_obj, const char *p_type, const char *p_sdp); typedef void (*RTCOnError)(void *p_obj); -extern int godot_js_rtc_pc_create(const char *p_config, void *p_obj, RTCOnIceConnectionStateChange p_on_state_change, RTCOnIceCandidate p_on_candidate, RTCOnDataChannel p_on_datachannel); +extern int godot_js_rtc_pc_create(const char *p_config, void *p_obj, RTCOnIceConnectionStateChange p_on_connection_state_change, RTCOnIceGatheringStateChange p_on_gathering_state_change, RTCOnSignalingStateChange p_on_signaling_state_change, RTCOnIceCandidate p_on_candidate, RTCOnDataChannel p_on_datachannel); extern void godot_js_rtc_pc_close(int p_id); extern void godot_js_rtc_pc_destroy(int p_id); extern void godot_js_rtc_pc_offer_create(int p_id, void *p_obj, RTCOnSession p_on_session, RTCOnError p_on_error); @@ -55,10 +57,14 @@ class WebRTCPeerConnectionJS : public WebRTCPeerConnection { GDCLASS(WebRTCPeerConnectionJS, WebRTCPeerConnection); private: - int _js_id; - ConnectionState _conn_state; + int _js_id = 0; + ConnectionState _conn_state = STATE_NEW; + GatheringState _gathering_state = GATHERING_STATE_NEW; + SignalingState _signaling_state = SIGNALING_STATE_STABLE; static void _on_connection_state_changed(void *p_obj, int p_state); + static void _on_gathering_state_changed(void *p_obj, int p_state); + static void _on_signaling_state_changed(void *p_obj, int p_state); static void _on_ice_candidate(void *p_obj, const char *p_mid_name, int p_mline_idx, const char *p_candidate); static void _on_data_channel(void *p_obj, int p_channel); static void _on_session_created(void *p_obj, const char *p_type, const char *p_session); @@ -66,6 +72,8 @@ private: public: virtual ConnectionState get_connection_state() const override; + virtual GatheringState get_gathering_state() const override; + virtual SignalingState get_signaling_state() const override; virtual Error initialize(Dictionary configuration = Dictionary()) override; virtual Ref<WebRTCDataChannel> create_data_channel(String p_channel_name, Dictionary p_channel_config = Dictionary()) override; diff --git a/modules/websocket/SCsub b/modules/websocket/SCsub index 890fb71592..3f834471e5 100644 --- a/modules/websocket/SCsub +++ b/modules/websocket/SCsub @@ -41,7 +41,7 @@ elif env["builtin_wslay"]: module_obj = [] env_ws.add_source_files(module_obj, "*.cpp") -if env["tools"]: +if env.editor_build: env_ws.add_source_files(module_obj, "editor/*.cpp") env.modules_sources += module_obj diff --git a/modules/websocket/doc_classes/WebSocketClient.xml b/modules/websocket/doc_classes/WebSocketClient.xml deleted file mode 100644 index 1978d2e7c6..0000000000 --- a/modules/websocket/doc_classes/WebSocketClient.xml +++ /dev/null @@ -1,94 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" ?> -<class name="WebSocketClient" inherits="WebSocketMultiplayerPeer" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> - <brief_description> - A WebSocket client implementation. - </brief_description> - <description> - This class implements a WebSocket client compatible with any RFC 6455-compliant WebSocket server. - This client can be optionally used as a multiplayer peer for the [MultiplayerAPI]. - After starting the client ([method connect_to_url]), you will need to [method MultiplayerPeer.poll] it at regular intervals (e.g. inside [method Node._process]). - You will receive appropriate signals when connecting, disconnecting, or when new data is available. - [b]Note:[/b] When exporting to Android, make sure to enable the [code]INTERNET[/code] permission in the Android export preset before exporting the project or using one-click deploy. Otherwise, network communication of any kind will be blocked by Android. - </description> - <tutorials> - </tutorials> - <methods> - <method name="connect_to_url"> - <return type="int" enum="Error" /> - <param index="0" name="url" type="String" /> - <param index="1" name="protocols" type="PackedStringArray" default="PackedStringArray()" /> - <param index="2" name="gd_mp_api" type="bool" default="false" /> - <param index="3" name="custom_headers" type="PackedStringArray" default="PackedStringArray()" /> - <description> - Connects to the given URL requesting one of the given [code]protocols[/code] as sub-protocol. If the list empty (default), no sub-protocol will be requested. - If [code]true[/code] is passed as [code]gd_mp_api[/code], the client will behave like a multiplayer peer for the [MultiplayerAPI], connections to non-Godot servers will not work, and [signal data_received] will not be emitted. - If [code]false[/code] is passed instead (default), you must call [PacketPeer] functions ([code]put_packet[/code], [code]get_packet[/code], etc.) on the [WebSocketPeer] returned via [code]get_peer(1)[/code] and not on this object directly (e.g. [code]get_peer(1).put_packet(data)[/code]). - You can optionally pass a list of [code]custom_headers[/code] to be added to the handshake HTTP request. - [b]Note:[/b] To avoid mixed content warnings or errors in Web, you may have to use a [code]url[/code] that starts with [code]wss://[/code] (secure) instead of [code]ws://[/code]. When doing so, make sure to use the fully qualified domain name that matches the one defined in the server's TLS certificate. Do not connect directly via the IP address for [code]wss://[/code] connections, as it won't match with the TLS certificate. - [b]Note:[/b] Specifying [code]custom_headers[/code] is not supported in Web exports due to browsers' restrictions. - </description> - </method> - <method name="disconnect_from_host"> - <return type="void" /> - <param index="0" name="code" type="int" default="1000" /> - <param index="1" name="reason" type="String" default="""" /> - <description> - Disconnects this client from the connected host. See [method WebSocketPeer.close] for more information. - </description> - </method> - <method name="get_connected_host" qualifiers="const"> - <return type="String" /> - <description> - Returns the IP address of the currently connected host. - </description> - </method> - <method name="get_connected_port" qualifiers="const"> - <return type="int" /> - <description> - Returns the IP port of the currently connected host. - </description> - </method> - </methods> - <members> - <member name="trusted_tls_certificate" type="X509Certificate" setter="set_trusted_tls_certificate" getter="get_trusted_tls_certificate"> - If specified, this [X509Certificate] will be the only one accepted when connecting to an TLS host. Any other certificate provided by the server will be regarded as invalid. - [b]Note:[/b] Specifying a custom [code]trusted_tls_certificate[/code] is not supported in Web exports due to browsers' restrictions. - </member> - <member name="verify_tls" type="bool" setter="set_verify_tls_enabled" getter="is_verify_tls_enabled"> - If [code]true[/code], TLS certificate verification is enabled. - [b]Note:[/b] You must specify the certificates to be used in the Project Settings for it to work when exported. - </member> - </members> - <signals> - <signal name="connection_closed"> - <param index="0" name="was_clean_close" type="bool" /> - <description> - Emitted when the connection to the server is closed. [code]was_clean_close[/code] will be [code]true[/code] if the connection was shutdown cleanly. - </description> - </signal> - <signal name="connection_error"> - <description> - Emitted when the connection to the server fails. - </description> - </signal> - <signal name="connection_established"> - <param index="0" name="protocol" type="String" /> - <description> - Emitted when a connection with the server is established, [code]protocol[/code] will contain the sub-protocol agreed with the server. - </description> - </signal> - <signal name="data_received"> - <description> - Emitted when a WebSocket message is received. - [b]Note:[/b] This signal is [i]not[/i] emitted when used as high-level multiplayer peer. - </description> - </signal> - <signal name="server_close_request"> - <param index="0" name="code" type="int" /> - <param index="1" name="reason" type="String" /> - <description> - Emitted when the server requests a clean close. You should keep polling until you get a [signal connection_closed] signal to achieve the clean close. See [method WebSocketPeer.close] for more details. - </description> - </signal> - </signals> -</class> diff --git a/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml b/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml index 4cc4d515e7..7e896a0ca3 100644 --- a/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml +++ b/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml @@ -10,6 +10,26 @@ <tutorials> </tutorials> <methods> + <method name="create_client"> + <return type="int" enum="Error" /> + <param index="0" name="url" type="String" /> + <param index="1" name="verify_tls" type="bool" default="true" /> + <param index="2" name="tls_certificate" type="X509Certificate" default="null" /> + <description> + Starts a new multiplayer client connecting to the given [param url]. If [param verify_tls] is [code]false[/code] certificate validation will be disabled. If specified, the [param tls_certificate] will be used to verify the TLS host. + [b]Note[/b]: It is recommended to specify the scheme part of the URL, i.e. the [param url] should start with either [code]ws://[/code] or [code]wss://[/code]. + </description> + </method> + <method name="create_server"> + <return type="int" enum="Error" /> + <param index="0" name="port" type="int" /> + <param index="1" name="bind_address" type="String" default=""*"" /> + <param index="2" name="tls_key" type="CryptoKey" default="null" /> + <param index="3" name="tls_certificate" type="X509Certificate" default="null" /> + <description> + Starts a new multiplayer server listening on the given [param port]. You can optionally specify a [param bind_address], and provide a [param tls_key] and [param tls_certificate] to use TLS. + </description> + </method> <method name="get_peer" qualifiers="const"> <return type="WebSocketPeer" /> <param index="0" name="peer_id" type="int" /> @@ -17,27 +37,39 @@ Returns the [WebSocketPeer] associated to the given [code]peer_id[/code]. </description> </method> - <method name="set_buffers"> - <return type="int" enum="Error" /> - <param index="0" name="input_buffer_size_kb" type="int" /> - <param index="1" name="input_max_packets" type="int" /> - <param index="2" name="output_buffer_size_kb" type="int" /> - <param index="3" name="output_max_packets" type="int" /> + <method name="get_peer_address" qualifiers="const"> + <return type="String" /> + <param index="0" name="id" type="int" /> <description> - Configures the buffer sizes for this WebSocket peer. Default values can be specified in the Project Settings under [code]network/limits[/code]. For server, values are meant per connected peer. - The first two parameters define the size and queued packets limits of the input buffer, the last two of the output buffer. - Buffer sizes are expressed in KiB, so [code]4 = 2^12 = 4096 bytes[/code]. All parameters will be rounded up to the nearest power of two. - [b]Note:[/b] Web exports only use the input buffer since the output one is managed by browsers. + Returns the IP address of the given peer. </description> </method> - </methods> - <signals> - <signal name="peer_packet"> - <param index="0" name="peer_source" type="int" /> + <method name="get_peer_port" qualifiers="const"> + <return type="int" /> + <param index="0" name="id" type="int" /> <description> - Emitted when a packet is received from a peer. - [b]Note:[/b] This signal is only emitted when the client or server is configured to use Godot multiplayer API. + Returns the remote port of the given peer. </description> - </signal> - </signals> + </method> + </methods> + <members> + <member name="handshake_headers" type="PackedStringArray" setter="set_handshake_headers" getter="get_handshake_headers" default="PackedStringArray()"> + The extra headers to use during handshake. See [member WebSocketPeer.handshake_headers] for more details. + </member> + <member name="handshake_timeout" type="float" setter="set_handshake_timeout" getter="get_handshake_timeout" default="3.0"> + The maximum time each peer can stay in a connecting state before being dropped. + </member> + <member name="inbound_buffer_size" type="int" setter="set_inbound_buffer_size" getter="get_inbound_buffer_size" default="65535"> + The inbound buffer size for connected peers. See [member WebSocketPeer.inbound_buffer_size] for more details. + </member> + <member name="max_queued_packets" type="int" setter="set_max_queued_packets" getter="get_max_queued_packets" default="2048"> + The maximum number of queued packets for connected peers. See [member WebSocketPeer.max_queued_packets] for more details. + </member> + <member name="outbound_buffer_size" type="int" setter="set_outbound_buffer_size" getter="get_outbound_buffer_size" default="65535"> + The outbound buffer size for connected peers. See [member WebSocketPeer.outbound_buffer_size] for more details. + </member> + <member name="supported_protocols" type="PackedStringArray" setter="set_supported_protocols" getter="get_supported_protocols" default="PackedStringArray()"> + The supported WebSocket sub-protocols. See [member WebSocketPeer.supported_protocols] for more details. + </member> + </members> </class> diff --git a/modules/websocket/doc_classes/WebSocketPeer.xml b/modules/websocket/doc_classes/WebSocketPeer.xml index 627b9c607c..41d166a0f5 100644 --- a/modules/websocket/doc_classes/WebSocketPeer.xml +++ b/modules/websocket/doc_classes/WebSocketPeer.xml @@ -1,25 +1,82 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="WebSocketPeer" inherits="PacketPeer" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> - A class representing a specific WebSocket connection. + A WebSocket connection. </brief_description> <description> - This class represents a specific WebSocket connection, allowing you to do lower level operations with it. - You can choose to write to the socket in binary or text mode, and you can recognize the mode used for writing by the other peer. + This class represents WebSocket connection, and can be used as a WebSocket client (RFC 6455-compliant) or as a remote peer of a WebSocket server. + You can send WebSocket binary frames using [method PacketPeer.put_packet], and WebSocket text frames using [method send] (prefer text frames when interacting with text-based API). You can check the frame type of the last packet via [method was_string_packet]. + To start a WebSocket client, first call [method connect_to_url], then regularly call [method poll] (e.g. during [Node] process). You can query the socket state via [method get_ready_state], get the number of pending packets using [method PacketPeer.get_available_packet_count], and retrieve them via [method PacketPeer.get_packet]. + [codeblocks] + [gdscript] + extends Node + + var socket = WebSocketPeer.new() + + func _ready(): + socket.connect_to_url("wss://example.com") + + func _process(delta): + socket.poll() + var state = socket.get_ready_state() + if state == WebSocketPeer.STATE_OPEN: + while socket.get_available_packet_count(): + print("Packet: ", socket.get_packet()) + elif state == WebSocketPeer.STATE_CLOSING: + # Keep polling to achieve proper close. + pass + elif state == WebSocketPeer.STATE_CLOSED: + var code = socket.get_close_code() + var reason = socket.get_close_reason() + print("WebSocket closed with code: %d, reason %s. Clean: %s" % [code, reason, code != -1]) + set_process(false) # Stop processing. + [/gdscript] + [/codeblocks] + To use the peer as part of a WebSocket server refer to [method accept_stream] and the online tutorial. </description> <tutorials> </tutorials> <methods> + <method name="accept_stream"> + <return type="int" enum="Error" /> + <param index="0" name="stream" type="StreamPeer" /> + <description> + Accepts a peer connection performing the HTTP handshake as a WebSocket server. The [param stream] must be a valid TCP stream retrieved via [method TCPServer.take_connection], or a TLS stream accepted via [method StreamPeerTLS.accept_stream]. + [b]Note:[/b] Not supported in Web exports due to browsers' restrictions. + </description> + </method> <method name="close"> <return type="void" /> <param index="0" name="code" type="int" default="1000" /> <param index="1" name="reason" type="String" default="""" /> <description> - Closes this WebSocket connection. [code]code[/code] is the status code for the closure (see RFC 6455 section 7.4 for a list of valid status codes). [code]reason[/code] is the human readable reason for closing the connection (can be any UTF-8 string that's smaller than 123 bytes). - [b]Note:[/b] To achieve a clean close, you will need to keep polling until either [signal WebSocketClient.connection_closed] or [signal WebSocketServer.client_disconnected] is received. + Closes this WebSocket connection. [param code] is the status code for the closure (see RFC 6455 section 7.4 for a list of valid status codes). [param reason] is the human readable reason for closing the connection (can be any UTF-8 string that's smaller than 123 bytes). If [param code] is negative, the connection will be closed immediately without notifying the remote peer. + [b]Note:[/b] To achieve a clean close, you will need to keep polling until [constant STATE_CLOSED] is reached. [b]Note:[/b] The Web export might not support all status codes. Please refer to browser-specific documentation for more details. </description> </method> + <method name="connect_to_url"> + <return type="int" enum="Error" /> + <param index="0" name="url" type="String" /> + <param index="1" name="verify_tls" type="bool" default="true" /> + <param index="2" name="trusted_tls_certificate" type="X509Certificate" default="null" /> + <description> + Connects to the given URL. If [param verify_tls] is [code]false[/code] certificate validation will be disabled. If specified, the [param trusted_tls_certificate] will be the only one accepted when connecting to a TLS host. + [b]Note:[/b] To avoid mixed content warnings or errors in Web, you may have to use a [code]url[/code] that starts with [code]wss://[/code] (secure) instead of [code]ws://[/code]. When doing so, make sure to use the fully qualified domain name that matches the one defined in the server's TLS certificate. Do not connect directly via the IP address for [code]wss://[/code] connections, as it won't match with the TLS certificate. + </description> + </method> + <method name="get_close_code" qualifiers="const"> + <return type="int" /> + <description> + Returns the received WebSocket close frame status code, or [code]-1[/code] when the connection was not cleanly closed. Only call this method when [method get_ready_state] returns [constant STATE_CLOSED]. + </description> + </method> + <method name="get_close_reason" qualifiers="const"> + <return type="String" /> + <description> + Returns the received WebSocket close frame status reason string. Only call this method when [method get_ready_state] returns [constant STATE_CLOSED]. + </description> + </method> <method name="get_connected_host" qualifiers="const"> <return type="String" /> <description> @@ -40,31 +97,51 @@ Returns the current amount of data in the outbound websocket buffer. [b]Note:[/b] Web exports use WebSocket.bufferedAmount, while other platforms use an internal buffer. </description> </method> - <method name="get_write_mode" qualifiers="const"> - <return type="int" enum="WebSocketPeer.WriteMode" /> + <method name="get_ready_state" qualifiers="const"> + <return type="int" enum="WebSocketPeer.State" /> <description> - Gets the current selected write mode. See [enum WriteMode]. + Returns the ready state of the connection. See [enum State]. </description> </method> - <method name="is_connected_to_host" qualifiers="const"> - <return type="bool" /> + <method name="get_requested_url" qualifiers="const"> + <return type="String" /> <description> - Returns [code]true[/code] if this peer is currently connected. + Returns the URL requested by this peer. The URL is derived from the [code]url[/code] passed to [method connect_to_url] or from the HTTP headers when acting as server (i.e. when using [method accept_stream]). </description> </method> - <method name="set_no_delay"> + <method name="get_selected_protocol" qualifiers="const"> + <return type="String" /> + <description> + Returns the selected WebSocket sub-protocol for this connection or an empty string if the sub-protocol has not been selected yet. + </description> + </method> + <method name="poll"> <return type="void" /> - <param index="0" name="enabled" type="bool" /> <description> - Disable Nagle's algorithm on the underling TCP socket (default). See [method StreamPeerTCP.set_no_delay] for more information. - [b]Note:[/b] Not available in the Web export. + Updates the connection state and receive incoming packets. Call this function regularly to keep it in a clean state. </description> </method> - <method name="set_write_mode"> + <method name="send"> + <return type="int" enum="Error" /> + <param index="0" name="message" type="PackedByteArray" /> + <param index="1" name="write_mode" type="int" enum="WebSocketPeer.WriteMode" default="1" /> + <description> + Sends the given [param message] using the desired [param write_mode]. When sending a [String], prefer using [method send_text]. + </description> + </method> + <method name="send_text"> + <return type="int" enum="Error" /> + <param index="0" name="message" type="String" /> + <description> + Sends the given [param message] using WebSocket text mode. Prefer this method over [method PacketPeer.put_packet] when interacting with third-party text-based API (e.g. when using [JSON] formatted messages). + </description> + </method> + <method name="set_no_delay"> <return type="void" /> - <param index="0" name="mode" type="int" enum="WebSocketPeer.WriteMode" /> + <param index="0" name="enabled" type="bool" /> <description> - Sets the socket to use the given [enum WriteMode]. + Disable Nagle's algorithm on the underling TCP socket (default). See [method StreamPeerTCP.set_no_delay] for more information. + [b]Note:[/b] Not available in the Web export. </description> </method> <method name="was_string_packet" qualifiers="const"> @@ -74,6 +151,24 @@ </description> </method> </methods> + <members> + <member name="handshake_headers" type="PackedStringArray" setter="set_handshake_headers" getter="get_handshake_headers" default="PackedStringArray()"> + The extra HTTP headers to be sent during the WebSocket handshake. + [b]Note:[/b] Not supported in Web exports due to browsers' restrictions. + </member> + <member name="inbound_buffer_size" type="int" setter="set_inbound_buffer_size" getter="get_inbound_buffer_size" default="65535"> + The size of the input buffer in bytes (roughly the maximum amount of memory that will be allocated for the inbound packets). + </member> + <member name="max_queued_packets" type="int" setter="set_max_queued_packets" getter="get_max_queued_packets" default="2048"> + The maximum amount of packets that will be allowed in the queues (both inbound and outbound). + </member> + <member name="outbound_buffer_size" type="int" setter="set_outbound_buffer_size" getter="get_outbound_buffer_size" default="65535"> + The size of the input buffer in bytes (roughly the maximum amount of memory that will be allocated for the outbound packets). + </member> + <member name="supported_protocols" type="PackedStringArray" setter="set_supported_protocols" getter="get_supported_protocols" default="PackedStringArray()"> + The WebSocket sub-protocols allowed during the WebSocket handshake. + </member> + </members> <constants> <constant name="WRITE_MODE_TEXT" value="0" enum="WriteMode"> Specifies that WebSockets messages should be transferred as text payload (only valid UTF-8 is allowed). @@ -81,5 +176,17 @@ <constant name="WRITE_MODE_BINARY" value="1" enum="WriteMode"> Specifies that WebSockets messages should be transferred as binary payload (any byte combination is allowed). </constant> + <constant name="STATE_CONNECTING" value="0" enum="State"> + Socket has been created. The connection is not yet open. + </constant> + <constant name="STATE_OPEN" value="1" enum="State"> + The connection is open and ready to communicate. + </constant> + <constant name="STATE_CLOSING" value="2" enum="State"> + The connection is in the process of closing. This means a close request has been sent to the remote peer but confirmation has not been received. + </constant> + <constant name="STATE_CLOSED" value="3" enum="State"> + The connection is closed or couldn't be opened. + </constant> </constants> </class> diff --git a/modules/websocket/doc_classes/WebSocketServer.xml b/modules/websocket/doc_classes/WebSocketServer.xml deleted file mode 100644 index 07a55b73f1..0000000000 --- a/modules/websocket/doc_classes/WebSocketServer.xml +++ /dev/null @@ -1,127 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" ?> -<class name="WebSocketServer" inherits="WebSocketMultiplayerPeer" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> - <brief_description> - A WebSocket server implementation. - </brief_description> - <description> - This class implements a WebSocket server that can also support the high-level multiplayer API. - After starting the server ([method listen]), you will need to [method MultiplayerPeer.poll] it at regular intervals (e.g. inside [method Node._process]). When clients connect, disconnect, or send data, you will receive the appropriate signal. - [b]Note:[/b] Not available in Web exports. - [b]Note:[/b] When exporting to Android, make sure to enable the [code]INTERNET[/code] permission in the Android export preset before exporting the project or using one-click deploy. Otherwise, network communication of any kind will be blocked by Android. - </description> - <tutorials> - </tutorials> - <methods> - <method name="disconnect_peer"> - <return type="void" /> - <param index="0" name="id" type="int" /> - <param index="1" name="code" type="int" default="1000" /> - <param index="2" name="reason" type="String" default="""" /> - <description> - Disconnects the peer identified by [code]id[/code] from the server. See [method WebSocketPeer.close] for more information. - </description> - </method> - <method name="get_peer_address" qualifiers="const"> - <return type="String" /> - <param index="0" name="id" type="int" /> - <description> - Returns the IP address of the given peer. - </description> - </method> - <method name="get_peer_port" qualifiers="const"> - <return type="int" /> - <param index="0" name="id" type="int" /> - <description> - Returns the remote port of the given peer. - </description> - </method> - <method name="has_peer" qualifiers="const"> - <return type="bool" /> - <param index="0" name="id" type="int" /> - <description> - Returns [code]true[/code] if a peer with the given ID is connected. - </description> - </method> - <method name="is_listening" qualifiers="const"> - <return type="bool" /> - <description> - Returns [code]true[/code] if the server is actively listening on a port. - </description> - </method> - <method name="listen"> - <return type="int" enum="Error" /> - <param index="0" name="port" type="int" /> - <param index="1" name="protocols" type="PackedStringArray" default="PackedStringArray()" /> - <param index="2" name="gd_mp_api" type="bool" default="false" /> - <description> - Starts listening on the given port. - You can specify the desired subprotocols via the "protocols" array. If the list empty (default), no sub-protocol will be requested. - If [code]true[/code] is passed as [code]gd_mp_api[/code], the server will behave like a multiplayer peer for the [MultiplayerAPI], connections from non-Godot clients will not work, and [signal data_received] will not be emitted. - If [code]false[/code] is passed instead (default), you must call [PacketPeer] functions ([code]put_packet[/code], [code]get_packet[/code], etc.), on the [WebSocketPeer] returned via [code]get_peer(id)[/code] to communicate with the peer with given [code]id[/code] (e.g. [code]get_peer(id).get_available_packet_count[/code]). - </description> - </method> - <method name="set_extra_headers"> - <return type="void" /> - <param index="0" name="headers" type="PackedStringArray" default="PackedStringArray()" /> - <description> - Sets additional headers to be sent to clients during the HTTP handshake. - </description> - </method> - <method name="stop"> - <return type="void" /> - <description> - Stops the server and clear its state. - </description> - </method> - </methods> - <members> - <member name="bind_ip" type="String" setter="set_bind_ip" getter="get_bind_ip" default=""*""> - When not set to [code]*[/code] will restrict incoming connections to the specified IP address. Setting [code]bind_ip[/code] to [code]127.0.0.1[/code] will cause the server to listen only to the local host. - </member> - <member name="ca_chain" type="X509Certificate" setter="set_ca_chain" getter="get_ca_chain"> - When using TLS (see [member private_key] and [member tls_certificate]), you can set this to a valid [X509Certificate] to be provided as additional CA chain information during the TLS handshake. - </member> - <member name="handshake_timeout" type="float" setter="set_handshake_timeout" getter="get_handshake_timeout" default="3.0"> - The time in seconds before a pending client (i.e. a client that has not yet finished the HTTP handshake) is considered stale and forcefully disconnected. - </member> - <member name="private_key" type="CryptoKey" setter="set_private_key" getter="get_private_key"> - When set to a valid [CryptoKey] (along with [member tls_certificate]) will cause the server to require TLS instead of regular TCP (i.e. the [code]wss://[/code] protocol). - </member> - <member name="tls_certificate" type="X509Certificate" setter="set_tls_certificate" getter="get_tls_certificate"> - When set to a valid [X509Certificate] (along with [member private_key]) will cause the server to require TLS instead of regular TCP (i.e. the [code]wss://[/code] protocol). - </member> - </members> - <signals> - <signal name="client_close_request"> - <param index="0" name="id" type="int" /> - <param index="1" name="code" type="int" /> - <param index="2" name="reason" type="String" /> - <description> - Emitted when a client requests a clean close. You should keep polling until you get a [signal client_disconnected] signal with the same [code]id[/code] to achieve the clean close. See [method WebSocketPeer.close] for more details. - </description> - </signal> - <signal name="client_connected"> - <param index="0" name="id" type="int" /> - <param index="1" name="protocol" type="String" /> - <param index="2" name="resource_name" type="String" /> - <description> - Emitted when a new client connects. "protocol" will be the sub-protocol agreed with the client, and "resource_name" will be the resource name of the URI the peer used. - "resource_name" is a path (at the very least a single forward slash) and potentially a query string. - </description> - </signal> - <signal name="client_disconnected"> - <param index="0" name="id" type="int" /> - <param index="1" name="was_clean_close" type="bool" /> - <description> - Emitted when a client disconnects. [code]was_clean_close[/code] will be [code]true[/code] if the connection was shutdown cleanly. - </description> - </signal> - <signal name="data_received"> - <param index="0" name="id" type="int" /> - <description> - Emitted when a new message is received. - [b]Note:[/b] This signal is [i]not[/i] emitted when used as high-level multiplayer peer. - </description> - </signal> - </signals> -</class> diff --git a/modules/websocket/editor/editor_debugger_server_websocket.cpp b/modules/websocket/editor/editor_debugger_server_websocket.cpp index 0443147d98..a9c44141aa 100644 --- a/modules/websocket/editor/editor_debugger_server_websocket.cpp +++ b/modules/websocket/editor/editor_debugger_server_websocket.cpp @@ -38,18 +38,31 @@ #include "editor/editor_node.h" #include "editor/editor_settings.h" -void EditorDebuggerServerWebSocket::_peer_connected(int p_id, String _protocol) { - pending_peers.push_back(p_id); -} +void EditorDebuggerServerWebSocket::poll() { + if (pending_peer.is_null() && tcp_server->is_connection_available()) { + Ref<WebSocketPeer> peer = Ref<WebSocketPeer>(WebSocketPeer::create()); + ERR_FAIL_COND(peer.is_null()); // Bug. -void EditorDebuggerServerWebSocket::_peer_disconnected(int p_id, bool p_was_clean) { - if (pending_peers.find(p_id)) { - pending_peers.erase(p_id); - } -} + Vector<String> ws_protocols; + ws_protocols.push_back("binary"); // Compatibility for emscripten TCP-to-WebSocket. + peer->set_supported_protocols(ws_protocols); -void EditorDebuggerServerWebSocket::poll() { - server->poll(); + Error err = peer->accept_stream(tcp_server->take_connection()); + if (err == OK) { + pending_timer = OS::get_singleton()->get_ticks_msec(); + pending_peer = peer; + } + } + if (pending_peer.is_valid() && pending_peer->get_ready_state() != WebSocketPeer::STATE_OPEN) { + pending_peer->poll(); + WebSocketPeer::State ready_state = pending_peer->get_ready_state(); + if (ready_state != WebSocketPeer::STATE_CONNECTING && ready_state != WebSocketPeer::STATE_OPEN) { + pending_peer.unref(); // Failed. + } + if (ready_state == WebSocketPeer::STATE_CONNECTING && OS::get_singleton()->get_ticks_msec() - pending_timer > 3000) { + pending_peer.unref(); // Timeout. + } + } } String EditorDebuggerServerWebSocket::get_uri() const { @@ -58,8 +71,8 @@ String EditorDebuggerServerWebSocket::get_uri() const { Error EditorDebuggerServerWebSocket::start(const String &p_uri) { // Default host and port - String bind_host = (String)EditorSettings::get_singleton()->get("network/debug/remote_host"); - int bind_port = (int)EditorSettings::get_singleton()->get("network/debug/remote_port"); + String bind_host = (String)EDITOR_GET("network/debug/remote_host"); + int bind_port = (int)EDITOR_GET("network/debug/remote_port"); // Optionally override if (!p_uri.is_empty() && p_uri != "ws://") { @@ -69,15 +82,10 @@ Error EditorDebuggerServerWebSocket::start(const String &p_uri) { ERR_FAIL_COND_V(!bind_host.is_valid_ip_address() && bind_host != "*", ERR_INVALID_PARAMETER); } - // Set up the server - server->set_bind_ip(bind_host); - Vector<String> compatible_protocols; - compatible_protocols.push_back("binary"); // compatibility with EMSCRIPTEN TCP-to-WebSocket layer. - // Try listening on ports const int max_attempts = 5; for (int attempt = 1;; ++attempt) { - const Error err = server->listen(bind_port, compatible_protocols); + const Error err = tcp_server->listen(bind_port, bind_host); if (err == OK) { break; } @@ -96,31 +104,27 @@ Error EditorDebuggerServerWebSocket::start(const String &p_uri) { } void EditorDebuggerServerWebSocket::stop() { - server->stop(); - pending_peers.clear(); + pending_peer.unref(); + tcp_server->stop(); } bool EditorDebuggerServerWebSocket::is_active() const { - return server->is_listening(); + return tcp_server->is_listening(); } bool EditorDebuggerServerWebSocket::is_connection_available() const { - return pending_peers.size() > 0; + return pending_peer.is_valid() && pending_peer->get_ready_state() == WebSocketPeer::STATE_OPEN; } Ref<RemoteDebuggerPeer> EditorDebuggerServerWebSocket::take_connection() { ERR_FAIL_COND_V(!is_connection_available(), Ref<RemoteDebuggerPeer>()); - RemoteDebuggerPeer *peer = memnew(RemoteDebuggerPeerWebSocket(server->get_peer(pending_peers[0]))); - pending_peers.pop_front(); + RemoteDebuggerPeer *peer = memnew(RemoteDebuggerPeerWebSocket(pending_peer)); + pending_peer.unref(); return peer; } EditorDebuggerServerWebSocket::EditorDebuggerServerWebSocket() { - server = Ref<WebSocketServer>(WebSocketServer::create()); - int max_pkts = (int)GLOBAL_GET("network/limits/debugger/max_queued_messages"); - server->set_buffers(8192, max_pkts, 8192, max_pkts); - server->connect("client_connected", callable_mp(this, &EditorDebuggerServerWebSocket::_peer_connected)); - server->connect("client_disconnected", callable_mp(this, &EditorDebuggerServerWebSocket::_peer_disconnected)); + tcp_server.instantiate(); } EditorDebuggerServerWebSocket::~EditorDebuggerServerWebSocket() { diff --git a/modules/websocket/editor/editor_debugger_server_websocket.h b/modules/websocket/editor/editor_debugger_server_websocket.h index 7c0705302d..31e54cb5df 100644 --- a/modules/websocket/editor/editor_debugger_server_websocket.h +++ b/modules/websocket/editor/editor_debugger_server_websocket.h @@ -33,15 +33,18 @@ #ifdef TOOLS_ENABLED -#include "../websocket_server.h" +#include "../websocket_peer.h" + +#include "core/io/tcp_server.h" #include "editor/debugger/editor_debugger_server.h" class EditorDebuggerServerWebSocket : public EditorDebuggerServer { GDCLASS(EditorDebuggerServerWebSocket, EditorDebuggerServer); private: - Ref<WebSocketServer> server; - List<int> pending_peers; + Ref<TCPServer> tcp_server; + Ref<WebSocketPeer> pending_peer; + uint64_t pending_timer = 0; String endpoint; public: diff --git a/modules/websocket/emws_client.cpp b/modules/websocket/emws_client.cpp deleted file mode 100644 index 933a1f43e9..0000000000 --- a/modules/websocket/emws_client.cpp +++ /dev/null @@ -1,159 +0,0 @@ -/*************************************************************************/ -/* emws_client.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 WEB_ENABLED - -#include "emws_client.h" - -#include "core/config/project_settings.h" -#include "core/io/ip.h" -#include "emscripten.h" - -void EMWSClient::_esws_on_connect(void *obj, char *proto) { - EMWSClient *client = static_cast<EMWSClient *>(obj); - client->_is_connecting = false; - client->_on_connect(String(proto)); -} - -void EMWSClient::_esws_on_message(void *obj, const uint8_t *p_data, int p_data_size, int p_is_string) { - EMWSClient *client = static_cast<EMWSClient *>(obj); - - Error err = static_cast<EMWSPeer *>(*client->get_peer(1))->read_msg(p_data, p_data_size, p_is_string == 1); - if (err == OK) { - client->_on_peer_packet(); - } -} - -void EMWSClient::_esws_on_error(void *obj) { - EMWSClient *client = static_cast<EMWSClient *>(obj); - client->_is_connecting = false; - client->_on_error(); -} - -void EMWSClient::_esws_on_close(void *obj, int code, const char *reason, int was_clean) { - EMWSClient *client = static_cast<EMWSClient *>(obj); - client->_on_close_request(code, String(reason)); - client->_is_connecting = false; - client->disconnect_from_host(); - client->_on_disconnect(was_clean != 0); -} - -Error EMWSClient::connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_tls, const Vector<String> p_protocols, const Vector<String> p_custom_headers) { - if (_js_id) { - godot_js_websocket_destroy(_js_id); - _js_id = 0; - } - - String proto_string; - for (int i = 0; i < p_protocols.size(); i++) { - if (i != 0) { - proto_string += ","; - } - proto_string += p_protocols[i]; - } - - String str = "ws://"; - - if (p_custom_headers.size()) { - WARN_PRINT_ONCE("Custom headers are not supported in Web platform."); - } - if (p_tls) { - str = "wss://"; - if (tls_cert.is_valid()) { - WARN_PRINT_ONCE("Custom SSL certificate is not supported in Web platform."); - } - } - str += p_host + ":" + itos(p_port) + p_path; - _is_connecting = true; - - _js_id = godot_js_websocket_create(this, str.utf8().get_data(), proto_string.utf8().get_data(), &_esws_on_connect, &_esws_on_message, &_esws_on_error, &_esws_on_close); - if (!_js_id) { - return FAILED; - } - - static_cast<Ref<EMWSPeer>>(_peer)->set_sock(_js_id, _in_buf_size, _in_pkt_size, _out_buf_size); - - return OK; -} - -void EMWSClient::poll() { -} - -Ref<WebSocketPeer> EMWSClient::get_peer(int p_peer_id) const { - return _peer; -} - -MultiplayerPeer::ConnectionStatus EMWSClient::get_connection_status() const { - if (_peer->is_connected_to_host()) { - if (_is_connecting) { - return CONNECTION_CONNECTING; - } - return CONNECTION_CONNECTED; - } - - return CONNECTION_DISCONNECTED; -} - -void EMWSClient::disconnect_from_host(int p_code, String p_reason) { - _peer->close(p_code, p_reason); -} - -IPAddress EMWSClient::get_connected_host() const { - ERR_FAIL_V_MSG(IPAddress(), "Not supported in Web export."); -} - -uint16_t EMWSClient::get_connected_port() const { - ERR_FAIL_V_MSG(0, "Not supported in Web export."); -} - -int EMWSClient::get_max_packet_size() const { - return (1 << _in_buf_size) - PROTO_SIZE; -} - -Error EMWSClient::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) { - _in_buf_size = nearest_shift(p_in_buffer - 1) + 10; - _in_pkt_size = nearest_shift(p_in_packets - 1); - _out_buf_size = nearest_shift(p_out_buffer - 1) + 10; - return OK; -} - -EMWSClient::EMWSClient() { - _peer = Ref<EMWSPeer>(memnew(EMWSPeer)); -} - -EMWSClient::~EMWSClient() { - disconnect_from_host(); - _peer = Ref<EMWSPeer>(); - if (_js_id) { - godot_js_websocket_destroy(_js_id); - } -} - -#endif // WEB_ENABLED diff --git a/modules/websocket/emws_peer.cpp b/modules/websocket/emws_peer.cpp index 859c92b457..eea015e486 100644 --- a/modules/websocket/emws_peer.cpp +++ b/modules/websocket/emws_peer.cpp @@ -34,55 +34,120 @@ #include "core/io/ip.h" -void EMWSPeer::set_sock(int p_sock, unsigned int p_in_buf_size, unsigned int p_in_pkt_size, unsigned int p_out_buf_size) { - peer_sock = p_sock; - _in_buffer.resize(p_in_pkt_size, p_in_buf_size); - _packet_buffer.resize((1 << p_in_buf_size)); - _out_buf_size = p_out_buf_size; +void EMWSPeer::_esws_on_connect(void *p_obj, char *p_proto) { + EMWSPeer *peer = static_cast<EMWSPeer *>(p_obj); + peer->ready_state = STATE_OPEN; + peer->selected_protocol.parse_utf8(p_proto); } -void EMWSPeer::set_write_mode(WriteMode p_mode) { - write_mode = p_mode; +void EMWSPeer::_esws_on_message(void *p_obj, const uint8_t *p_data, int p_data_size, int p_is_string) { + EMWSPeer *peer = static_cast<EMWSPeer *>(p_obj); + uint8_t is_string = p_is_string ? 1 : 0; + peer->in_buffer.write_packet(p_data, p_data_size, &is_string); } -EMWSPeer::WriteMode EMWSPeer::get_write_mode() const { - return write_mode; +void EMWSPeer::_esws_on_error(void *p_obj) { + EMWSPeer *peer = static_cast<EMWSPeer *>(p_obj); + peer->ready_state = STATE_CLOSED; } -Error EMWSPeer::read_msg(const uint8_t *p_data, uint32_t p_size, bool p_is_string) { - uint8_t is_string = p_is_string ? 1 : 0; - return _in_buffer.write_packet(p_data, p_size, &is_string); +void EMWSPeer::_esws_on_close(void *p_obj, int p_code, const char *p_reason, int p_was_clean) { + EMWSPeer *peer = static_cast<EMWSPeer *>(p_obj); + peer->close_code = p_code; + peer->close_reason.parse_utf8(p_reason); + peer->ready_state = STATE_CLOSED; } -Error EMWSPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) { - ERR_FAIL_COND_V(_out_buf_size && ((uint64_t)godot_js_websocket_buffered_amount(peer_sock) + p_buffer_size >= (1ULL << _out_buf_size)), ERR_OUT_OF_MEMORY); +Error EMWSPeer::connect_to_url(const String &p_url, bool p_verify_tls, Ref<X509Certificate> p_tls_certificate) { + ERR_FAIL_COND_V(ready_state != STATE_CLOSED, ERR_ALREADY_IN_USE); + _clear(); - int is_bin = write_mode == WebSocketPeer::WRITE_MODE_BINARY ? 1 : 0; + String host; + String path; + String scheme; + int port = 0; + Error err = p_url.parse_url(scheme, host, port, path); + ERR_FAIL_COND_V_MSG(err != OK, err, "Invalid URL: " + p_url); + + if (scheme.is_empty()) { + scheme = "ws://"; + } + ERR_FAIL_COND_V_MSG(scheme != "ws://" && scheme != "wss://", ERR_INVALID_PARAMETER, vformat("Invalid protocol: \"%s\" (must be either \"ws://\" or \"wss://\").", scheme)); + + String proto_string; + for (int i = 0; i < supported_protocols.size(); i++) { + if (i != 0) { + proto_string += ","; + } + proto_string += supported_protocols[i]; + } - if (godot_js_websocket_send(peer_sock, p_buffer, p_buffer_size, is_bin) != 0) { + if (handshake_headers.size()) { + WARN_PRINT_ONCE("Custom headers are not supported in Web platform."); + } + if (p_tls_certificate.is_valid()) { + WARN_PRINT_ONCE("Custom SSL certificates are not supported in Web platform."); + } + + requested_url = scheme + host; + + if (port && ((scheme == "ws://" && port != 80) || (scheme == "wss://" && port != 443))) { + requested_url += ":" + String::num(port); + } + + if (!path.is_empty()) { + requested_url += path; + } + + peer_sock = godot_js_websocket_create(this, requested_url.utf8().get_data(), proto_string.utf8().get_data(), &_esws_on_connect, &_esws_on_message, &_esws_on_error, &_esws_on_close); + if (peer_sock == -1) { return FAILED; } + in_buffer.resize(nearest_shift(inbound_buffer_size), max_queued_packets); + packet_buffer.resize(inbound_buffer_size); + ready_state = STATE_CONNECTING; + return OK; +} +Error EMWSPeer::accept_stream(Ref<StreamPeer> p_stream) { + WARN_PRINT_ONCE("Acting as WebSocket server is not supported in Web platforms."); + return ERR_UNAVAILABLE; +} + +Error EMWSPeer::_send(const uint8_t *p_buffer, int p_buffer_size, bool p_binary) { + ERR_FAIL_COND_V(outbound_buffer_size > 0 && (get_current_outbound_buffered_amount() + p_buffer_size >= outbound_buffer_size), ERR_OUT_OF_MEMORY); + + if (godot_js_websocket_send(peer_sock, p_buffer, p_buffer_size, p_binary ? 1 : 0) != 0) { + return FAILED; + } return OK; } +Error EMWSPeer::send(const uint8_t *p_buffer, int p_buffer_size, WriteMode p_mode) { + return _send(p_buffer, p_buffer_size, p_mode == WRITE_MODE_BINARY); +} + +Error EMWSPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) { + return _send(p_buffer, p_buffer_size, true); +} + Error EMWSPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { - if (_in_buffer.packets_left() == 0) { + if (in_buffer.packets_left() == 0) { return ERR_UNAVAILABLE; } int read = 0; - Error err = _in_buffer.read_packet(_packet_buffer.ptrw(), _packet_buffer.size(), &_is_string, read); + Error err = in_buffer.read_packet(packet_buffer.ptrw(), packet_buffer.size(), &was_string, read); ERR_FAIL_COND_V(err != OK, err); - *r_buffer = _packet_buffer.ptr(); + *r_buffer = packet_buffer.ptr(); r_buffer_size = read; return OK; } int EMWSPeer::get_available_packet_count() const { - return _in_buffer.packets_left(); + return in_buffer.packets_left(); } int EMWSPeer::get_current_outbound_buffered_amount() const { @@ -93,20 +158,66 @@ int EMWSPeer::get_current_outbound_buffered_amount() const { } bool EMWSPeer::was_string_packet() const { - return _is_string; + return was_string; } -bool EMWSPeer::is_connected_to_host() const { - return peer_sock != -1; +void EMWSPeer::_clear() { + if (peer_sock != -1) { + godot_js_websocket_destroy(peer_sock); + peer_sock = -1; + } + ready_state = STATE_CLOSED; + was_string = 0; + close_code = -1; + close_reason.clear(); + selected_protocol.clear(); + requested_url.clear(); + in_buffer.clear(); + packet_buffer.clear(); } void EMWSPeer::close(int p_code, String p_reason) { - if (peer_sock != -1) { - godot_js_websocket_close(peer_sock, p_code, p_reason.utf8().get_data()); + if (p_code < 0) { + if (peer_sock != -1) { + godot_js_websocket_destroy(peer_sock); + peer_sock = -1; + } + ready_state = STATE_CLOSED; + } + if (ready_state == STATE_CONNECTING || ready_state == STATE_OPEN) { + ready_state = STATE_CLOSING; + if (peer_sock != -1) { + godot_js_websocket_close(peer_sock, p_code, p_reason.utf8().get_data()); + } else { + ready_state = STATE_CLOSED; + } } - _is_string = 0; - _in_buffer.clear(); - peer_sock = -1; + in_buffer.clear(); + packet_buffer.clear(); +} + +void EMWSPeer::poll() { + // Automatically polled by the navigator. +} + +WebSocketPeer::State EMWSPeer::get_ready_state() const { + return ready_state; +} + +int EMWSPeer::get_close_code() const { + return close_code; +} + +String EMWSPeer::get_close_reason() const { + return close_reason; +} + +String EMWSPeer::get_selected_protocol() const { + return selected_protocol; +} + +String EMWSPeer::get_requested_url() const { + return requested_url; } IPAddress EMWSPeer::get_connected_host() const { @@ -122,11 +233,10 @@ void EMWSPeer::set_no_delay(bool p_enabled) { } EMWSPeer::EMWSPeer() { - close(); } EMWSPeer::~EMWSPeer() { - close(); + _clear(); } #endif // WEB_ENABLED diff --git a/modules/websocket/emws_peer.h b/modules/websocket/emws_peer.h index cdbc9212a5..322cc3b700 100644 --- a/modules/websocket/emws_peer.h +++ b/modules/websocket/emws_peer.h @@ -54,33 +54,53 @@ extern void godot_js_websocket_destroy(int p_id); } class EMWSPeer : public WebSocketPeer { - GDCIIMPL(EMWSPeer, WebSocketPeer); - private: int peer_sock = -1; - WriteMode write_mode = WRITE_MODE_BINARY; - Vector<uint8_t> _packet_buffer; - PacketBuffer<uint8_t> _in_buffer; - uint8_t _is_string = 0; - int _out_buf_size = 0; + State ready_state = STATE_CLOSED; + Vector<uint8_t> packet_buffer; + PacketBuffer<uint8_t> in_buffer; + uint8_t was_string = 0; + int close_code = -1; + String close_reason; + String selected_protocol; + String requested_url; + + static WebSocketPeer *_create() { return memnew(EMWSPeer); } + static void _esws_on_connect(void *obj, char *proto); + static void _esws_on_message(void *obj, const uint8_t *p_data, int p_data_size, int p_is_string); + static void _esws_on_error(void *obj); + static void _esws_on_close(void *obj, int code, const char *reason, int was_clean); + + void _clear(); + Error _send(const uint8_t *p_buffer, int p_buffer_size, bool p_binary); public: - Error read_msg(const uint8_t *p_data, uint32_t p_size, bool p_is_string); - void set_sock(int p_sock, unsigned int p_in_buf_size, unsigned int p_in_pkt_size, unsigned int p_out_buf_size); + static void initialize() { WebSocketPeer::_create = EMWSPeer::_create; } + + // PacketPeer virtual int get_available_packet_count() const override; virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) override; virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) override; - virtual int get_max_packet_size() const override { return _packet_buffer.size(); }; - virtual int get_current_outbound_buffered_amount() const override; + virtual int get_max_packet_size() const override { return packet_buffer.size(); }; + // WebSocketPeer + virtual Error send(const uint8_t *p_buffer, int p_buffer_size, WriteMode p_mode) override; + virtual Error connect_to_url(const String &p_url, bool p_verify_tls = true, Ref<X509Certificate> p_cert = Ref<X509Certificate>()) override; + virtual Error accept_stream(Ref<StreamPeer> p_stream) override; virtual void close(int p_code = 1000, String p_reason = "") override; - virtual bool is_connected_to_host() const override; + virtual void poll() override; + + virtual State get_ready_state() const override; + virtual int get_close_code() const override; + virtual String get_close_reason() const override; + virtual int get_current_outbound_buffered_amount() const override; + virtual IPAddress get_connected_host() const override; virtual uint16_t get_connected_port() const override; + virtual String get_selected_protocol() const override; + virtual String get_requested_url() const override; - virtual WriteMode get_write_mode() const override; - virtual void set_write_mode(WriteMode p_mode) override; virtual bool was_string_packet() const override; virtual void set_no_delay(bool p_enabled) override; diff --git a/modules/websocket/packet_buffer.h b/modules/websocket/packet_buffer.h index 7b4a164576..cd81dc43cd 100644 --- a/modules/websocket/packet_buffer.h +++ b/modules/websocket/packet_buffer.h @@ -41,32 +41,29 @@ private: T info; } _Packet; - RingBuffer<_Packet> _packets; + Vector<_Packet> _packets; + int _queued = 0; + int _write_pos = 0; + int _read_pos = 0; RingBuffer<uint8_t> _payload; public: Error write_packet(const uint8_t *p_payload, uint32_t p_size, const T *p_info) { -#ifdef TOOLS_ENABLED - // Verbose buffer warnings - if (p_payload && _payload.space_left() < (int32_t)p_size) { - ERR_PRINT("Buffer payload full! Dropping data."); - ERR_FAIL_V(ERR_OUT_OF_MEMORY); - } - if (p_info && _packets.space_left() < 1) { - ERR_PRINT("Too many packets in queue! Dropping data."); - ERR_FAIL_V(ERR_OUT_OF_MEMORY); - } -#else - ERR_FAIL_COND_V(p_payload && (uint32_t)_payload.space_left() < p_size, ERR_OUT_OF_MEMORY); - ERR_FAIL_COND_V(p_info && _packets.space_left() < 1, ERR_OUT_OF_MEMORY); -#endif + ERR_FAIL_COND_V_MSG(p_payload && (uint32_t)_payload.space_left() < p_size, ERR_OUT_OF_MEMORY, "Buffer payload full! Dropping data."); + ERR_FAIL_COND_V_MSG(p_info && _queued >= _packets.size(), ERR_OUT_OF_MEMORY, "Too many packets in queue! Dropping data."); // If p_info is nullptr, only the payload is written if (p_info) { + ERR_FAIL_COND_V(_write_pos > _packets.size(), ERR_OUT_OF_MEMORY); _Packet p; p.size = p_size; - memcpy(&p.info, p_info, sizeof(T)); - _packets.write(p); + p.info = *p_info; + _packets.write[_write_pos] = p; + _queued += 1; + _write_pos++; + if (_write_pos >= _packets.size()) { + _write_pos = 0; + } } // If p_payload is nullptr, only the packet information is written. @@ -78,9 +75,14 @@ public: } Error read_packet(uint8_t *r_payload, int p_bytes, T *r_info, int &r_read) { - ERR_FAIL_COND_V(_packets.data_left() < 1, ERR_UNAVAILABLE); - _Packet p; - _packets.read(&p, 1); + ERR_FAIL_COND_V(_queued < 1, ERR_UNAVAILABLE); + _Packet p = _packets[_read_pos]; + _read_pos += 1; + if (_read_pos >= _packets.size()) { + _read_pos = 0; + } + _queued -= 1; + ERR_FAIL_COND_V(_payload.data_left() < (int)p.size, ERR_BUG); ERR_FAIL_COND_V(p_bytes < (int)p.size, ERR_OUT_OF_MEMORY); @@ -90,22 +92,24 @@ public: return OK; } - void discard_payload(int p_size) { - _packets.decrease_write(p_size); - } - - void resize(int p_pkt_shift, int p_buf_shift) { - _packets.resize(p_pkt_shift); + void resize(int p_buf_shift, int p_max_packets) { _payload.resize(p_buf_shift); + _packets.resize(p_max_packets); + _read_pos = 0; + _write_pos = 0; + _queued = 0; } int packets_left() const { - return _packets.data_left(); + return _queued; } void clear() { _payload.resize(0); _packets.resize(0); + _read_pos = 0; + _write_pos = 0; + _queued = 0; } PacketBuffer() { diff --git a/modules/websocket/register_types.cpp b/modules/websocket/register_types.cpp index faa7021b2f..c55a651ab0 100644 --- a/modules/websocket/register_types.cpp +++ b/modules/websocket/register_types.cpp @@ -31,18 +31,18 @@ #include "register_types.h" #include "core/config/project_settings.h" +#include "core/debugger/engine_debugger.h" #include "core/error/error_macros.h" -#include "websocket_client.h" -#include "websocket_server.h" +#include "websocket_multiplayer_peer.h" +#include "websocket_peer.h" + +#include "remote_debugger_peer_websocket.h" #ifdef WEB_ENABLED -#include "emscripten.h" -#include "emws_client.h" #include "emws_peer.h" #else -#include "wsl_client.h" -#include "wsl_server.h" +#include "wsl_peer.h" #endif #ifdef TOOLS_ENABLED @@ -58,20 +58,18 @@ static void _editor_init_callback() { #endif void initialize_websocket_module(ModuleInitializationLevel p_level) { - if (p_level == MODULE_INITIALIZATION_LEVEL_SCENE) { + if (p_level == MODULE_INITIALIZATION_LEVEL_CORE) { #ifdef WEB_ENABLED - EMWSPeer::make_default(); - EMWSClient::make_default(); + EMWSPeer::initialize(); #else - WSLPeer::make_default(); - WSLClient::make_default(); - WSLServer::make_default(); + WSLPeer::initialize(); #endif - GDREGISTER_ABSTRACT_CLASS(WebSocketMultiplayerPeer); - ClassDB::register_custom_instance_class<WebSocketServer>(); - ClassDB::register_custom_instance_class<WebSocketClient>(); + GDREGISTER_CLASS(WebSocketMultiplayerPeer); ClassDB::register_custom_instance_class<WebSocketPeer>(); + + EngineDebugger::register_uri_handler("ws://", RemoteDebuggerPeerWebSocket::create); + EngineDebugger::register_uri_handler("wss://", RemoteDebuggerPeerWebSocket::create); } #ifdef TOOLS_ENABLED @@ -82,7 +80,10 @@ void initialize_websocket_module(ModuleInitializationLevel p_level) { } void uninitialize_websocket_module(ModuleInitializationLevel p_level) { - if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) { + if (p_level != MODULE_INITIALIZATION_LEVEL_CORE) { return; } +#ifndef WEB_ENABLED + WSLPeer::deinitialize(); +#endif } diff --git a/modules/websocket/remote_debugger_peer_websocket.cpp b/modules/websocket/remote_debugger_peer_websocket.cpp index f703873cbf..58adb76208 100644 --- a/modules/websocket/remote_debugger_peer_websocket.cpp +++ b/modules/websocket/remote_debugger_peer_websocket.cpp @@ -33,30 +33,39 @@ #include "core/config/project_settings.h" Error RemoteDebuggerPeerWebSocket::connect_to_host(const String &p_uri) { + ws_peer = Ref<WebSocketPeer>(WebSocketPeer::create()); + ERR_FAIL_COND_V(ws_peer.is_null(), ERR_BUG); + Vector<String> protocols; protocols.push_back("binary"); // Compatibility for emscripten TCP-to-WebSocket. - ws_client->connect_to_url(p_uri, protocols); - ws_client->poll(); + ws_peer->set_supported_protocols(protocols); + ws_peer->set_max_queued_packets(max_queued_messages); + ws_peer->set_inbound_buffer_size((1 << 23) - 1); + ws_peer->set_outbound_buffer_size((1 << 23) - 1); + + Error err = ws_peer->connect_to_url(p_uri); + ERR_FAIL_COND_V(err != OK, err); - if (ws_client->get_connection_status() == WebSocketClient::CONNECTION_DISCONNECTED) { - ERR_PRINT("Remote Debugger: Unable to connect. Status: " + String::num(ws_client->get_connection_status()) + "."); + ws_peer->poll(); + WebSocketPeer::State ready_state = ws_peer->get_ready_state(); + if (ready_state != WebSocketPeer::STATE_CONNECTING && ready_state != WebSocketPeer::STATE_OPEN) { + ERR_PRINT(vformat("Remote Debugger: Unable to connect. State: %s.", ws_peer->get_ready_state())); return FAILED; } - ws_peer = ws_client->get_peer(1); - return OK; } bool RemoteDebuggerPeerWebSocket::is_peer_connected() { - return ws_peer.is_valid() && ws_peer->is_connected_to_host(); + return ws_peer.is_valid() && (ws_peer->get_ready_state() == WebSocketPeer::STATE_OPEN || ws_peer->get_ready_state() == WebSocketPeer::STATE_CONNECTING); } void RemoteDebuggerPeerWebSocket::poll() { - ws_client->poll(); + ERR_FAIL_COND(ws_peer.is_null()); + ws_peer->poll(); - while (ws_peer->is_connected_to_host() && ws_peer->get_available_packet_count() > 0 && in_queue.size() < max_queued_messages) { + while (ws_peer->get_ready_state() == WebSocketPeer::STATE_OPEN && ws_peer->get_available_packet_count() > 0 && in_queue.size() < max_queued_messages) { Variant var; Error err = ws_peer->get_var(var); ERR_CONTINUE(err != OK); @@ -64,7 +73,7 @@ void RemoteDebuggerPeerWebSocket::poll() { in_queue.push_back(var); } - while (ws_peer->is_connected_to_host() && out_queue.size() > 0) { + while (ws_peer->get_ready_state() == WebSocketPeer::STATE_OPEN && out_queue.size() > 0) { Array var = out_queue[0]; Error err = ws_peer->put_var(var); ERR_BREAK(err != OK); // Peer buffer full? @@ -73,7 +82,8 @@ void RemoteDebuggerPeerWebSocket::poll() { } int RemoteDebuggerPeerWebSocket::get_max_message_size() const { - return 8 << 20; // 8 Mib + ERR_FAIL_COND_V(ws_peer.is_null(), 0); + return ws_peer->get_max_packet_size(); } bool RemoteDebuggerPeerWebSocket::has_message() { @@ -99,7 +109,6 @@ void RemoteDebuggerPeerWebSocket::close() { if (ws_peer.is_valid()) { ws_peer.unref(); } - ws_client->disconnect_from_host(); } bool RemoteDebuggerPeerWebSocket::can_block() const { @@ -111,14 +120,13 @@ bool RemoteDebuggerPeerWebSocket::can_block() const { } RemoteDebuggerPeerWebSocket::RemoteDebuggerPeerWebSocket(Ref<WebSocketPeer> p_peer) { -#ifdef WEB_ENABLED - ws_client = Ref<WebSocketClient>(memnew(EMWSClient)); -#else - ws_client = Ref<WebSocketClient>(memnew(WSLClient)); -#endif max_queued_messages = (int)GLOBAL_GET("network/limits/debugger/max_queued_messages"); - ws_client->set_buffers(8192, max_queued_messages, 8192, max_queued_messages); ws_peer = p_peer; + if (ws_peer.is_valid()) { + ws_peer->set_max_queued_packets(max_queued_messages); + ws_peer->set_inbound_buffer_size((1 << 23) - 1); + ws_peer->set_outbound_buffer_size((1 << 23) - 1); + } } RemoteDebuggerPeer *RemoteDebuggerPeerWebSocket::create(const String &p_uri) { diff --git a/modules/websocket/remote_debugger_peer_websocket.h b/modules/websocket/remote_debugger_peer_websocket.h index a37a789cbe..4d496ae891 100644 --- a/modules/websocket/remote_debugger_peer_websocket.h +++ b/modules/websocket/remote_debugger_peer_websocket.h @@ -33,14 +33,9 @@ #include "core/debugger/remote_debugger_peer.h" -#ifdef WEB_ENABLED -#include "emws_client.h" -#else -#include "wsl_client.h" -#endif +#include "websocket_peer.h" class RemoteDebuggerPeerWebSocket : public RemoteDebuggerPeer { - Ref<WebSocketClient> ws_client; Ref<WebSocketPeer> ws_peer; List<Array> in_queue; List<Array> out_queue; @@ -51,6 +46,7 @@ public: static RemoteDebuggerPeer *create(const String &p_uri); Error connect_to_host(const String &p_uri); + bool is_peer_connected() override; int get_max_message_size() const override; bool has_message() override; diff --git a/modules/websocket/websocket_client.cpp b/modules/websocket/websocket_client.cpp deleted file mode 100644 index 0b2d5d1918..0000000000 --- a/modules/websocket/websocket_client.cpp +++ /dev/null @@ -1,141 +0,0 @@ -/*************************************************************************/ -/* websocket_client.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "websocket_client.h" - -GDCINULL(WebSocketClient); - -WebSocketClient::WebSocketClient() { -} - -WebSocketClient::~WebSocketClient() { -} - -Error WebSocketClient::connect_to_url(String p_url, const Vector<String> p_protocols, bool gd_mp_api, const Vector<String> p_custom_headers) { - _is_multiplayer = gd_mp_api; - - String host = p_url; - String path; - String scheme; - int port = 0; - Error err = p_url.parse_url(scheme, host, port, path); - ERR_FAIL_COND_V_MSG(err != OK, err, "Invalid URL: " + p_url); - - bool tls = false; - if (scheme == "wss://") { - tls = true; - } - if (port == 0) { - port = tls ? 443 : 80; - } - if (path.is_empty()) { - path = "/"; - } - return connect_to_host(host, path, port, tls, p_protocols, p_custom_headers); -} - -void WebSocketClient::set_verify_tls_enabled(bool p_verify_tls) { - verify_tls = p_verify_tls; -} - -bool WebSocketClient::is_verify_tls_enabled() const { - return verify_tls; -} - -Ref<X509Certificate> WebSocketClient::get_trusted_tls_certificate() const { - return tls_cert; -} - -void WebSocketClient::set_trusted_tls_certificate(Ref<X509Certificate> p_cert) { - ERR_FAIL_COND(get_connection_status() != CONNECTION_DISCONNECTED); - tls_cert = p_cert; -} - -bool WebSocketClient::is_server() const { - return false; -} - -void WebSocketClient::_on_peer_packet() { - if (_is_multiplayer) { - _process_multiplayer(get_peer(1), 1); - } else { - emit_signal(SNAME("data_received")); - } -} - -void WebSocketClient::_on_connect(String p_protocol) { - if (_is_multiplayer) { - // need to wait for ID confirmation... - } else { - emit_signal(SNAME("connection_established"), p_protocol); - } -} - -void WebSocketClient::_on_close_request(int p_code, String p_reason) { - emit_signal(SNAME("server_close_request"), p_code, p_reason); -} - -void WebSocketClient::_on_disconnect(bool p_was_clean) { - if (_is_multiplayer) { - emit_signal(SNAME("connection_failed")); - } else { - emit_signal(SNAME("connection_closed"), p_was_clean); - } -} - -void WebSocketClient::_on_error() { - if (_is_multiplayer) { - emit_signal(SNAME("connection_failed")); - } else { - emit_signal(SNAME("connection_error")); - } -} - -void WebSocketClient::_bind_methods() { - ClassDB::bind_method(D_METHOD("connect_to_url", "url", "protocols", "gd_mp_api", "custom_headers"), &WebSocketClient::connect_to_url, DEFVAL(Vector<String>()), DEFVAL(false), DEFVAL(Vector<String>())); - ClassDB::bind_method(D_METHOD("disconnect_from_host", "code", "reason"), &WebSocketClient::disconnect_from_host, DEFVAL(1000), DEFVAL("")); - ClassDB::bind_method(D_METHOD("get_connected_host"), &WebSocketClient::get_connected_host); - ClassDB::bind_method(D_METHOD("get_connected_port"), &WebSocketClient::get_connected_port); - ClassDB::bind_method(D_METHOD("set_verify_tls_enabled", "enabled"), &WebSocketClient::set_verify_tls_enabled); - ClassDB::bind_method(D_METHOD("is_verify_tls_enabled"), &WebSocketClient::is_verify_tls_enabled); - - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "verify_tls", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_verify_tls_enabled", "is_verify_tls_enabled"); - - ClassDB::bind_method(D_METHOD("get_trusted_tls_certificate"), &WebSocketClient::get_trusted_tls_certificate); - ClassDB::bind_method(D_METHOD("set_trusted_tls_certificate", "cert"), &WebSocketClient::set_trusted_tls_certificate); - - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "trusted_tls_certificate", PROPERTY_HINT_RESOURCE_TYPE, "X509Certificate", PROPERTY_USAGE_NONE), "set_trusted_tls_certificate", "get_trusted_tls_certificate"); - - ADD_SIGNAL(MethodInfo("data_received")); - ADD_SIGNAL(MethodInfo("connection_established", PropertyInfo(Variant::STRING, "protocol"))); - ADD_SIGNAL(MethodInfo("server_close_request", PropertyInfo(Variant::INT, "code"), PropertyInfo(Variant::STRING, "reason"))); - ADD_SIGNAL(MethodInfo("connection_closed", PropertyInfo(Variant::BOOL, "was_clean_close"))); - ADD_SIGNAL(MethodInfo("connection_error")); -} diff --git a/modules/websocket/websocket_multiplayer_peer.cpp b/modules/websocket/websocket_multiplayer_peer.cpp index 7a3bbf1c47..14f9c0ba4d 100644 --- a/modules/websocket/websocket_multiplayer_peer.cpp +++ b/modules/websocket/websocket_multiplayer_peer.cpp @@ -33,72 +33,128 @@ #include "core/os/os.h" WebSocketMultiplayerPeer::WebSocketMultiplayerPeer() { + peer_config = Ref<WebSocketPeer>(WebSocketPeer::create()); } WebSocketMultiplayerPeer::~WebSocketMultiplayerPeer() { _clear(); } +Ref<WebSocketPeer> WebSocketMultiplayerPeer::_create_peer() { + Ref<WebSocketPeer> peer = Ref<WebSocketPeer>(WebSocketPeer::create()); + peer->set_supported_protocols(get_supported_protocols()); + peer->set_handshake_headers(get_handshake_headers()); + peer->set_inbound_buffer_size(get_inbound_buffer_size()); + peer->set_outbound_buffer_size(get_outbound_buffer_size()); + peer->set_max_queued_packets(get_max_queued_packets()); + return peer; +} + void WebSocketMultiplayerPeer::_clear() { - _peer_map.clear(); - if (_current_packet.data != nullptr) { - memfree(_current_packet.data); + connection_status = CONNECTION_DISCONNECTED; + unique_id = 0; + peers_map.clear(); + use_tls = false; + tcp_server.unref(); + pending_peers.clear(); + tls_certificate.unref(); + tls_key.unref(); + if (current_packet.data != nullptr) { + memfree(current_packet.data); + current_packet.data = nullptr; } - for (Packet &E : _incoming_packets) { + for (Packet &E : incoming_packets) { memfree(E.data); E.data = nullptr; } - _incoming_packets.clear(); + incoming_packets.clear(); } void WebSocketMultiplayerPeer::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_buffers", "input_buffer_size_kb", "input_max_packets", "output_buffer_size_kb", "output_max_packets"), &WebSocketMultiplayerPeer::set_buffers); + ClassDB::bind_method(D_METHOD("create_client", "url", "verify_tls", "tls_certificate"), &WebSocketMultiplayerPeer::create_client, DEFVAL(true), DEFVAL(Ref<X509Certificate>())); + ClassDB::bind_method(D_METHOD("create_server", "port", "bind_address", "tls_key", "tls_certificate"), &WebSocketMultiplayerPeer::create_server, DEFVAL("*"), DEFVAL(Ref<CryptoKey>()), DEFVAL(Ref<X509Certificate>())); + ClassDB::bind_method(D_METHOD("get_peer", "peer_id"), &WebSocketMultiplayerPeer::get_peer); + ClassDB::bind_method(D_METHOD("get_peer_address", "id"), &WebSocketMultiplayerPeer::get_peer_address); + ClassDB::bind_method(D_METHOD("get_peer_port", "id"), &WebSocketMultiplayerPeer::get_peer_port); + + ClassDB::bind_method(D_METHOD("get_supported_protocols"), &WebSocketMultiplayerPeer::get_supported_protocols); + ClassDB::bind_method(D_METHOD("set_supported_protocols", "protocols"), &WebSocketMultiplayerPeer::set_supported_protocols); + + ClassDB::bind_method(D_METHOD("get_handshake_headers"), &WebSocketMultiplayerPeer::get_handshake_headers); + ClassDB::bind_method(D_METHOD("set_handshake_headers", "protocols"), &WebSocketMultiplayerPeer::set_handshake_headers); + + ClassDB::bind_method(D_METHOD("get_inbound_buffer_size"), &WebSocketMultiplayerPeer::get_inbound_buffer_size); + ClassDB::bind_method(D_METHOD("set_inbound_buffer_size", "buffer_size"), &WebSocketMultiplayerPeer::set_inbound_buffer_size); + + ClassDB::bind_method(D_METHOD("get_outbound_buffer_size"), &WebSocketMultiplayerPeer::get_outbound_buffer_size); + ClassDB::bind_method(D_METHOD("set_outbound_buffer_size", "buffer_size"), &WebSocketMultiplayerPeer::set_outbound_buffer_size); + + ClassDB::bind_method(D_METHOD("get_handshake_timeout"), &WebSocketMultiplayerPeer::get_handshake_timeout); + ClassDB::bind_method(D_METHOD("set_handshake_timeout", "timeout"), &WebSocketMultiplayerPeer::set_handshake_timeout); + + ClassDB::bind_method(D_METHOD("set_max_queued_packets", "max_queued_packets"), &WebSocketMultiplayerPeer::set_max_queued_packets); + ClassDB::bind_method(D_METHOD("get_max_queued_packets"), &WebSocketMultiplayerPeer::get_max_queued_packets); + + ADD_PROPERTY(PropertyInfo(Variant::PACKED_STRING_ARRAY, "supported_protocols"), "set_supported_protocols", "get_supported_protocols"); + ADD_PROPERTY(PropertyInfo(Variant::PACKED_STRING_ARRAY, "handshake_headers"), "set_handshake_headers", "get_handshake_headers"); + + ADD_PROPERTY(PropertyInfo(Variant::INT, "inbound_buffer_size"), "set_inbound_buffer_size", "get_inbound_buffer_size"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "outbound_buffer_size"), "set_outbound_buffer_size", "get_outbound_buffer_size"); + + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "handshake_timeout"), "set_handshake_timeout", "get_handshake_timeout"); - ADD_SIGNAL(MethodInfo("peer_packet", PropertyInfo(Variant::INT, "peer_source"))); + ADD_PROPERTY(PropertyInfo(Variant::INT, "max_queued_packets"), "set_max_queued_packets", "get_max_queued_packets"); } // // PacketPeer // int WebSocketMultiplayerPeer::get_available_packet_count() const { - ERR_FAIL_COND_V_MSG(!_is_multiplayer, 0, "Please use get_peer(ID).get_available_packet_count to get available packet count from peers when not using the MultiplayerAPI."); - - return _incoming_packets.size(); + return incoming_packets.size(); } Error WebSocketMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { - ERR_FAIL_COND_V_MSG(!_is_multiplayer, ERR_UNCONFIGURED, "Please use get_peer(ID).get_packet/var to communicate with peers when not using the MultiplayerAPI."); + ERR_FAIL_COND_V(get_connection_status() != CONNECTION_CONNECTED, ERR_UNCONFIGURED); r_buffer_size = 0; - if (_current_packet.data != nullptr) { - memfree(_current_packet.data); - _current_packet.data = nullptr; + if (current_packet.data != nullptr) { + memfree(current_packet.data); + current_packet.data = nullptr; } - ERR_FAIL_COND_V(_incoming_packets.size() == 0, ERR_UNAVAILABLE); + ERR_FAIL_COND_V(incoming_packets.size() == 0, ERR_UNAVAILABLE); - _current_packet = _incoming_packets.front()->get(); - _incoming_packets.pop_front(); + current_packet = incoming_packets.front()->get(); + incoming_packets.pop_front(); - *r_buffer = _current_packet.data; - r_buffer_size = _current_packet.size; + *r_buffer = current_packet.data; + r_buffer_size = current_packet.size; return OK; } Error WebSocketMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) { - ERR_FAIL_COND_V_MSG(!_is_multiplayer, ERR_UNCONFIGURED, "Please use get_peer(ID).put_packet/var to communicate with peers when not using the MultiplayerAPI."); - - Vector<uint8_t> buffer = _make_pkt(SYS_NONE, get_unique_id(), _target_peer, p_buffer, p_buffer_size); + ERR_FAIL_COND_V(get_connection_status() != CONNECTION_CONNECTED, ERR_UNCONFIGURED); if (is_server()) { - return _server_relay(1, _target_peer, &(buffer.ptr()[0]), buffer.size()); + if (target_peer > 0) { + ERR_FAIL_COND_V_MSG(!peers_map.has(target_peer), ERR_INVALID_PARAMETER, "Peer not found: " + itos(target_peer)); + get_peer(target_peer)->put_packet(p_buffer, p_buffer_size); + } else { + for (KeyValue<int, Ref<WebSocketPeer>> &E : peers_map) { + if (target_peer && -target_peer == E.key) { + continue; // Excluded. + } + E.value->put_packet(p_buffer, p_buffer_size); + } + } + return OK; } else { - return get_peer(1)->put_packet(&(buffer.ptr()[0]), buffer.size()); + return get_peer(1)->put_packet(p_buffer, p_buffer_size); } } @@ -106,185 +162,338 @@ Error WebSocketMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer // MultiplayerPeer // void WebSocketMultiplayerPeer::set_target_peer(int p_target_peer) { - _target_peer = p_target_peer; + target_peer = p_target_peer; } int WebSocketMultiplayerPeer::get_packet_peer() const { - ERR_FAIL_COND_V_MSG(!_is_multiplayer, 1, "This function is not available when not using the MultiplayerAPI."); - ERR_FAIL_COND_V(_incoming_packets.size() == 0, 1); + ERR_FAIL_COND_V(incoming_packets.size() == 0, 1); - return _incoming_packets.front()->get().source; + return incoming_packets.front()->get().source; } int WebSocketMultiplayerPeer::get_unique_id() const { - return _peer_id; + return unique_id; } -void WebSocketMultiplayerPeer::_send_sys(Ref<WebSocketPeer> p_peer, uint8_t p_type, int32_t p_peer_id) { - ERR_FAIL_COND(!p_peer.is_valid()); - ERR_FAIL_COND(!p_peer->is_connected_to_host()); - - Vector<uint8_t> message = _make_pkt(p_type, 1, 0, (uint8_t *)&p_peer_id, 4); - p_peer->put_packet(&(message.ptr()[0]), message.size()); +int WebSocketMultiplayerPeer::get_max_packet_size() const { + return get_outbound_buffer_size() - PROTO_SIZE; } -Vector<uint8_t> WebSocketMultiplayerPeer::_make_pkt(uint8_t p_type, int32_t p_from, int32_t p_to, const uint8_t *p_data, uint32_t p_data_size) { - Vector<uint8_t> out; - out.resize(PROTO_SIZE + p_data_size); - - uint8_t *w = out.ptrw(); - memcpy(&w[0], &p_type, 1); - memcpy(&w[1], &p_from, 4); - memcpy(&w[5], &p_to, 4); - memcpy(&w[PROTO_SIZE], p_data, p_data_size); - - return out; +Error WebSocketMultiplayerPeer::create_server(int p_port, IPAddress p_bind_ip, Ref<CryptoKey> p_tls_key, Ref<X509Certificate> p_tls_certificate) { + ERR_FAIL_COND_V(get_connection_status() != CONNECTION_DISCONNECTED, ERR_ALREADY_IN_USE); + _clear(); + tcp_server.instantiate(); + Error err = tcp_server->listen(p_port, p_bind_ip); + if (err != OK) { + tcp_server.unref(); + return err; + } + unique_id = 1; + connection_status = CONNECTION_CONNECTED; + // TLS config + tls_key = p_tls_key; + tls_certificate = p_tls_certificate; + if (tls_key.is_valid() && tls_certificate.is_valid()) { + use_tls = true; + } + return OK; } -void WebSocketMultiplayerPeer::_send_add(int32_t p_peer_id) { - // First of all, confirm the ID! - _send_sys(get_peer(p_peer_id), SYS_ID, p_peer_id); +Error WebSocketMultiplayerPeer::create_client(const String &p_url, bool p_verify_tls, Ref<X509Certificate> p_tls_certificate) { + ERR_FAIL_COND_V(get_connection_status() != CONNECTION_DISCONNECTED, ERR_ALREADY_IN_USE); + _clear(); + Ref<WebSocketPeer> peer = _create_peer(); + Error err = peer->connect_to_url(p_url, p_verify_tls, p_tls_certificate); + if (err != OK) { + return err; + } + PendingPeer pending; + pending.time = OS::get_singleton()->get_ticks_msec(); + pending_peers[1] = pending; + peers_map[1] = peer; + connection_status = CONNECTION_CONNECTING; + return OK; +} - // Then send the server peer (which will trigger connection_succeded in client) - _send_sys(get_peer(p_peer_id), SYS_ADD, 1); +bool WebSocketMultiplayerPeer::is_server() const { + return tcp_server.is_valid(); +} - for (const KeyValue<int, Ref<WebSocketPeer>> &E : _peer_map) { - int32_t id = E.key; - if (p_peer_id == id) { - continue; // Skip the newly added peer (already confirmed) +void WebSocketMultiplayerPeer::_poll_client() { + ERR_FAIL_COND(connection_status == CONNECTION_DISCONNECTED); // Bug. + ERR_FAIL_COND(!peers_map.has(1) || peers_map[1].is_null()); // Bug. + Ref<WebSocketPeer> peer = peers_map[1]; + peer->poll(); // Update state and fetch packets. + WebSocketPeer::State ready_state = peer->get_ready_state(); + if (ready_state == WebSocketPeer::STATE_OPEN) { + if (connection_status == CONNECTION_CONNECTING) { + if (peer->get_available_packet_count() > 0) { + const uint8_t *in_buffer; + int size = 0; + Error err = peer->get_packet(&in_buffer, size); + if (err != OK || size != 4) { + peer->close(); // Will cause connection error on next poll. + ERR_FAIL_MSG("Invalid ID received from server"); + } + unique_id = *((int32_t *)in_buffer); + if (unique_id < 2) { + peer->close(); // Will cause connection error on next poll. + ERR_FAIL_MSG("Invalid ID received from server"); + } + connection_status = CONNECTION_CONNECTED; + emit_signal("peer_connected", 1); + emit_signal("connection_succeeded"); + } else { + return; // Still waiting for an ID. + } } - - // Send new peer to others - _send_sys(get_peer(id), SYS_ADD, p_peer_id); - // Send others to new peer - _send_sys(get_peer(p_peer_id), SYS_ADD, id); + int pkts = peer->get_available_packet_count(); + while (pkts > 0 && peer->get_ready_state() == WebSocketPeer::STATE_OPEN) { + const uint8_t *in_buffer; + int size = 0; + Error err = peer->get_packet(&in_buffer, size); + ERR_FAIL_COND(err != OK); + ERR_FAIL_COND(size <= 0); + Packet packet; + packet.data = (uint8_t *)memalloc(size); + memcpy(packet.data, in_buffer, size); + packet.size = size; + packet.source = 1; + incoming_packets.push_back(packet); + pkts--; + } + } else if (peer->get_ready_state() == WebSocketPeer::STATE_CLOSED) { + if (connection_status == CONNECTION_CONNECTED) { + emit_signal(SNAME("peer_disconnected"), 1); + } + _clear(); + return; } -} - -void WebSocketMultiplayerPeer::_send_del(int32_t p_peer_id) { - for (const KeyValue<int, Ref<WebSocketPeer>> &E : _peer_map) { - int32_t id = E.key; - if (p_peer_id != id) { - _send_sys(get_peer(id), SYS_DEL, p_peer_id); + if (connection_status == CONNECTION_CONNECTING) { + // Still connecting + ERR_FAIL_COND(!pending_peers.has(1)); // Bug. + if (OS::get_singleton()->get_ticks_msec() - pending_peers[1].time > handshake_timeout) { + print_verbose(vformat("WebSocket handshake timed out after %.3f seconds.", handshake_timeout * 0.001)); + _clear(); + return; } } } -void WebSocketMultiplayerPeer::_store_pkt(int32_t p_source, int32_t p_dest, const uint8_t *p_data, uint32_t p_data_size) { - Packet packet; - packet.data = (uint8_t *)memalloc(p_data_size); - packet.size = p_data_size; - packet.source = p_source; - packet.destination = p_dest; - memcpy(packet.data, &p_data[PROTO_SIZE], p_data_size); - _incoming_packets.push_back(packet); - emit_signal(SNAME("peer_packet"), p_source); -} +void WebSocketMultiplayerPeer::_poll_server() { + ERR_FAIL_COND(connection_status != CONNECTION_CONNECTED); // Bug. + ERR_FAIL_COND(tcp_server.is_null() || !tcp_server->is_listening()); // Bug. + + // Accept new connections. + if (!is_refusing_new_connections() && tcp_server->is_connection_available()) { + PendingPeer peer; + peer.time = OS::get_singleton()->get_ticks_msec(); + peer.tcp = tcp_server->take_connection(); + peer.connection = peer.tcp; + pending_peers[generate_unique_id()] = peer; + } -Error WebSocketMultiplayerPeer::_server_relay(int32_t p_from, int32_t p_to, const uint8_t *p_buffer, uint32_t p_buffer_size) { - if (p_to == 1) { - return OK; // Will not send to self + // Process pending peers. + HashSet<int> to_remove; + for (KeyValue<int, PendingPeer> &E : pending_peers) { + PendingPeer &peer = E.value; + int id = E.key; - } else if (p_to == 0) { - for (KeyValue<int, Ref<WebSocketPeer>> &E : _peer_map) { - if (E.key != p_from) { - E.value->put_packet(p_buffer, p_buffer_size); - } + if (OS::get_singleton()->get_ticks_msec() - peer.time > handshake_timeout) { + print_verbose(vformat("WebSocket handshake timed out after %.3f seconds.", handshake_timeout * 0.001)); + to_remove.insert(id); + continue; } - return OK; // Sent to all but sender - } else if (p_to < 0) { - for (KeyValue<int, Ref<WebSocketPeer>> &E : _peer_map) { - if (E.key != p_from && E.key != -p_to) { - E.value->put_packet(p_buffer, p_buffer_size); + if (peer.ws.is_valid()) { + peer.ws->poll(); + WebSocketPeer::State state = peer.ws->get_ready_state(); + if (state == WebSocketPeer::STATE_OPEN) { + // Connected. + to_remove.insert(id); + if (is_refusing_new_connections()) { + // The user does not want new connections, dropping it. + continue; + } + int32_t peer_id = id; + Error err = peer.ws->put_packet((const uint8_t *)&peer_id, sizeof(peer_id)); + if (err == OK) { + peers_map[id] = peer.ws; + emit_signal("peer_connected", id); + } else { + ERR_PRINT("Failed to send ID to newly connected peer."); + } + continue; + } else if (state == WebSocketPeer::STATE_CONNECTING) { + continue; // Still connecting. + } + to_remove.insert(id); // Error. + continue; + } + if (peer.tcp->get_status() != StreamPeerTCP::STATUS_CONNECTED) { + to_remove.insert(id); // Error. + continue; + } + if (!use_tls) { + peer.ws = _create_peer(); + peer.ws->accept_stream(peer.tcp); + continue; + } else { + if (peer.connection == peer.tcp) { + Ref<StreamPeerTLS> tls = Ref<StreamPeerTLS>(StreamPeerTLS::create()); + Error err = tls->accept_stream(peer.tcp, tls_key, tls_certificate); + if (err != OK) { + to_remove.insert(id); + continue; + } + } + Ref<StreamPeerTLS> tls = static_cast<Ref<StreamPeerTLS>>(peer.connection); + tls->poll(); + if (tls->get_status() == StreamPeerTLS::STATUS_CONNECTED) { + peer.ws = _create_peer(); + peer.ws->accept_stream(peer.connection); + continue; + } else if (tls->get_status() == StreamPeerTLS::STATUS_HANDSHAKING) { + // Still connecting. + continue; + } else { + // Error + to_remove.insert(id); } } - return OK; // Sent to all but sender and excluded + } - } else { - ERR_FAIL_COND_V(p_to == p_from, FAILED); + // Remove disconnected pending peers. + for (const int &pid : to_remove) { + pending_peers.erase(pid); + } + to_remove.clear(); + + // Process connected peers. + for (KeyValue<int, Ref<WebSocketPeer>> &E : peers_map) { + Ref<WebSocketPeer> ws = E.value; + int id = E.key; + ws->poll(); + if (ws->get_ready_state() != WebSocketPeer::STATE_OPEN) { + to_remove.insert(id); // Disconnected. + continue; + } + // Fetch packets + int pkts = ws->get_available_packet_count(); + while (pkts > 0 && ws->get_ready_state() == WebSocketPeer::STATE_OPEN) { + const uint8_t *in_buffer; + int size = 0; + Error err = ws->get_packet(&in_buffer, size); + if (err != OK || size <= 0) { + break; + } + Packet packet; + packet.data = (uint8_t *)memalloc(size); + memcpy(packet.data, in_buffer, size); + packet.size = size; + packet.source = E.key; + incoming_packets.push_back(packet); + pkts--; + } + } - Ref<WebSocketPeer> peer_to = get_peer(p_to); - ERR_FAIL_COND_V(peer_to.is_null(), FAILED); + // Remove disconnected peers. + for (const int &pid : to_remove) { + emit_signal(SNAME("peer_disconnected"), pid); + peers_map.erase(pid); + } +} - return peer_to->put_packet(p_buffer, p_buffer_size); // Sending to specific peer +void WebSocketMultiplayerPeer::poll() { + if (connection_status == CONNECTION_DISCONNECTED) { + return; + } + if (is_server()) { + _poll_server(); + } else { + _poll_client(); } } -void WebSocketMultiplayerPeer::_process_multiplayer(Ref<WebSocketPeer> p_peer, uint32_t p_peer_id) { - ERR_FAIL_COND(!p_peer.is_valid()); +MultiplayerPeer::ConnectionStatus WebSocketMultiplayerPeer::get_connection_status() const { + return connection_status; +} - const uint8_t *in_buffer; - int size = 0; - int data_size = 0; +Ref<WebSocketPeer> WebSocketMultiplayerPeer::get_peer(int p_id) const { + ERR_FAIL_COND_V(!peers_map.has(p_id), Ref<WebSocketPeer>()); + return peers_map[p_id]; +} - Error err = p_peer->get_packet(&in_buffer, size); +void WebSocketMultiplayerPeer::set_supported_protocols(const Vector<String> &p_protocols) { + peer_config->set_supported_protocols(p_protocols); +} - ERR_FAIL_COND(err != OK); - ERR_FAIL_COND(size < PROTO_SIZE); +Vector<String> WebSocketMultiplayerPeer::get_supported_protocols() const { + return peer_config->get_supported_protocols(); +} - data_size = size - PROTO_SIZE; +void WebSocketMultiplayerPeer::set_handshake_headers(const Vector<String> &p_headers) { + peer_config->set_handshake_headers(p_headers); +} - uint8_t type = 0; - uint32_t from = 0; - int32_t to = 0; - memcpy(&type, in_buffer, 1); - memcpy(&from, &in_buffer[1], 4); - memcpy(&to, &in_buffer[5], 4); +Vector<String> WebSocketMultiplayerPeer::get_handshake_headers() const { + return peer_config->get_handshake_headers(); +} - if (is_server()) { // Server can resend +void WebSocketMultiplayerPeer::set_outbound_buffer_size(int p_buffer_size) { + peer_config->set_outbound_buffer_size(p_buffer_size); +} - ERR_FAIL_COND(type != SYS_NONE); // Only server sends sys messages - ERR_FAIL_COND(from != p_peer_id); // Someone is cheating +int WebSocketMultiplayerPeer::get_outbound_buffer_size() const { + return peer_config->get_outbound_buffer_size(); +} - if (to == 1) { // This is for the server +void WebSocketMultiplayerPeer::set_inbound_buffer_size(int p_buffer_size) { + peer_config->set_inbound_buffer_size(p_buffer_size); +} - _store_pkt(from, to, in_buffer, data_size); +int WebSocketMultiplayerPeer::get_inbound_buffer_size() const { + return peer_config->get_inbound_buffer_size(); +} - } else if (to == 0) { - // Broadcast, for us too - _store_pkt(from, to, in_buffer, data_size); +void WebSocketMultiplayerPeer::set_max_queued_packets(int p_max_queued_packets) { + peer_config->set_max_queued_packets(p_max_queued_packets); +} - } else if (to < 0) { - // All but one, for us if not excluded - if (_peer_id != -(int32_t)p_peer_id) { - _store_pkt(from, to, in_buffer, data_size); - } - } - // Relay if needed (i.e. "to" includes a peer that is not the server) - _server_relay(from, to, in_buffer, size); +int WebSocketMultiplayerPeer::get_max_queued_packets() const { + return peer_config->get_max_queued_packets(); +} - } else { - if (type == SYS_NONE) { // Payload message +float WebSocketMultiplayerPeer::get_handshake_timeout() const { + return handshake_timeout / 1000.0; +} - _store_pkt(from, to, in_buffer, data_size); - return; - } +void WebSocketMultiplayerPeer::set_handshake_timeout(float p_timeout) { + ERR_FAIL_COND(p_timeout <= 0.0); + handshake_timeout = p_timeout * 1000; +} - // System message - ERR_FAIL_COND(data_size < 4); - int id = 0; - memcpy(&id, &in_buffer[PROTO_SIZE], 4); - - switch (type) { - case SYS_ADD: // Add peer - _peer_map[id] = Ref<WebSocketPeer>(); - emit_signal(SNAME("peer_connected"), id); - if (id == 1) { // We just connected to the server - emit_signal(SNAME("connection_succeeded")); - } - break; +IPAddress WebSocketMultiplayerPeer::get_peer_address(int p_peer_id) const { + ERR_FAIL_COND_V(!peers_map.has(p_peer_id), IPAddress()); + return peers_map[p_peer_id]->get_connected_host(); +} - case SYS_DEL: // Remove peer - _peer_map.erase(id); - emit_signal(SNAME("peer_disconnected"), id); - break; - case SYS_ID: // Hello, server assigned ID - _peer_id = id; - break; - default: - ERR_FAIL_MSG("Invalid multiplayer message."); - break; +int WebSocketMultiplayerPeer::get_peer_port(int p_peer_id) const { + ERR_FAIL_COND_V(!peers_map.has(p_peer_id), 0); + return peers_map[p_peer_id]->get_connected_port(); +} + +void WebSocketMultiplayerPeer::disconnect_peer(int p_peer_id, bool p_force) { + ERR_FAIL_COND(!peers_map.has(p_peer_id)); + peers_map[p_peer_id]->close(); + if (p_force) { + peers_map.erase(p_peer_id); + if (!is_server()) { + _clear(); } } } + +void WebSocketMultiplayerPeer::close() { + _clear(); +} diff --git a/modules/websocket/websocket_multiplayer_peer.h b/modules/websocket/websocket_multiplayer_peer.h index 3259e78b3b..78a58162ab 100644 --- a/modules/websocket/websocket_multiplayer_peer.h +++ b/modules/websocket/websocket_multiplayer_peer.h @@ -32,6 +32,8 @@ #define WEBSOCKET_MULTIPLAYER_PEER_H #include "core/error/error_list.h" +#include "core/io/stream_peer_tls.h" +#include "core/io/tcp_server.h" #include "core/templates/list.h" #include "scene/main/multiplayer_peer.h" #include "websocket_peer.h" @@ -40,9 +42,7 @@ class WebSocketMultiplayerPeer : public MultiplayerPeer { GDCLASS(WebSocketMultiplayerPeer, MultiplayerPeer); private: - Vector<uint8_t> _make_pkt(uint8_t p_type, int32_t p_from, int32_t p_to, const uint8_t *p_data, uint32_t p_data_size); - void _store_pkt(int32_t p_source, int32_t p_dest, const uint8_t *p_data, uint32_t p_data_size); - Error _server_relay(int32_t p_from, int32_t p_to, const uint8_t *p_buffer, uint32_t p_buffer_size); + Ref<WebSocketPeer> _create_peer(); protected: enum { @@ -56,30 +56,56 @@ protected: struct Packet { int source = 0; - int destination = 0; uint8_t *data = nullptr; uint32_t size = 0; }; - List<Packet> _incoming_packets; - HashMap<int, Ref<WebSocketPeer>> _peer_map; - Packet _current_packet; + struct PendingPeer { + uint64_t time = 0; + Ref<StreamPeerTCP> tcp; + Ref<StreamPeer> connection; + Ref<WebSocketPeer> ws; + }; + + uint64_t handshake_timeout = 3000; + Ref<WebSocketPeer> peer_config; + HashMap<int, PendingPeer> pending_peers; + Ref<TCPServer> tcp_server; + bool use_tls = false; + Ref<X509Certificate> tls_certificate; + Ref<CryptoKey> tls_key; + + ConnectionStatus connection_status = CONNECTION_DISCONNECTED; + + List<Packet> incoming_packets; + HashMap<int, Ref<WebSocketPeer>> peers_map; + Packet current_packet; - bool _is_multiplayer = false; - int _target_peer = 0; - int _peer_id = 0; + int target_peer = 0; + int unique_id = 0; static void _bind_methods(); - void _send_add(int32_t p_peer_id); - void _send_sys(Ref<WebSocketPeer> p_peer, uint8_t p_type, int32_t p_peer_id); - void _send_del(int32_t p_peer_id); + void _poll_client(); + void _poll_server(); + void _clear(); public: /* MultiplayerPeer */ - void set_target_peer(int p_target_peer) override; - int get_packet_peer() const override; - int get_unique_id() const override; + virtual void set_target_peer(int p_target_peer) override; + virtual int get_packet_peer() const override; + virtual int get_packet_channel() const override { return 0; } + virtual TransferMode get_packet_mode() const override { return TRANSFER_MODE_RELIABLE; } + virtual int get_unique_id() const override; + virtual bool is_server_relay_supported() const override { return true; } + + virtual int get_max_packet_size() const override; + virtual bool is_server() const override; + virtual void poll() override; + virtual void close() override; + virtual void disconnect_peer(int p_peer_id, bool p_force = false) override; + + virtual ConnectionStatus get_connection_status() const override; /* PacketPeer */ virtual int get_available_packet_count() const override; @@ -87,11 +113,31 @@ public: virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) override; /* WebSocketPeer */ - virtual Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) = 0; - virtual Ref<WebSocketPeer> get_peer(int p_peer_id) const = 0; + virtual Ref<WebSocketPeer> get_peer(int p_peer_id) const; - void _process_multiplayer(Ref<WebSocketPeer> p_peer, uint32_t p_peer_id); - void _clear(); + Error create_client(const String &p_url, bool p_verify_tls, Ref<X509Certificate> p_tls_certificate); + Error create_server(int p_port, IPAddress p_bind_ip, Ref<CryptoKey> p_tls_key, Ref<X509Certificate> p_tls_certificate); + + void set_supported_protocols(const Vector<String> &p_protocols); + Vector<String> get_supported_protocols() const; + + void set_handshake_headers(const Vector<String> &p_headers); + Vector<String> get_handshake_headers() const; + + void set_outbound_buffer_size(int p_buffer_size); + int get_outbound_buffer_size() const; + + void set_inbound_buffer_size(int p_buffer_size); + int get_inbound_buffer_size() const; + + float get_handshake_timeout() const; + void set_handshake_timeout(float p_timeout); + + IPAddress get_peer_address(int p_peer_id) const; + int get_peer_port(int p_peer_id) const; + + void set_max_queued_packets(int p_max_queued_packets); + int get_max_queued_packets() const; WebSocketMultiplayerPeer(); ~WebSocketMultiplayerPeer(); diff --git a/modules/websocket/websocket_peer.cpp b/modules/websocket/websocket_peer.cpp index a0af9303b8..b46b20bef2 100644 --- a/modules/websocket/websocket_peer.cpp +++ b/modules/websocket/websocket_peer.cpp @@ -30,7 +30,7 @@ #include "websocket_peer.h" -GDCINULL(WebSocketPeer); +WebSocketPeer *(*WebSocketPeer::_create)() = nullptr; WebSocketPeer::WebSocketPeer() { } @@ -39,16 +39,115 @@ WebSocketPeer::~WebSocketPeer() { } void WebSocketPeer::_bind_methods() { - ClassDB::bind_method(D_METHOD("get_write_mode"), &WebSocketPeer::get_write_mode); - ClassDB::bind_method(D_METHOD("set_write_mode", "mode"), &WebSocketPeer::set_write_mode); - ClassDB::bind_method(D_METHOD("is_connected_to_host"), &WebSocketPeer::is_connected_to_host); + ClassDB::bind_method(D_METHOD("connect_to_url", "url", "verify_tls", "trusted_tls_certificate"), &WebSocketPeer::connect_to_url, DEFVAL(true), DEFVAL(Ref<X509Certificate>())); + ClassDB::bind_method(D_METHOD("accept_stream", "stream"), &WebSocketPeer::accept_stream); + ClassDB::bind_method(D_METHOD("send", "message", "write_mode"), &WebSocketPeer::_send_bind, DEFVAL(WRITE_MODE_BINARY)); + ClassDB::bind_method(D_METHOD("send_text", "message"), &WebSocketPeer::send_text); ClassDB::bind_method(D_METHOD("was_string_packet"), &WebSocketPeer::was_string_packet); + ClassDB::bind_method(D_METHOD("poll"), &WebSocketPeer::poll); ClassDB::bind_method(D_METHOD("close", "code", "reason"), &WebSocketPeer::close, DEFVAL(1000), DEFVAL("")); ClassDB::bind_method(D_METHOD("get_connected_host"), &WebSocketPeer::get_connected_host); ClassDB::bind_method(D_METHOD("get_connected_port"), &WebSocketPeer::get_connected_port); + ClassDB::bind_method(D_METHOD("get_selected_protocol"), &WebSocketPeer::get_selected_protocol); + ClassDB::bind_method(D_METHOD("get_requested_url"), &WebSocketPeer::get_requested_url); ClassDB::bind_method(D_METHOD("set_no_delay", "enabled"), &WebSocketPeer::set_no_delay); ClassDB::bind_method(D_METHOD("get_current_outbound_buffered_amount"), &WebSocketPeer::get_current_outbound_buffered_amount); + ClassDB::bind_method(D_METHOD("get_ready_state"), &WebSocketPeer::get_ready_state); + ClassDB::bind_method(D_METHOD("get_close_code"), &WebSocketPeer::get_close_code); + ClassDB::bind_method(D_METHOD("get_close_reason"), &WebSocketPeer::get_close_reason); + + ClassDB::bind_method(D_METHOD("get_supported_protocols"), &WebSocketPeer::_get_supported_protocols); + ClassDB::bind_method(D_METHOD("set_supported_protocols", "protocols"), &WebSocketPeer::set_supported_protocols); + ClassDB::bind_method(D_METHOD("get_handshake_headers"), &WebSocketPeer::_get_handshake_headers); + ClassDB::bind_method(D_METHOD("set_handshake_headers", "protocols"), &WebSocketPeer::set_handshake_headers); + + ClassDB::bind_method(D_METHOD("get_inbound_buffer_size"), &WebSocketPeer::get_inbound_buffer_size); + ClassDB::bind_method(D_METHOD("set_inbound_buffer_size", "buffer_size"), &WebSocketPeer::set_inbound_buffer_size); + ClassDB::bind_method(D_METHOD("get_outbound_buffer_size"), &WebSocketPeer::get_outbound_buffer_size); + ClassDB::bind_method(D_METHOD("set_outbound_buffer_size", "buffer_size"), &WebSocketPeer::set_outbound_buffer_size); + + ClassDB::bind_method(D_METHOD("set_max_queued_packets", "buffer_size"), &WebSocketPeer::set_max_queued_packets); + ClassDB::bind_method(D_METHOD("get_max_queued_packets"), &WebSocketPeer::get_max_queued_packets); + + ADD_PROPERTY(PropertyInfo(Variant::PACKED_STRING_ARRAY, "supported_protocols"), "set_supported_protocols", "get_supported_protocols"); + ADD_PROPERTY(PropertyInfo(Variant::PACKED_STRING_ARRAY, "handshake_headers"), "set_handshake_headers", "get_handshake_headers"); + + ADD_PROPERTY(PropertyInfo(Variant::INT, "inbound_buffer_size"), "set_inbound_buffer_size", "get_inbound_buffer_size"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "outbound_buffer_size"), "set_outbound_buffer_size", "get_outbound_buffer_size"); + + ADD_PROPERTY(PropertyInfo(Variant::INT, "max_queued_packets"), "set_max_queued_packets", "get_max_queued_packets"); + BIND_ENUM_CONSTANT(WRITE_MODE_TEXT); BIND_ENUM_CONSTANT(WRITE_MODE_BINARY); + + BIND_ENUM_CONSTANT(STATE_CONNECTING); + BIND_ENUM_CONSTANT(STATE_OPEN); + BIND_ENUM_CONSTANT(STATE_CLOSING); + BIND_ENUM_CONSTANT(STATE_CLOSED); +} + +Error WebSocketPeer::_send_bind(const PackedByteArray &p_message, WriteMode p_mode) { + return send(p_message.ptr(), p_message.size(), p_mode); +} + +Error WebSocketPeer::send_text(const String &p_text) { + const CharString cs = p_text.utf8(); + return send((const uint8_t *)cs.ptr(), cs.length(), WRITE_MODE_TEXT); +} + +void WebSocketPeer::set_supported_protocols(const Vector<String> &p_protocols) { + // Strip edges from protocols. + supported_protocols.resize(p_protocols.size()); + for (int i = 0; i < p_protocols.size(); i++) { + supported_protocols.write[i] = p_protocols[i].strip_edges(); + } +} + +const Vector<String> WebSocketPeer::get_supported_protocols() const { + return supported_protocols; +} + +Vector<String> WebSocketPeer::_get_supported_protocols() const { + Vector<String> out; + out.append_array(supported_protocols); + return out; +} + +void WebSocketPeer::set_handshake_headers(const Vector<String> &p_headers) { + handshake_headers = p_headers; +} + +const Vector<String> WebSocketPeer::get_handshake_headers() const { + return handshake_headers; +} + +Vector<String> WebSocketPeer::_get_handshake_headers() const { + Vector<String> out; + out.append_array(handshake_headers); + return out; +} + +void WebSocketPeer::set_outbound_buffer_size(int p_buffer_size) { + outbound_buffer_size = p_buffer_size; +} + +int WebSocketPeer::get_outbound_buffer_size() const { + return outbound_buffer_size; +} + +void WebSocketPeer::set_inbound_buffer_size(int p_buffer_size) { + inbound_buffer_size = p_buffer_size; +} + +int WebSocketPeer::get_inbound_buffer_size() const { + return inbound_buffer_size; +} + +void WebSocketPeer::set_max_queued_packets(int p_max_queued_packets) { + max_queued_packets = p_max_queued_packets; +} + +int WebSocketPeer::get_max_queued_packets() const { + return max_queued_packets; } diff --git a/modules/websocket/websocket_peer.h b/modules/websocket/websocket_peer.h index 22099f7258..db969dd08e 100644 --- a/modules/websocket/websocket_peer.h +++ b/modules/websocket/websocket_peer.h @@ -31,40 +31,97 @@ #ifndef WEBSOCKET_PEER_H #define WEBSOCKET_PEER_H +#include "core/crypto/crypto.h" #include "core/error/error_list.h" #include "core/io/packet_peer.h" -#include "websocket_macros.h" class WebSocketPeer : public PacketPeer { GDCLASS(WebSocketPeer, PacketPeer); - GDCICLASS(WebSocketPeer); public: + enum State { + STATE_CONNECTING, + STATE_OPEN, + STATE_CLOSING, + STATE_CLOSED + }; + enum WriteMode { WRITE_MODE_TEXT, WRITE_MODE_BINARY, }; + enum { + DEFAULT_BUFFER_SIZE = 65535, + }; + +private: + virtual Error _send_bind(const PackedByteArray &p_data, WriteMode p_mode = WRITE_MODE_BINARY); + protected: + static WebSocketPeer *(*_create)(); + static void _bind_methods(); + Vector<String> supported_protocols; + Vector<String> handshake_headers; + + Vector<String> _get_supported_protocols() const; + Vector<String> _get_handshake_headers() const; + + int outbound_buffer_size = DEFAULT_BUFFER_SIZE; + int inbound_buffer_size = DEFAULT_BUFFER_SIZE; + int max_queued_packets = 2048; + public: - virtual WriteMode get_write_mode() const = 0; - virtual void set_write_mode(WriteMode p_mode) = 0; + static WebSocketPeer *create() { + if (!_create) { + return nullptr; + } + return _create(); + } + virtual Error connect_to_url(const String &p_url, bool p_verify_tls = true, Ref<X509Certificate> p_cert = Ref<X509Certificate>()) { return ERR_UNAVAILABLE; }; + virtual Error accept_stream(Ref<StreamPeer> p_stream) = 0; + + virtual Error send(const uint8_t *p_buffer, int p_buffer_size, WriteMode p_mode) = 0; virtual void close(int p_code = 1000, String p_reason = "") = 0; - virtual bool is_connected_to_host() const = 0; virtual IPAddress get_connected_host() const = 0; virtual uint16_t get_connected_port() const = 0; virtual bool was_string_packet() const = 0; virtual void set_no_delay(bool p_enabled) = 0; virtual int get_current_outbound_buffered_amount() const = 0; + virtual String get_selected_protocol() const = 0; + virtual String get_requested_url() const = 0; + + virtual void poll() = 0; + virtual State get_ready_state() const = 0; + virtual int get_close_code() const = 0; + virtual String get_close_reason() const = 0; + + Error send_text(const String &p_text); + + void set_supported_protocols(const Vector<String> &p_protocols); + const Vector<String> get_supported_protocols() const; + + void set_handshake_headers(const Vector<String> &p_headers); + const Vector<String> get_handshake_headers() const; + + void set_outbound_buffer_size(int p_buffer_size); + int get_outbound_buffer_size() const; + + void set_inbound_buffer_size(int p_buffer_size); + int get_inbound_buffer_size() const; + + void set_max_queued_packets(int p_max_queued_packets); + int get_max_queued_packets() const; WebSocketPeer(); ~WebSocketPeer(); }; VARIANT_ENUM_CAST(WebSocketPeer::WriteMode); +VARIANT_ENUM_CAST(WebSocketPeer::State); #endif // WEBSOCKET_PEER_H diff --git a/modules/websocket/websocket_server.cpp b/modules/websocket/websocket_server.cpp deleted file mode 100644 index 25a6e420fc..0000000000 --- a/modules/websocket/websocket_server.cpp +++ /dev/null @@ -1,167 +0,0 @@ -/*************************************************************************/ -/* websocket_server.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "websocket_server.h" - -GDCINULL(WebSocketServer); - -WebSocketServer::WebSocketServer() { - _peer_id = 1; - bind_ip = IPAddress("*"); -} - -WebSocketServer::~WebSocketServer() { -} - -void WebSocketServer::_bind_methods() { - ClassDB::bind_method(D_METHOD("is_listening"), &WebSocketServer::is_listening); - ClassDB::bind_method(D_METHOD("set_extra_headers", "headers"), &WebSocketServer::set_extra_headers, DEFVAL(Vector<String>())); - ClassDB::bind_method(D_METHOD("listen", "port", "protocols", "gd_mp_api"), &WebSocketServer::listen, DEFVAL(Vector<String>()), DEFVAL(false)); - ClassDB::bind_method(D_METHOD("stop"), &WebSocketServer::stop); - ClassDB::bind_method(D_METHOD("has_peer", "id"), &WebSocketServer::has_peer); - ClassDB::bind_method(D_METHOD("get_peer_address", "id"), &WebSocketServer::get_peer_address); - ClassDB::bind_method(D_METHOD("get_peer_port", "id"), &WebSocketServer::get_peer_port); - ClassDB::bind_method(D_METHOD("disconnect_peer", "id", "code", "reason"), &WebSocketServer::disconnect_peer, DEFVAL(1000), DEFVAL("")); - - ClassDB::bind_method(D_METHOD("get_bind_ip"), &WebSocketServer::get_bind_ip); - ClassDB::bind_method(D_METHOD("set_bind_ip", "ip"), &WebSocketServer::set_bind_ip); - ADD_PROPERTY(PropertyInfo(Variant::STRING, "bind_ip"), "set_bind_ip", "get_bind_ip"); - - ClassDB::bind_method(D_METHOD("get_private_key"), &WebSocketServer::get_private_key); - ClassDB::bind_method(D_METHOD("set_private_key", "key"), &WebSocketServer::set_private_key); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "private_key", PROPERTY_HINT_RESOURCE_TYPE, "CryptoKey", PROPERTY_USAGE_NONE), "set_private_key", "get_private_key"); - - ClassDB::bind_method(D_METHOD("get_tls_certificate"), &WebSocketServer::get_tls_certificate); - ClassDB::bind_method(D_METHOD("set_tls_certificate", "cert"), &WebSocketServer::set_tls_certificate); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "tls_certificate", PROPERTY_HINT_RESOURCE_TYPE, "X509Certificate", PROPERTY_USAGE_NONE), "set_tls_certificate", "get_tls_certificate"); - - ClassDB::bind_method(D_METHOD("get_ca_chain"), &WebSocketServer::get_ca_chain); - ClassDB::bind_method(D_METHOD("set_ca_chain", "ca_chain"), &WebSocketServer::set_ca_chain); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "ca_chain", PROPERTY_HINT_RESOURCE_TYPE, "X509Certificate", PROPERTY_USAGE_NONE), "set_ca_chain", "get_ca_chain"); - - ClassDB::bind_method(D_METHOD("get_handshake_timeout"), &WebSocketServer::get_handshake_timeout); - ClassDB::bind_method(D_METHOD("set_handshake_timeout", "timeout"), &WebSocketServer::set_handshake_timeout); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "handshake_timeout"), "set_handshake_timeout", "get_handshake_timeout"); - - ADD_SIGNAL(MethodInfo("client_close_request", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::INT, "code"), PropertyInfo(Variant::STRING, "reason"))); - ADD_SIGNAL(MethodInfo("client_disconnected", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::BOOL, "was_clean_close"))); - ADD_SIGNAL(MethodInfo("client_connected", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::STRING, "protocol"), PropertyInfo(Variant::STRING, "resource_name"))); - ADD_SIGNAL(MethodInfo("data_received", PropertyInfo(Variant::INT, "id"))); -} - -IPAddress WebSocketServer::get_bind_ip() const { - return bind_ip; -} - -void WebSocketServer::set_bind_ip(const IPAddress &p_bind_ip) { - ERR_FAIL_COND(is_listening()); - ERR_FAIL_COND(!p_bind_ip.is_valid() && !p_bind_ip.is_wildcard()); - bind_ip = p_bind_ip; -} - -Ref<CryptoKey> WebSocketServer::get_private_key() const { - return private_key; -} - -void WebSocketServer::set_private_key(Ref<CryptoKey> p_key) { - ERR_FAIL_COND(is_listening()); - private_key = p_key; -} - -Ref<X509Certificate> WebSocketServer::get_tls_certificate() const { - return tls_cert; -} - -void WebSocketServer::set_tls_certificate(Ref<X509Certificate> p_cert) { - ERR_FAIL_COND(is_listening()); - tls_cert = p_cert; -} - -Ref<X509Certificate> WebSocketServer::get_ca_chain() const { - return ca_chain; -} - -void WebSocketServer::set_ca_chain(Ref<X509Certificate> p_ca_chain) { - ERR_FAIL_COND(is_listening()); - ca_chain = p_ca_chain; -} - -float WebSocketServer::get_handshake_timeout() const { - return handshake_timeout / 1000.0; -} - -void WebSocketServer::set_handshake_timeout(float p_timeout) { - ERR_FAIL_COND(p_timeout <= 0.0); - handshake_timeout = p_timeout * 1000; -} - -MultiplayerPeer::ConnectionStatus WebSocketServer::get_connection_status() const { - if (is_listening()) { - return CONNECTION_CONNECTED; - } - - return CONNECTION_DISCONNECTED; -} - -bool WebSocketServer::is_server() const { - return true; -} - -void WebSocketServer::_on_peer_packet(int32_t p_peer_id) { - if (_is_multiplayer) { - _process_multiplayer(get_peer(p_peer_id), p_peer_id); - } else { - emit_signal(SNAME("data_received"), p_peer_id); - } -} - -void WebSocketServer::_on_connect(int32_t p_peer_id, String p_protocol, String p_resource_name) { - if (_is_multiplayer) { - // Send add to clients - _send_add(p_peer_id); - emit_signal(SNAME("peer_connected"), p_peer_id); - } else { - emit_signal(SNAME("client_connected"), p_peer_id, p_protocol, p_resource_name); - } -} - -void WebSocketServer::_on_disconnect(int32_t p_peer_id, bool p_was_clean) { - if (_is_multiplayer) { - // Send delete to clients - _send_del(p_peer_id); - emit_signal(SNAME("peer_disconnected"), p_peer_id); - } else { - emit_signal(SNAME("client_disconnected"), p_peer_id, p_was_clean); - } -} - -void WebSocketServer::_on_close_request(int32_t p_peer_id, int p_code, String p_reason) { - emit_signal(SNAME("client_close_request"), p_peer_id, p_code, p_reason); -} diff --git a/modules/websocket/websocket_server.h b/modules/websocket/websocket_server.h deleted file mode 100644 index de23ee884d..0000000000 --- a/modules/websocket/websocket_server.h +++ /dev/null @@ -1,90 +0,0 @@ -/*************************************************************************/ -/* websocket_server.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 WEBSOCKET_SERVER_H -#define WEBSOCKET_SERVER_H - -#include "core/crypto/crypto.h" -#include "core/object/ref_counted.h" -#include "websocket_multiplayer_peer.h" -#include "websocket_peer.h" - -class WebSocketServer : public WebSocketMultiplayerPeer { - GDCLASS(WebSocketServer, WebSocketMultiplayerPeer); - GDCICLASS(WebSocketServer); - - IPAddress bind_ip; - -protected: - static void _bind_methods(); - - Ref<CryptoKey> private_key; - Ref<X509Certificate> tls_cert; - Ref<X509Certificate> ca_chain; - uint32_t handshake_timeout = 3000; - -public: - virtual void set_extra_headers(const Vector<String> &p_headers) = 0; - virtual Error listen(int p_port, const Vector<String> p_protocols = Vector<String>(), bool gd_mp_api = false) = 0; - virtual void stop() = 0; - virtual bool is_listening() const = 0; - virtual bool has_peer(int p_id) const = 0; - virtual bool is_server() const override; - ConnectionStatus get_connection_status() const override; - - virtual IPAddress get_peer_address(int p_peer_id) const = 0; - virtual int get_peer_port(int p_peer_id) const = 0; - virtual void disconnect_peer(int p_peer_id, int p_code = 1000, String p_reason = "") = 0; - - void _on_peer_packet(int32_t p_peer_id); - void _on_connect(int32_t p_peer_id, String p_protocol, String p_resource_name); - void _on_disconnect(int32_t p_peer_id, bool p_was_clean); - void _on_close_request(int32_t p_peer_id, int p_code, String p_reason); - - IPAddress get_bind_ip() const; - void set_bind_ip(const IPAddress &p_bind_ip); - - Ref<CryptoKey> get_private_key() const; - void set_private_key(Ref<CryptoKey> p_key); - - Ref<X509Certificate> get_tls_certificate() const; - void set_tls_certificate(Ref<X509Certificate> p_cert); - - Ref<X509Certificate> get_ca_chain() const; - void set_ca_chain(Ref<X509Certificate> p_ca_chain); - - float get_handshake_timeout() const; - void set_handshake_timeout(float p_timeout); - - WebSocketServer(); - ~WebSocketServer(); -}; - -#endif // WEBSOCKET_SERVER_H diff --git a/modules/websocket/wsl_client.cpp b/modules/websocket/wsl_client.cpp deleted file mode 100644 index 50ef53e267..0000000000 --- a/modules/websocket/wsl_client.cpp +++ /dev/null @@ -1,407 +0,0 @@ -/*************************************************************************/ -/* wsl_client.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 WEB_ENABLED - -#include "wsl_client.h" -#include "core/config/project_settings.h" -#include "core/io/ip.h" - -void WSLClient::_do_handshake() { - if (_requested < _request.size() - 1) { - int sent = 0; - Error err = _connection->put_partial_data(((const uint8_t *)_request.get_data() + _requested), _request.size() - _requested - 1, sent); - // Sending handshake failed - if (err != OK) { - disconnect_from_host(); - _on_error(); - return; - } - _requested += sent; - - } else { - int read = 0; - while (true) { - if (_resp_pos >= WSL_MAX_HEADER_SIZE) { - // Header is too big - disconnect_from_host(); - _on_error(); - ERR_FAIL_MSG("Response headers too big."); - } - Error err = _connection->get_partial_data(&_resp_buf[_resp_pos], 1, read); - if (err == ERR_FILE_EOF) { - // We got a disconnect. - disconnect_from_host(); - _on_error(); - return; - } else if (err != OK) { - // Got some error. - disconnect_from_host(); - _on_error(); - return; - } else if (read != 1) { - // Busy, wait next poll. - break; - } - // Check "\r\n\r\n" header terminator - char *r = (char *)_resp_buf; - int l = _resp_pos; - if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') { - r[l - 3] = '\0'; - String protocol; - // Response is over, verify headers and create peer. - if (!_verify_headers(protocol)) { - disconnect_from_host(); - _on_error(); - ERR_FAIL_MSG("Invalid response headers."); - } - // Create peer. - WSLPeer::PeerData *data = memnew(struct WSLPeer::PeerData); - data->obj = this; - data->conn = _connection; - data->tcp = _tcp; - data->is_server = false; - data->id = 1; - _peer->make_context(data, _in_buf_size, _in_pkt_size, _out_buf_size, _out_pkt_size); - _peer->set_no_delay(true); - _status = CONNECTION_CONNECTED; - _on_connect(protocol); - break; - } - _resp_pos += 1; - } - } -} - -bool WSLClient::_verify_headers(String &r_protocol) { - String s = (char *)_resp_buf; - Vector<String> psa = s.split("\r\n"); - int len = psa.size(); - ERR_FAIL_COND_V_MSG(len < 4, false, "Not enough response headers. Got: " + itos(len) + ", expected >= 4."); - - Vector<String> req = psa[0].split(" ", false); - ERR_FAIL_COND_V_MSG(req.size() < 2, false, "Invalid protocol or status code. Got '" + psa[0] + "', expected 'HTTP/1.1 101'."); - - // Wrong protocol - ERR_FAIL_COND_V_MSG(req[0] != "HTTP/1.1", false, "Invalid protocol. Got: '" + req[0] + "', expected 'HTTP/1.1'."); - ERR_FAIL_COND_V_MSG(req[1] != "101", false, "Invalid status code. Got: '" + req[1] + "', expected '101'."); - - HashMap<String, String> headers; - for (int i = 1; i < len; i++) { - Vector<String> header = psa[i].split(":", false, 1); - ERR_FAIL_COND_V_MSG(header.size() != 2, false, "Invalid header -> " + psa[i] + "."); - String name = header[0].to_lower(); - String value = header[1].strip_edges(); - if (headers.has(name)) { - headers[name] += "," + value; - } else { - headers[name] = value; - } - } - -#define WSL_CHECK(NAME, VALUE) \ - ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false, \ - "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'."); -#define WSL_CHECK_NC(NAME, VALUE) \ - ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME] != VALUE, false, \ - "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'."); - WSL_CHECK("connection", "upgrade"); - WSL_CHECK("upgrade", "websocket"); - WSL_CHECK_NC("sec-websocket-accept", WSLPeer::compute_key_response(_key)); -#undef WSL_CHECK_NC -#undef WSL_CHECK - if (_protocols.size() == 0) { - // We didn't request a custom protocol - ERR_FAIL_COND_V_MSG(headers.has("sec-websocket-protocol"), false, "Received unrequested sub-protocol -> " + headers["sec-websocket-protocol"]); - } else { - // We requested at least one custom protocol but didn't receive one - ERR_FAIL_COND_V_MSG(!headers.has("sec-websocket-protocol"), false, "Requested sub-protocol(s) but received none."); - // Check received sub-protocol was one of those requested. - r_protocol = headers["sec-websocket-protocol"]; - bool valid = false; - for (int i = 0; i < _protocols.size(); i++) { - if (_protocols[i] != r_protocol) { - continue; - } - valid = true; - break; - } - if (!valid) { - ERR_FAIL_V_MSG(false, "Received unrequested sub-protocol -> " + r_protocol); - return false; - } - } - return true; -} - -Error WSLClient::connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_tls, const Vector<String> p_protocols, const Vector<String> p_custom_headers) { - ERR_FAIL_COND_V(_connection.is_valid(), ERR_ALREADY_IN_USE); - ERR_FAIL_COND_V(p_path.is_empty(), ERR_INVALID_PARAMETER); - - _peer = Ref<WSLPeer>(memnew(WSLPeer)); - - if (p_host.is_valid_ip_address()) { - _ip_candidates.push_back(IPAddress(p_host)); - } else { - // Queue hostname for resolution. - _resolver_id = IP::get_singleton()->resolve_hostname_queue_item(p_host); - ERR_FAIL_COND_V(_resolver_id == IP::RESOLVER_INVALID_ID, ERR_INVALID_PARAMETER); - // Check if it was found in cache. - IP::ResolverStatus ip_status = IP::get_singleton()->get_resolve_item_status(_resolver_id); - if (ip_status == IP::RESOLVER_STATUS_DONE) { - _ip_candidates = IP::get_singleton()->get_resolve_item_addresses(_resolver_id); - IP::get_singleton()->erase_resolve_item(_resolver_id); - _resolver_id = IP::RESOLVER_INVALID_ID; - } - } - - // We assume OK while hostname resolution is pending. - Error err = _resolver_id != IP::RESOLVER_INVALID_ID ? OK : FAILED; - while (_ip_candidates.size()) { - err = _tcp->connect_to_host(_ip_candidates.pop_front(), p_port); - if (err == OK) { - break; - } - } - if (err != OK) { - _tcp->disconnect_from_host(); - _on_error(); - return err; - } - _connection = _tcp; - _use_tls = p_tls; - _host = p_host; - _port = p_port; - // Strip edges from protocols. - _protocols.resize(p_protocols.size()); - String *pw = _protocols.ptrw(); - for (int i = 0; i < p_protocols.size(); i++) { - pw[i] = p_protocols[i].strip_edges(); - } - - _key = WSLPeer::generate_key(); - String request = "GET " + p_path + " HTTP/1.1\r\n"; - String port = ""; - if ((p_port != 80 && !p_tls) || (p_port != 443 && p_tls)) { - port = ":" + itos(p_port); - } - request += "Host: " + p_host + port + "\r\n"; - request += "Upgrade: websocket\r\n"; - request += "Connection: Upgrade\r\n"; - request += "Sec-WebSocket-Key: " + _key + "\r\n"; - request += "Sec-WebSocket-Version: 13\r\n"; - if (p_protocols.size() > 0) { - request += "Sec-WebSocket-Protocol: "; - for (int i = 0; i < p_protocols.size(); i++) { - if (i != 0) { - request += ","; - } - request += p_protocols[i]; - } - request += "\r\n"; - } - for (int i = 0; i < p_custom_headers.size(); i++) { - request += p_custom_headers[i] + "\r\n"; - } - request += "\r\n"; - _request = request.utf8(); - _status = CONNECTION_CONNECTING; - - return OK; -} - -int WSLClient::get_max_packet_size() const { - return (1 << _out_buf_size) - PROTO_SIZE; -} - -void WSLClient::poll() { - if (_resolver_id != IP::RESOLVER_INVALID_ID) { - IP::ResolverStatus ip_status = IP::get_singleton()->get_resolve_item_status(_resolver_id); - if (ip_status == IP::RESOLVER_STATUS_WAITING) { - return; - } - // Anything else is either a candidate or a failure. - Error err = FAILED; - if (ip_status == IP::RESOLVER_STATUS_DONE) { - _ip_candidates = IP::get_singleton()->get_resolve_item_addresses(_resolver_id); - while (_ip_candidates.size()) { - err = _tcp->connect_to_host(_ip_candidates.pop_front(), _port); - if (err == OK) { - break; - } - } - } - IP::get_singleton()->erase_resolve_item(_resolver_id); - _resolver_id = IP::RESOLVER_INVALID_ID; - if (err != OK) { - disconnect_from_host(); - _on_error(); - return; - } - } - if (_peer->is_connected_to_host()) { - _peer->poll(); - if (!_peer->is_connected_to_host()) { - disconnect_from_host(); - _on_disconnect(_peer->close_code != -1); - } - return; - } - - if (_connection.is_null()) { - return; // Not connected. - } - - _tcp->poll(); - switch (_tcp->get_status()) { - case StreamPeerTCP::STATUS_NONE: - // Clean close - disconnect_from_host(); - _on_error(); - break; - case StreamPeerTCP::STATUS_CONNECTED: { - _ip_candidates.clear(); - Ref<StreamPeerTLS> tls; - if (_use_tls) { - if (_connection == _tcp) { - // Start SSL handshake - tls = Ref<StreamPeerTLS>(StreamPeerTLS::create()); - ERR_FAIL_COND_MSG(tls.is_null(), "SSL is not available in this build."); - tls->set_blocking_handshake_enabled(false); - if (tls->connect_to_stream(_tcp, verify_tls, _host, tls_cert) != OK) { - disconnect_from_host(); - _on_error(); - return; - } - _connection = tls; - } else { - tls = static_cast<Ref<StreamPeerTLS>>(_connection); - ERR_FAIL_COND(tls.is_null()); // Bug? - tls->poll(); - } - if (tls->get_status() == StreamPeerTLS::STATUS_HANDSHAKING) { - return; // Need more polling. - } else if (tls->get_status() != StreamPeerTLS::STATUS_CONNECTED) { - disconnect_from_host(); - _on_error(); - return; // Error. - } - } - // Do websocket handshake. - _do_handshake(); - } break; - case StreamPeerTCP::STATUS_ERROR: - while (_ip_candidates.size() > 0) { - _tcp->disconnect_from_host(); - if (_tcp->connect_to_host(_ip_candidates.pop_front(), _port) == OK) { - return; - } - } - disconnect_from_host(); - _on_error(); - break; - case StreamPeerTCP::STATUS_CONNECTING: - break; // Wait for connection - } -} - -Ref<WebSocketPeer> WSLClient::get_peer(int p_peer_id) const { - ERR_FAIL_COND_V(p_peer_id != 1, nullptr); - - return _peer; -} - -MultiplayerPeer::ConnectionStatus WSLClient::get_connection_status() const { - // This is surprising, but keeps the current behaviour to allow clean close requests. - // TODO Refactor WebSocket and split Client/Server/Multiplayer like done in other peers. - if (_peer->is_connected_to_host()) { - return CONNECTION_CONNECTED; - } - return _status; -} - -void WSLClient::disconnect_from_host(int p_code, String p_reason) { - _peer->close(p_code, p_reason); - _connection = Ref<StreamPeer>(nullptr); - _tcp = Ref<StreamPeerTCP>(memnew(StreamPeerTCP)); - _status = CONNECTION_DISCONNECTED; - - _key = ""; - _host = ""; - _protocols.clear(); - _use_tls = false; - - _request = ""; - _requested = 0; - - memset(_resp_buf, 0, sizeof(_resp_buf)); - _resp_pos = 0; - - if (_resolver_id != IP::RESOLVER_INVALID_ID) { - IP::get_singleton()->erase_resolve_item(_resolver_id); - _resolver_id = IP::RESOLVER_INVALID_ID; - } - - _ip_candidates.clear(); -} - -IPAddress WSLClient::get_connected_host() const { - ERR_FAIL_COND_V(!_peer->is_connected_to_host(), IPAddress()); - return _peer->get_connected_host(); -} - -uint16_t WSLClient::get_connected_port() const { - ERR_FAIL_COND_V(!_peer->is_connected_to_host(), 0); - return _peer->get_connected_port(); -} - -Error WSLClient::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) { - ERR_FAIL_COND_V_MSG(_connection.is_valid(), FAILED, "Buffers sizes can only be set before listening or connecting."); - - _in_buf_size = nearest_shift(p_in_buffer - 1) + 10; - _in_pkt_size = nearest_shift(p_in_packets - 1); - _out_buf_size = nearest_shift(p_out_buffer - 1) + 10; - _out_pkt_size = nearest_shift(p_out_packets - 1); - return OK; -} - -WSLClient::WSLClient() { - _peer.instantiate(); - _tcp.instantiate(); - disconnect_from_host(); -} - -WSLClient::~WSLClient() { - _peer->close_now(); - _peer->invalidate(); - disconnect_from_host(); -} - -#endif // WEB_ENABLED diff --git a/modules/websocket/wsl_client.h b/modules/websocket/wsl_client.h deleted file mode 100644 index dfb989fdd3..0000000000 --- a/modules/websocket/wsl_client.h +++ /dev/null @@ -1,91 +0,0 @@ -/*************************************************************************/ -/* wsl_client.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 WSL_CLIENT_H -#define WSL_CLIENT_H - -#ifndef WEB_ENABLED - -#include "core/error/error_list.h" -#include "core/io/stream_peer_tcp.h" -#include "core/io/stream_peer_tls.h" -#include "websocket_client.h" -#include "wsl_peer.h" -#include "wslay/wslay.h" - -class WSLClient : public WebSocketClient { - GDCIIMPL(WSLClient, WebSocketClient); - -private: - int _in_buf_size = DEF_BUF_SHIFT; - int _in_pkt_size = DEF_PKT_SHIFT; - int _out_buf_size = DEF_BUF_SHIFT; - int _out_pkt_size = DEF_PKT_SHIFT; - - Ref<WSLPeer> _peer; - Ref<StreamPeerTCP> _tcp; - Ref<StreamPeer> _connection; - ConnectionStatus _status = CONNECTION_DISCONNECTED; - - CharString _request; - int _requested = 0; - - uint8_t _resp_buf[WSL_MAX_HEADER_SIZE]; - int _resp_pos = 0; - - String _key; - String _host; - uint16_t _port = 0; - Array _ip_candidates; - Vector<String> _protocols; - bool _use_tls = false; - IP::ResolverID _resolver_id = IP::RESOLVER_INVALID_ID; - - void _do_handshake(); - bool _verify_headers(String &r_protocol); - -public: - Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) override; - Error connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_tls, const Vector<String> p_protocol = Vector<String>(), const Vector<String> p_custom_headers = Vector<String>()) override; - int get_max_packet_size() const override; - Ref<WebSocketPeer> get_peer(int p_peer_id) const override; - void disconnect_from_host(int p_code = 1000, String p_reason = "") override; - IPAddress get_connected_host() const override; - uint16_t get_connected_port() const override; - virtual ConnectionStatus get_connection_status() const override; - virtual void poll() override; - - WSLClient(); - ~WSLClient(); -}; - -#endif // WEB_ENABLED - -#endif // WSL_CLIENT_H diff --git a/modules/websocket/wsl_peer.cpp b/modules/websocket/wsl_peer.cpp index 97bd87a526..84e022182e 100644 --- a/modules/websocket/wsl_peer.cpp +++ b/modules/websocket/wsl_peer.cpp @@ -32,71 +32,537 @@ #include "wsl_peer.h" -#include "wsl_client.h" -#include "wsl_server.h" +#include "wsl_peer.h" -#include "core/crypto/crypto_core.h" -#include "core/math/random_number_generator.h" -#include "core/os/os.h" +#include "core/io/stream_peer_tls.h" -String WSLPeer::generate_key() { - // Random key - RandomNumberGenerator rng; - rng.set_seed(OS::get_singleton()->get_unix_time()); - Vector<uint8_t> bkey; - int len = 16; // 16 bytes, as per RFC - bkey.resize(len); - uint8_t *w = bkey.ptrw(); - for (int i = 0; i < len; i++) { - w[i] = (uint8_t)rng.randi_range(0, 255); +CryptoCore::RandomGenerator *WSLPeer::_static_rng = nullptr; + +void WSLPeer::initialize() { + WebSocketPeer::_create = WSLPeer::_create; + _static_rng = memnew(CryptoCore::RandomGenerator); + _static_rng->init(); +} + +void WSLPeer::deinitialize() { + if (_static_rng) { + memdelete(_static_rng); + _static_rng = nullptr; } - return CryptoCore::b64_encode_str(&w[0], len); } -String WSLPeer::compute_key_response(String p_key) { - String key = p_key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; // Magic UUID as per RFC - Vector<uint8_t> sha = key.sha1_buffer(); - return CryptoCore::b64_encode_str(sha.ptr(), sha.size()); +/// +/// Resolver +/// +void WSLPeer::Resolver::start(const String &p_host, int p_port) { + stop(); + + port = p_port; + if (p_host.is_valid_ip_address()) { + ip_candidates.push_back(IPAddress(p_host)); + } else { + // Queue hostname for resolution. + resolver_id = IP::get_singleton()->resolve_hostname_queue_item(p_host); + ERR_FAIL_COND(resolver_id == IP::RESOLVER_INVALID_ID); + // Check if it was found in cache. + IP::ResolverStatus ip_status = IP::get_singleton()->get_resolve_item_status(resolver_id); + if (ip_status == IP::RESOLVER_STATUS_DONE) { + ip_candidates = IP::get_singleton()->get_resolve_item_addresses(resolver_id); + IP::get_singleton()->erase_resolve_item(resolver_id); + resolver_id = IP::RESOLVER_INVALID_ID; + } + } } -void WSLPeer::_wsl_destroy(struct PeerData **p_data) { - if (!p_data || !(*p_data)) { - return; +void WSLPeer::Resolver::stop() { + if (resolver_id != IP::RESOLVER_INVALID_ID) { + IP::get_singleton()->erase_resolve_item(resolver_id); + resolver_id = IP::RESOLVER_INVALID_ID; + } + port = 0; +} + +void WSLPeer::Resolver::try_next_candidate(Ref<StreamPeerTCP> &p_tcp) { + // Check if we still need resolving. + if (resolver_id != IP::RESOLVER_INVALID_ID) { + IP::ResolverStatus ip_status = IP::get_singleton()->get_resolve_item_status(resolver_id); + if (ip_status == IP::RESOLVER_STATUS_WAITING) { + return; + } + if (ip_status == IP::RESOLVER_STATUS_DONE) { + ip_candidates = IP::get_singleton()->get_resolve_item_addresses(resolver_id); + } + IP::get_singleton()->erase_resolve_item(resolver_id); + resolver_id = IP::RESOLVER_INVALID_ID; } - struct PeerData *data = *p_data; - if (data->polling) { - data->destroy = true; + + // Try the current candidate if we have one. + if (p_tcp->get_status() != StreamPeerTCP::STATUS_NONE) { + p_tcp->poll(); + StreamPeerTCP::Status status = p_tcp->get_status(); + if (status == StreamPeerTCP::STATUS_CONNECTED) { + p_tcp->set_no_delay(true); + ip_candidates.clear(); + return; + } else if (status == StreamPeerTCP::STATUS_CONNECTING) { + return; // Keep connecting. + } else { + p_tcp->disconnect_from_host(); + } + } + + // Keep trying next candidate. + while (ip_candidates.size()) { + Error err = p_tcp->connect_to_host(ip_candidates.pop_front(), port); + if (err == OK) { + return; + } else { + p_tcp->disconnect_from_host(); + } + } +} + +/// +/// Server functions +/// +Error WSLPeer::accept_stream(Ref<StreamPeer> p_stream) { + ERR_FAIL_COND_V(wsl_ctx || tcp.is_valid(), ERR_ALREADY_IN_USE); + ERR_FAIL_COND_V(p_stream.is_null(), ERR_INVALID_PARAMETER); + + _clear(); + + if (p_stream->is_class_ptr(StreamPeerTCP::get_class_ptr_static())) { + tcp = p_stream; + connection = p_stream; + use_tls = false; + } else if (p_stream->is_class_ptr(StreamPeerTLS::get_class_ptr_static())) { + Ref<StreamPeer> base_stream = static_cast<Ref<StreamPeerTLS>>(p_stream)->get_stream(); + ERR_FAIL_COND_V(base_stream.is_null() || !base_stream->is_class_ptr(StreamPeerTCP::get_class_ptr_static()), ERR_INVALID_PARAMETER); + tcp = static_cast<Ref<StreamPeerTCP>>(base_stream); + connection = p_stream; + use_tls = true; + } + ERR_FAIL_COND_V(connection.is_null() || tcp.is_null(), ERR_INVALID_PARAMETER); + is_server = true; + ready_state = STATE_CONNECTING; + handshake_buffer->resize(WSL_MAX_HEADER_SIZE); + handshake_buffer->seek(0); + return OK; +} + +bool WSLPeer::_parse_client_request() { + Vector<String> psa = String((const char *)handshake_buffer->get_data_array().ptr(), handshake_buffer->get_position() - 4).split("\r\n"); + int len = psa.size(); + ERR_FAIL_COND_V_MSG(len < 4, false, "Not enough response headers, got: " + itos(len) + ", expected >= 4."); + + Vector<String> req = psa[0].split(" ", false); + ERR_FAIL_COND_V_MSG(req.size() < 2, false, "Invalid protocol or status code."); + + // Wrong protocol + ERR_FAIL_COND_V_MSG(req[0] != "GET" || req[2] != "HTTP/1.1", false, "Invalid method or HTTP version."); + + HashMap<String, String> headers; + for (int i = 1; i < len; i++) { + Vector<String> header = psa[i].split(":", false, 1); + ERR_FAIL_COND_V_MSG(header.size() != 2, false, "Invalid header -> " + psa[i]); + String name = header[0].to_lower(); + String value = header[1].strip_edges(); + if (headers.has(name)) { + headers[name] += "," + value; + } else { + headers[name] = value; + } + } + requested_host = headers.has("host") ? headers.get("host") : ""; + requested_url = (use_tls ? "wss://" : "ws://") + requested_host + req[1]; +#define WSL_CHECK(NAME, VALUE) \ + ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false, \ + "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'."); +#define WSL_CHECK_EX(NAME) \ + ERR_FAIL_COND_V_MSG(!headers.has(NAME), false, "Missing header '" + String(NAME) + "'."); + WSL_CHECK("upgrade", "websocket"); + WSL_CHECK("sec-websocket-version", "13"); + WSL_CHECK_EX("sec-websocket-key"); + WSL_CHECK_EX("connection"); +#undef WSL_CHECK_EX +#undef WSL_CHECK + session_key = headers["sec-websocket-key"]; + if (headers.has("sec-websocket-protocol")) { + Vector<String> protos = headers["sec-websocket-protocol"].split(","); + for (int i = 0; i < protos.size(); i++) { + String proto = protos[i].strip_edges(); + // Check if we have the given protocol + for (int j = 0; j < supported_protocols.size(); j++) { + if (proto != supported_protocols[j]) { + continue; + } + selected_protocol = proto; + break; + } + // Found a protocol + if (!selected_protocol.is_empty()) { + break; + } + } + if (selected_protocol.is_empty()) { // Invalid protocol(s) requested + return false; + } + } else if (supported_protocols.size() > 0) { // No protocol requested, but we need one + return false; + } + return true; +} + +Error WSLPeer::_do_server_handshake() { + if (use_tls) { + Ref<StreamPeerTLS> tls = static_cast<Ref<StreamPeerTLS>>(connection); + if (tls.is_null()) { + ERR_FAIL_V_MSG(ERR_BUG, "Couldn't get StreamPeerTLS for WebSocket handshake."); + close(-1); + return FAILED; + } + tls->poll(); + if (tls->get_status() == StreamPeerTLS::STATUS_HANDSHAKING) { + return OK; // Pending handshake + } else if (tls->get_status() != StreamPeerTLS::STATUS_CONNECTED) { + print_verbose(vformat("WebSocket SSL connection error during handshake (StreamPeerTLS status code %d).", tls->get_status())); + close(-1); + return FAILED; + } + } + + if (pending_request) { + int read = 0; + while (true) { + ERR_FAIL_COND_V_MSG(handshake_buffer->get_available_bytes() < 1, ERR_OUT_OF_MEMORY, "WebSocket response headers are too big."); + int pos = handshake_buffer->get_position(); + uint8_t byte; + Error err = connection->get_partial_data(&byte, 1, read); + if (err != OK) { // Got an error + print_verbose(vformat("WebSocket error while getting partial data (StreamPeer error code %d).", err)); + close(-1); + return FAILED; + } else if (read != 1) { // Busy, wait next poll + return OK; + } + handshake_buffer->put_u8(byte); + const char *r = (const char *)handshake_buffer->get_data_array().ptr(); + int l = pos; + if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') { + if (!_parse_client_request()) { + close(-1); + return FAILED; + } + String s = "HTTP/1.1 101 Switching Protocols\r\n"; + s += "Upgrade: websocket\r\n"; + s += "Connection: Upgrade\r\n"; + s += "Sec-WebSocket-Accept: " + _compute_key_response(session_key) + "\r\n"; + if (!selected_protocol.is_empty()) { + s += "Sec-WebSocket-Protocol: " + selected_protocol + "\r\n"; + } + for (int i = 0; i < handshake_headers.size(); i++) { + s += handshake_headers[i] + "\r\n"; + } + s += "\r\n"; + CharString cs = s.utf8(); + handshake_buffer->clear(); + handshake_buffer->put_data((const uint8_t *)cs.get_data(), cs.length()); + handshake_buffer->seek(0); + pending_request = false; + break; + } + } + } + + if (pending_request) { // Still pending. + return OK; + } + + int left = handshake_buffer->get_available_bytes(); + if (left) { + Vector<uint8_t> data = handshake_buffer->get_data_array(); + int pos = handshake_buffer->get_position(); + int sent = 0; + Error err = connection->put_partial_data(data.ptr() + pos, left, sent); + if (err != OK) { + print_verbose(vformat("WebSocket error while putting partial data (StreamPeer error code %d).", err)); + close(-1); + return err; + } + handshake_buffer->seek(pos + sent); + left -= sent; + if (left == 0) { + resolver.stop(); + // Response sent, initialize wslay context. + wslay_event_context_server_init(&wsl_ctx, &_wsl_callbacks, this); + wslay_event_config_set_max_recv_msg_length(wsl_ctx, inbound_buffer_size); + in_buffer.resize(nearest_shift(inbound_buffer_size), max_queued_packets); + packet_buffer.resize(inbound_buffer_size); + ready_state = STATE_OPEN; + } + } + + return OK; +} + +/// +/// Client functions +/// +void WSLPeer::_do_client_handshake() { + ERR_FAIL_COND(tcp.is_null()); + + // Try to connect to candidates. + if (resolver.has_more_candidates()) { + resolver.try_next_candidate(tcp); + if (resolver.has_more_candidates()) { + return; // Still pending. + } + } + + tcp->poll(); + if (tcp->get_status() == StreamPeerTCP::STATUS_CONNECTING) { + return; // Keep connecting. + } else if (tcp->get_status() != StreamPeerTCP::STATUS_CONNECTED) { + close(-1); // Failed to connect. return; } - wslay_event_context_free(data->ctx); - memdelete(data); - *p_data = nullptr; + + if (use_tls) { + Ref<StreamPeerTLS> tls; + if (connection == tcp) { + // Start SSL handshake + tls = Ref<StreamPeerTLS>(StreamPeerTLS::create()); + ERR_FAIL_COND_MSG(tls.is_null(), "SSL is not available in this build."); + tls->set_blocking_handshake_enabled(false); + if (tls->connect_to_stream(tcp, verify_tls, requested_host, tls_cert) != OK) { + close(-1); + return; // Error. + } + connection = tls; + } else { + tls = static_cast<Ref<StreamPeerTLS>>(connection); + ERR_FAIL_COND(tls.is_null()); + tls->poll(); + } + if (tls->get_status() == StreamPeerTLS::STATUS_HANDSHAKING) { + return; // Need more polling. + } else if (tls->get_status() != StreamPeerTLS::STATUS_CONNECTED) { + close(-1); + return; // Error. + } + } + + // Do websocket handshake. + if (pending_request) { + int left = handshake_buffer->get_available_bytes(); + int pos = handshake_buffer->get_position(); + const Vector<uint8_t> data = handshake_buffer->get_data_array(); + int sent = 0; + Error err = connection->put_partial_data(data.ptr() + pos, left, sent); + // Sending handshake failed + if (err != OK) { + close(-1); + return; // Error. + } + handshake_buffer->seek(pos + sent); + if (handshake_buffer->get_available_bytes() == 0) { + pending_request = false; + handshake_buffer->clear(); + handshake_buffer->resize(WSL_MAX_HEADER_SIZE); + handshake_buffer->seek(0); + } + } else { + int read = 0; + while (true) { + int left = handshake_buffer->get_available_bytes(); + int pos = handshake_buffer->get_position(); + if (left == 0) { + // Header is too big + close(-1); + ERR_FAIL_MSG("Response headers too big."); + return; + } + + uint8_t byte; + Error err = connection->get_partial_data(&byte, 1, read); + if (err != OK) { + // Got some error. + close(-1); + return; + } else if (read != 1) { + // Busy, wait next poll. + break; + } + handshake_buffer->put_u8(byte); + + // Check "\r\n\r\n" header terminator + const char *r = (const char *)handshake_buffer->get_data_array().ptr(); + int l = pos; + if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') { + // Response is over, verify headers and initialize wslay context/ + if (!_verify_server_response()) { + close(-1); + ERR_FAIL_MSG("Invalid response headers."); + return; + } + wslay_event_context_client_init(&wsl_ctx, &_wsl_callbacks, this); + wslay_event_config_set_max_recv_msg_length(wsl_ctx, inbound_buffer_size); + in_buffer.resize(nearest_shift(inbound_buffer_size), max_queued_packets); + packet_buffer.resize(inbound_buffer_size); + ready_state = STATE_OPEN; + break; + } + } + } } -bool WSLPeer::_wsl_poll(struct PeerData *p_data) { - p_data->polling = true; - int err = 0; - if ((err = wslay_event_recv(p_data->ctx)) != 0 || (err = wslay_event_send(p_data->ctx)) != 0) { - print_verbose("Websocket (wslay) poll error: " + itos(err)); - p_data->destroy = true; +bool WSLPeer::_verify_server_response() { + Vector<String> psa = String((const char *)handshake_buffer->get_data_array().ptr(), handshake_buffer->get_position() - 4).split("\r\n"); + int len = psa.size(); + ERR_FAIL_COND_V_MSG(len < 4, false, "Not enough response headers. Got: " + itos(len) + ", expected >= 4."); + + Vector<String> req = psa[0].split(" ", false); + ERR_FAIL_COND_V_MSG(req.size() < 2, false, "Invalid protocol or status code. Got '" + psa[0] + "', expected 'HTTP/1.1 101'."); + + // Wrong protocol + ERR_FAIL_COND_V_MSG(req[0] != "HTTP/1.1", false, "Invalid protocol. Got: '" + req[0] + "', expected 'HTTP/1.1'."); + ERR_FAIL_COND_V_MSG(req[1] != "101", false, "Invalid status code. Got: '" + req[1] + "', expected '101'."); + + HashMap<String, String> headers; + for (int i = 1; i < len; i++) { + Vector<String> header = psa[i].split(":", false, 1); + ERR_FAIL_COND_V_MSG(header.size() != 2, false, "Invalid header -> " + psa[i] + "."); + String name = header[0].to_lower(); + String value = header[1].strip_edges(); + if (headers.has(name)) { + headers[name] += "," + value; + } else { + headers[name] = value; + } } - p_data->polling = false; - if (p_data->destroy || (wslay_event_get_close_sent(p_data->ctx) && wslay_event_get_close_received(p_data->ctx))) { - bool valid = p_data->valid; - _wsl_destroy(&p_data); - return valid; +#define WSL_CHECK(NAME, VALUE) \ + ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false, \ + "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'."); +#define WSL_CHECK_NC(NAME, VALUE) \ + ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME] != VALUE, false, \ + "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'."); + WSL_CHECK("connection", "upgrade"); + WSL_CHECK("upgrade", "websocket"); + WSL_CHECK_NC("sec-websocket-accept", _compute_key_response(session_key)); +#undef WSL_CHECK_NC +#undef WSL_CHECK + if (supported_protocols.size() == 0) { + // We didn't request a custom protocol + ERR_FAIL_COND_V_MSG(headers.has("sec-websocket-protocol"), false, "Received unrequested sub-protocol -> " + headers["sec-websocket-protocol"]); + } else { + // We requested at least one custom protocol but didn't receive one + ERR_FAIL_COND_V_MSG(!headers.has("sec-websocket-protocol"), false, "Requested sub-protocol(s) but received none."); + // Check received sub-protocol was one of those requested. + selected_protocol = headers["sec-websocket-protocol"]; + bool valid = false; + for (int i = 0; i < supported_protocols.size(); i++) { + if (supported_protocols[i] != selected_protocol) { + continue; + } + valid = true; + break; + } + if (!valid) { + ERR_FAIL_V_MSG(false, "Received unrequested sub-protocol -> " + selected_protocol); + return false; + } + } + return true; +} + +Error WSLPeer::connect_to_url(const String &p_url, bool p_verify_tls, Ref<X509Certificate> p_cert) { + ERR_FAIL_COND_V(wsl_ctx || tcp.is_valid(), ERR_ALREADY_IN_USE); + ERR_FAIL_COND_V(p_url.is_empty(), ERR_INVALID_PARAMETER); + + _clear(); + + String host; + String path; + String scheme; + int port = 0; + Error err = p_url.parse_url(scheme, host, port, path); + ERR_FAIL_COND_V_MSG(err != OK, err, "Invalid URL: " + p_url); + if (scheme.is_empty()) { + scheme = "ws://"; + } + ERR_FAIL_COND_V_MSG(scheme != "ws://" && scheme != "wss://", ERR_INVALID_PARAMETER, vformat("Invalid protocol: \"%s\" (must be either \"ws://\" or \"wss://\").", scheme)); + + use_tls = false; + if (scheme == "wss://") { + use_tls = true; + } + if (port == 0) { + port = use_tls ? 443 : 80; + } + if (path.is_empty()) { + path = "/"; + } + + requested_url = p_url; + requested_host = host; + verify_tls = p_verify_tls; + tls_cert = p_cert; + tcp.instantiate(); + + resolver.start(host, port); + resolver.try_next_candidate(tcp); + + if (tcp->get_status() != StreamPeerTCP::STATUS_CONNECTING && tcp->get_status() != StreamPeerTCP::STATUS_CONNECTED && !resolver.has_more_candidates()) { + _clear(); + return FAILED; + } + connection = tcp; + + // Prepare handshake request. + session_key = _generate_key(); + String request = "GET " + path + " HTTP/1.1\r\n"; + String port_string; + if ((port != 80 && !use_tls) || (port != 443 && use_tls)) { + port_string = ":" + itos(port); + } + request += "Host: " + host + port_string + "\r\n"; + request += "Upgrade: websocket\r\n"; + request += "Connection: Upgrade\r\n"; + request += "Sec-WebSocket-Key: " + session_key + "\r\n"; + request += "Sec-WebSocket-Version: 13\r\n"; + if (supported_protocols.size() > 0) { + request += "Sec-WebSocket-Protocol: "; + for (int i = 0; i < supported_protocols.size(); i++) { + if (i != 0) { + request += ","; + } + request += supported_protocols[i]; + } + request += "\r\n"; } - return false; + for (int i = 0; i < handshake_headers.size(); i++) { + request += handshake_headers[i] + "\r\n"; + } + request += "\r\n"; + CharString cs = request.utf8(); + handshake_buffer->put_data((const uint8_t *)cs.get_data(), cs.length()); + handshake_buffer->seek(0); + ready_state = STATE_CONNECTING; + is_server = false; + return OK; } -ssize_t wsl_recv_callback(wslay_event_context_ptr ctx, uint8_t *data, size_t len, int flags, void *user_data) { - struct WSLPeer::PeerData *peer_data = (struct WSLPeer::PeerData *)user_data; - if (!peer_data->valid) { +/// +/// Callback functions. +/// +ssize_t WSLPeer::_wsl_recv_callback(wslay_event_context_ptr ctx, uint8_t *data, size_t len, int flags, void *user_data) { + WSLPeer *peer = (WSLPeer *)user_data; + Ref<StreamPeer> conn = peer->connection; + if (conn.is_null()) { wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE); return -1; } - Ref<StreamPeer> conn = peer_data->conn; int read = 0; Error err = conn->get_partial_data(data, len, read); if (err != OK) { @@ -111,13 +577,13 @@ ssize_t wsl_recv_callback(wslay_event_context_ptr ctx, uint8_t *data, size_t len return read; } -ssize_t wsl_send_callback(wslay_event_context_ptr ctx, const uint8_t *data, size_t len, int flags, void *user_data) { - struct WSLPeer::PeerData *peer_data = (struct WSLPeer::PeerData *)user_data; - if (!peer_data->valid) { +ssize_t WSLPeer::_wsl_send_callback(wslay_event_context_ptr ctx, const uint8_t *data, size_t len, int flags, void *user_data) { + WSLPeer *peer = (WSLPeer *)user_data; + Ref<StreamPeer> conn = peer->connection; + if (conn.is_null()) { wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE); return -1; } - Ref<StreamPeer> conn = peer_data->conn; int sent = 0; Error err = conn->put_partial_data(data, len, sent); if (err != OK) { @@ -131,144 +597,142 @@ ssize_t wsl_send_callback(wslay_event_context_ptr ctx, const uint8_t *data, size return sent; } -int wsl_genmask_callback(wslay_event_context_ptr ctx, uint8_t *buf, size_t len, void *user_data) { - RandomNumberGenerator rng; - // TODO maybe use crypto in the future? - rng.set_seed(OS::get_singleton()->get_unix_time()); - for (unsigned int i = 0; i < len; i++) { - buf[i] = (uint8_t)rng.randi_range(0, 255); - } +int WSLPeer::_wsl_genmask_callback(wslay_event_context_ptr ctx, uint8_t *buf, size_t len, void *user_data) { + ERR_FAIL_COND_V(!_static_rng, WSLAY_ERR_CALLBACK_FAILURE); + Error err = _static_rng->get_random_bytes(buf, len); + ERR_FAIL_COND_V(err != OK, WSLAY_ERR_CALLBACK_FAILURE); return 0; } -void wsl_msg_recv_callback(wslay_event_context_ptr ctx, const struct wslay_event_on_msg_recv_arg *arg, void *user_data) { - struct WSLPeer::PeerData *peer_data = (struct WSLPeer::PeerData *)user_data; - if (!peer_data->valid || peer_data->closing) { +void WSLPeer::_wsl_msg_recv_callback(wslay_event_context_ptr ctx, const struct wslay_event_on_msg_recv_arg *arg, void *user_data) { + WSLPeer *peer = (WSLPeer *)user_data; + uint8_t op = arg->opcode; + + if (op == WSLAY_CONNECTION_CLOSE) { + // Close request or confirmation. + peer->close_code = arg->status_code; + size_t len = arg->msg_length; + peer->close_reason = ""; + if (len > 2 /* first 2 bytes = close code */) { + peer->close_reason.parse_utf8((char *)arg->msg + 2, len - 2); + } + if (peer->ready_state == STATE_OPEN) { + peer->ready_state = STATE_CLOSING; + } return; } - WSLPeer *peer = static_cast<WSLPeer *>(peer_data->peer); - if (peer->parse_message(arg) != OK) { + if (peer->ready_state == STATE_CLOSING) { return; } - if (peer_data->is_server) { - WSLServer *helper = static_cast<WSLServer *>(peer_data->obj); - helper->_on_peer_packet(peer_data->id); - } else { - WSLClient *helper = static_cast<WSLClient *>(peer_data->obj); - helper->_on_peer_packet(); + if (op == WSLAY_TEXT_FRAME || op == WSLAY_BINARY_FRAME) { + // Message. + uint8_t is_string = arg->opcode == WSLAY_TEXT_FRAME ? 1 : 0; + peer->in_buffer.write_packet(arg->msg, arg->msg_length, &is_string); } + // Ping or pong. } -wslay_event_callbacks wsl_callbacks = { - wsl_recv_callback, - wsl_send_callback, - wsl_genmask_callback, +wslay_event_callbacks WSLPeer::_wsl_callbacks = { + _wsl_recv_callback, + _wsl_send_callback, + _wsl_genmask_callback, nullptr, /* on_frame_recv_start_callback */ nullptr, /* on_frame_recv_callback */ nullptr, /* on_frame_recv_end_callback */ - wsl_msg_recv_callback + _wsl_msg_recv_callback }; -Error WSLPeer::parse_message(const wslay_event_on_msg_recv_arg *arg) { - uint8_t is_string = 0; - if (arg->opcode == WSLAY_TEXT_FRAME) { - is_string = 1; - } else if (arg->opcode == WSLAY_CONNECTION_CLOSE) { - close_code = arg->status_code; - size_t len = arg->msg_length; - close_reason = ""; - if (len > 2 /* first 2 bytes = close code */) { - close_reason.parse_utf8((char *)arg->msg + 2, len - 2); - } - if (!wslay_event_get_close_sent(_data->ctx)) { - if (_data->is_server) { - WSLServer *helper = static_cast<WSLServer *>(_data->obj); - helper->_on_close_request(_data->id, close_code, close_reason); - } else { - WSLClient *helper = static_cast<WSLClient *>(_data->obj); - helper->_on_close_request(close_code, close_reason); - } - } - return ERR_FILE_EOF; - } else if (arg->opcode != WSLAY_BINARY_FRAME) { - // Ping or pong - return ERR_SKIP; - } - _in_buffer.write_packet(arg->msg, arg->msg_length, &is_string); - return OK; -} - -void WSLPeer::make_context(PeerData *p_data, unsigned int p_in_buf_size, unsigned int p_in_pkt_size, unsigned int p_out_buf_size, unsigned int p_out_pkt_size) { - ERR_FAIL_COND(_data != nullptr); - ERR_FAIL_COND(p_data == nullptr); - - _in_buffer.resize(p_in_pkt_size, p_in_buf_size); - _packet_buffer.resize(1 << p_in_buf_size); - _out_buf_size = p_out_buf_size; - _out_pkt_size = p_out_pkt_size; - - _data = p_data; - _data->peer = this; - _data->valid = true; - - if (_data->is_server) { - wslay_event_context_server_init(&(_data->ctx), &wsl_callbacks, _data); - } else { - wslay_event_context_client_init(&(_data->ctx), &wsl_callbacks, _data); - } - wslay_event_config_set_max_recv_msg_length(_data->ctx, (1ULL << p_in_buf_size)); -} - -void WSLPeer::set_write_mode(WriteMode p_mode) { - write_mode = p_mode; +String WSLPeer::_generate_key() { + // Random key + Vector<uint8_t> bkey; + int len = 16; // 16 bytes, as per RFC + bkey.resize(len); + _wsl_genmask_callback(nullptr, bkey.ptrw(), len, nullptr); + return CryptoCore::b64_encode_str(bkey.ptrw(), len); } -WSLPeer::WriteMode WSLPeer::get_write_mode() const { - return write_mode; +String WSLPeer::_compute_key_response(String p_key) { + String key = p_key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; // Magic UUID as per RFC + Vector<uint8_t> sha = key.sha1_buffer(); + return CryptoCore::b64_encode_str(sha.ptr(), sha.size()); } void WSLPeer::poll() { - if (!_data) { + // Nothing to do. + if (ready_state == STATE_CLOSED) { return; } - if (_wsl_poll(_data)) { - _data = nullptr; + if (ready_state == STATE_CONNECTING) { + if (is_server) { + _do_server_handshake(); + } else { + _do_client_handshake(); + } + } + + if (ready_state == STATE_OPEN || ready_state == STATE_CLOSING) { + ERR_FAIL_COND(!wsl_ctx); + int err = 0; + if ((err = wslay_event_recv(wsl_ctx)) != 0 || (err = wslay_event_send(wsl_ctx)) != 0) { + // Error close. + print_verbose("Websocket (wslay) poll error: " + itos(err)); + wslay_event_context_free(wsl_ctx); + wsl_ctx = nullptr; + close(-1); + return; + } + if (wslay_event_get_close_sent(wsl_ctx) && wslay_event_get_close_received(wsl_ctx)) { + // Clean close. + wslay_event_context_free(wsl_ctx); + wsl_ctx = nullptr; + close(-1); + return; + } } } -Error WSLPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) { - ERR_FAIL_COND_V(!is_connected_to_host(), FAILED); - ERR_FAIL_COND_V(_out_pkt_size && (wslay_event_get_queued_msg_count(_data->ctx) >= (1ULL << _out_pkt_size)), ERR_OUT_OF_MEMORY); - ERR_FAIL_COND_V(_out_buf_size && (wslay_event_get_queued_msg_length(_data->ctx) + p_buffer_size >= (1ULL << _out_buf_size)), ERR_OUT_OF_MEMORY); +Error WSLPeer::_send(const uint8_t *p_buffer, int p_buffer_size, wslay_opcode p_opcode) { + ERR_FAIL_COND_V(ready_state != STATE_OPEN, FAILED); + ERR_FAIL_COND_V(wslay_event_get_queued_msg_count(wsl_ctx) >= (uint32_t)max_queued_packets, ERR_OUT_OF_MEMORY); + ERR_FAIL_COND_V(outbound_buffer_size > 0 && (wslay_event_get_queued_msg_length(wsl_ctx) + p_buffer_size > (uint32_t)outbound_buffer_size), ERR_OUT_OF_MEMORY); struct wslay_event_msg msg; - msg.opcode = write_mode == WRITE_MODE_TEXT ? WSLAY_TEXT_FRAME : WSLAY_BINARY_FRAME; + msg.opcode = p_opcode; msg.msg = p_buffer; msg.msg_length = p_buffer_size; // Queue & send message. - if (wslay_event_queue_msg(_data->ctx, &msg) != 0 || wslay_event_send(_data->ctx) != 0) { - close_now(); + if (wslay_event_queue_msg(wsl_ctx, &msg) != 0 || wslay_event_send(wsl_ctx) != 0) { + close(-1); return FAILED; } return OK; } +Error WSLPeer::send(const uint8_t *p_buffer, int p_buffer_size, WriteMode p_mode) { + wslay_opcode opcode = p_mode == WRITE_MODE_TEXT ? WSLAY_TEXT_FRAME : WSLAY_BINARY_FRAME; + return _send(p_buffer, p_buffer_size, opcode); +} + +Error WSLPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) { + return _send(p_buffer, p_buffer_size, WSLAY_BINARY_FRAME); +} + Error WSLPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { r_buffer_size = 0; - ERR_FAIL_COND_V(!is_connected_to_host(), FAILED); + ERR_FAIL_COND_V(ready_state != STATE_OPEN, FAILED); - if (_in_buffer.packets_left() == 0) { + if (in_buffer.packets_left() == 0) { return ERR_UNAVAILABLE; } int read = 0; - uint8_t *rw = _packet_buffer.ptrw(); - _in_buffer.read_packet(rw, _packet_buffer.size(), &_is_string, read); + uint8_t *rw = packet_buffer.ptrw(); + in_buffer.read_packet(rw, packet_buffer.size(), &was_string, read); *r_buffer = rw; r_buffer_size = read; @@ -277,75 +741,106 @@ Error WSLPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { } int WSLPeer::get_available_packet_count() const { - if (!is_connected_to_host()) { + if (ready_state != STATE_OPEN) { return 0; } - return _in_buffer.packets_left(); + return in_buffer.packets_left(); } int WSLPeer::get_current_outbound_buffered_amount() const { - ERR_FAIL_COND_V(!_data, 0); - - return wslay_event_get_queued_msg_length(_data->ctx); -} - -bool WSLPeer::was_string_packet() const { - return _is_string; -} - -bool WSLPeer::is_connected_to_host() const { - return _data != nullptr; -} + if (ready_state != STATE_OPEN) { + return 0; + } -void WSLPeer::close_now() { - close(1000, ""); - _wsl_destroy(&_data); + return wslay_event_get_queued_msg_length(wsl_ctx); } void WSLPeer::close(int p_code, String p_reason) { - if (_data && !wslay_event_get_close_sent(_data->ctx)) { + if (p_code < 0) { + // Force immediate close. + ready_state = STATE_CLOSED; + } + + if (ready_state == STATE_OPEN && !wslay_event_get_close_sent(wsl_ctx)) { CharString cs = p_reason.utf8(); - wslay_event_queue_close(_data->ctx, p_code, (uint8_t *)cs.ptr(), cs.size()); - wslay_event_send(_data->ctx); - _data->closing = true; + wslay_event_queue_close(wsl_ctx, p_code, (uint8_t *)cs.ptr(), cs.length()); + wslay_event_send(wsl_ctx); + ready_state = STATE_CLOSING; + } else if (ready_state == STATE_CONNECTING || ready_state == STATE_CLOSED) { + ready_state = STATE_CLOSED; + connection.unref(); + if (tcp.is_valid()) { + tcp->disconnect_from_host(); + tcp.unref(); + } } - _in_buffer.clear(); - _packet_buffer.resize(0); + in_buffer.clear(); + packet_buffer.resize(0); } IPAddress WSLPeer::get_connected_host() const { - ERR_FAIL_COND_V(!is_connected_to_host() || _data->tcp.is_null(), IPAddress()); - - return _data->tcp->get_connected_host(); + ERR_FAIL_COND_V(tcp.is_null(), IPAddress()); + return tcp->get_connected_host(); } uint16_t WSLPeer::get_connected_port() const { - ERR_FAIL_COND_V(!is_connected_to_host() || _data->tcp.is_null(), 0); + ERR_FAIL_COND_V(tcp.is_null(), 0); + return tcp->get_connected_port(); +} + +String WSLPeer::get_selected_protocol() const { + return selected_protocol; +} - return _data->tcp->get_connected_port(); +String WSLPeer::get_requested_url() const { + return requested_url; } void WSLPeer::set_no_delay(bool p_enabled) { - ERR_FAIL_COND(!is_connected_to_host() || _data->tcp.is_null()); - _data->tcp->set_no_delay(p_enabled); + ERR_FAIL_COND(tcp.is_null()); + tcp->set_no_delay(p_enabled); } -void WSLPeer::invalidate() { - if (_data) { - _data->valid = false; +void WSLPeer::_clear() { + // Connection info. + ready_state = STATE_CLOSED; + is_server = false; + connection.unref(); + if (tcp.is_valid()) { + tcp->disconnect_from_host(); + tcp.unref(); } + if (wsl_ctx) { + wslay_event_context_free(wsl_ctx); + wsl_ctx = nullptr; + } + + resolver.stop(); + requested_url.clear(); + requested_host.clear(); + pending_request = true; + handshake_buffer->clear(); + selected_protocol.clear(); + session_key.clear(); + + // Pending packets info. + was_string = 0; + in_buffer.clear(); + packet_buffer.clear(); + + // Close code info. + close_code = -1; + close_reason.clear(); } WSLPeer::WSLPeer() { + handshake_buffer.instantiate(); } WSLPeer::~WSLPeer() { - close(); - invalidate(); - _wsl_destroy(&_data); - _data = nullptr; + close(-1); } #endif // WEB_ENABLED diff --git a/modules/websocket/wsl_peer.h b/modules/websocket/wsl_peer.h index 92672eb2c4..379002739c 100644 --- a/modules/websocket/wsl_peer.h +++ b/modules/websocket/wsl_peer.h @@ -33,79 +33,123 @@ #ifndef WEB_ENABLED +#include "websocket_peer.h" + +#include "packet_buffer.h" + +#include "core/crypto/crypto_core.h" #include "core/error/error_list.h" #include "core/io/packet_peer.h" #include "core/io/stream_peer_tcp.h" #include "core/templates/ring_buffer.h" -#include "packet_buffer.h" -#include "websocket_peer.h" #include "wslay/wslay.h" #define WSL_MAX_HEADER_SIZE 4096 class WSLPeer : public WebSocketPeer { - GDCIIMPL(WSLPeer, WebSocketPeer); - -public: - struct PeerData { - bool polling = false; - bool destroy = false; - bool valid = false; - bool is_server = false; - bool closing = false; - void *obj = nullptr; - void *peer = nullptr; - Ref<StreamPeer> conn; - Ref<StreamPeerTCP> tcp; - int id = 1; - wslay_event_context_ptr ctx = nullptr; +private: + static CryptoCore::RandomGenerator *_static_rng; + static WebSocketPeer *_create() { return memnew(WSLPeer); } + + // Callbacks. + static ssize_t _wsl_recv_callback(wslay_event_context_ptr ctx, uint8_t *data, size_t len, int flags, void *user_data); + static ssize_t _wsl_send_callback(wslay_event_context_ptr ctx, const uint8_t *data, size_t len, int flags, void *user_data); + static int _wsl_genmask_callback(wslay_event_context_ptr ctx, uint8_t *buf, size_t len, void *user_data); + static void _wsl_msg_recv_callback(wslay_event_context_ptr ctx, const struct wslay_event_on_msg_recv_arg *arg, void *user_data); + + static wslay_event_callbacks _wsl_callbacks; + + // Helpers + static String _compute_key_response(String p_key); + static String _generate_key(); + + // Client IP resolver. + class Resolver { + Array ip_candidates; + IP::ResolverID resolver_id = IP::RESOLVER_INVALID_ID; + int port = 0; + + public: + bool has_more_candidates() { + return ip_candidates.size() > 0 || resolver_id != IP::RESOLVER_INVALID_ID; + } + + void try_next_candidate(Ref<StreamPeerTCP> &p_tcp); + void start(const String &p_host, int p_port); + void stop(); + Resolver() {} }; - static String compute_key_response(String p_key); - static String generate_key(); + Resolver resolver; -private: - static bool _wsl_poll(struct PeerData *p_data); - static void _wsl_destroy(struct PeerData **p_data); + // WebSocket connection state. + WebSocketPeer::State ready_state = WebSocketPeer::STATE_CLOSED; + bool is_server = false; + Ref<StreamPeerTCP> tcp; + Ref<StreamPeer> connection; + wslay_event_context_ptr wsl_ctx = nullptr; + + String requested_url; + String requested_host; + bool pending_request = true; + Ref<StreamPeerBuffer> handshake_buffer; + String selected_protocol; + String session_key; - struct PeerData *_data = nullptr; - uint8_t _is_string = 0; + int close_code = -1; + String close_reason; + uint8_t was_string = 0; + + // WebSocket configuration. + bool use_tls = true; + bool verify_tls = true; + Ref<X509Certificate> tls_cert; + + // Packet buffers. + Vector<uint8_t> packet_buffer; // Our packet info is just a boolean (is_string), using uint8_t for it. - PacketBuffer<uint8_t> _in_buffer; + PacketBuffer<uint8_t> in_buffer; - Vector<uint8_t> _packet_buffer; + Error _send(const uint8_t *p_buffer, int p_buffer_size, wslay_opcode p_opcode); - WriteMode write_mode = WRITE_MODE_BINARY; + Error _do_server_handshake(); + bool _parse_client_request(); - int _out_buf_size = 0; - int _out_pkt_size = 0; + void _do_client_handshake(); + bool _verify_server_response(); + + void _clear(); public: - int close_code = -1; - String close_reason; - void poll(); // Used by client and server. + static void initialize(); + static void deinitialize(); + // PacketPeer virtual int get_available_packet_count() const override; virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) override; virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) override; - virtual int get_max_packet_size() const override { return _packet_buffer.size(); }; - virtual int get_current_outbound_buffered_amount() const override; + virtual int get_max_packet_size() const override { return packet_buffer.size(); }; - virtual void close_now(); + // WebSocketPeer + virtual Error send(const uint8_t *p_buffer, int p_buffer_size, WriteMode p_mode) override; + virtual Error connect_to_url(const String &p_url, bool p_verify_tls = true, Ref<X509Certificate> p_cert = Ref<X509Certificate>()) override; + virtual Error accept_stream(Ref<StreamPeer> p_stream) override; virtual void close(int p_code = 1000, String p_reason = "") override; - virtual bool is_connected_to_host() const override; + virtual void poll() override; + + virtual State get_ready_state() const override { return ready_state; } + virtual int get_close_code() const override { return close_code; } + virtual String get_close_reason() const override { return close_reason; } + virtual int get_current_outbound_buffered_amount() const override; + virtual IPAddress get_connected_host() const override; virtual uint16_t get_connected_port() const override; + virtual String get_selected_protocol() const override; + virtual String get_requested_url() const override; - virtual WriteMode get_write_mode() const override; - virtual void set_write_mode(WriteMode p_mode) override; - virtual bool was_string_packet() const override; + virtual bool was_string_packet() const override { return was_string; } virtual void set_no_delay(bool p_enabled) override; - void make_context(PeerData *p_data, unsigned int p_in_buf_size, unsigned int p_in_pkt_size, unsigned int p_out_buf_size, unsigned int p_out_pkt_size); - Error parse_message(const wslay_event_on_msg_recv_arg *arg); - void invalidate(); - WSLPeer(); ~WSLPeer(); }; diff --git a/modules/websocket/wsl_server.cpp b/modules/websocket/wsl_server.cpp deleted file mode 100644 index 01dcd53839..0000000000 --- a/modules/websocket/wsl_server.cpp +++ /dev/null @@ -1,329 +0,0 @@ -/*************************************************************************/ -/* wsl_server.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 WEB_ENABLED - -#include "wsl_server.h" -#include "core/config/project_settings.h" -#include "core/os/os.h" - -bool WSLServer::PendingPeer::_parse_request(const Vector<String> p_protocols, String &r_resource_name) { - Vector<String> psa = String((char *)req_buf).split("\r\n"); - int len = psa.size(); - ERR_FAIL_COND_V_MSG(len < 4, false, "Not enough response headers, got: " + itos(len) + ", expected >= 4."); - - Vector<String> req = psa[0].split(" ", false); - ERR_FAIL_COND_V_MSG(req.size() < 2, false, "Invalid protocol or status code."); - - // Wrong protocol - ERR_FAIL_COND_V_MSG(req[0] != "GET" || req[2] != "HTTP/1.1", false, "Invalid method or HTTP version."); - - r_resource_name = req[1]; - HashMap<String, String> headers; - for (int i = 1; i < len; i++) { - Vector<String> header = psa[i].split(":", false, 1); - ERR_FAIL_COND_V_MSG(header.size() != 2, false, "Invalid header -> " + psa[i]); - String name = header[0].to_lower(); - String value = header[1].strip_edges(); - if (headers.has(name)) { - headers[name] += "," + value; - } else { - headers[name] = value; - } - } -#define WSL_CHECK(NAME, VALUE) \ - ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false, \ - "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'."); -#define WSL_CHECK_EX(NAME) \ - ERR_FAIL_COND_V_MSG(!headers.has(NAME), false, "Missing header '" + String(NAME) + "'."); - WSL_CHECK("upgrade", "websocket"); - WSL_CHECK("sec-websocket-version", "13"); - WSL_CHECK_EX("sec-websocket-key"); - WSL_CHECK_EX("connection"); -#undef WSL_CHECK_EX -#undef WSL_CHECK - key = headers["sec-websocket-key"]; - if (headers.has("sec-websocket-protocol")) { - Vector<String> protos = headers["sec-websocket-protocol"].split(","); - for (int i = 0; i < protos.size(); i++) { - String proto = protos[i].strip_edges(); - // Check if we have the given protocol - for (int j = 0; j < p_protocols.size(); j++) { - if (proto != p_protocols[j]) { - continue; - } - protocol = proto; - break; - } - // Found a protocol - if (!protocol.is_empty()) { - break; - } - } - if (protocol.is_empty()) { // Invalid protocol(s) requested - return false; - } - } else if (p_protocols.size() > 0) { // No protocol requested, but we need one - return false; - } - return true; -} - -Error WSLServer::PendingPeer::do_handshake(const Vector<String> p_protocols, uint64_t p_timeout, String &r_resource_name, const Vector<String> &p_extra_headers) { - if (OS::get_singleton()->get_ticks_msec() - time > p_timeout) { - print_verbose(vformat("WebSocket handshake timed out after %.3f seconds.", p_timeout * 0.001)); - return ERR_TIMEOUT; - } - - if (use_tls) { - Ref<StreamPeerTLS> tls = static_cast<Ref<StreamPeerTLS>>(connection); - if (tls.is_null()) { - ERR_FAIL_V_MSG(ERR_BUG, "Couldn't get StreamPeerTLS for WebSocket handshake."); - } - tls->poll(); - if (tls->get_status() == StreamPeerTLS::STATUS_HANDSHAKING) { - return ERR_BUSY; - } else if (tls->get_status() != StreamPeerTLS::STATUS_CONNECTED) { - print_verbose(vformat("WebSocket SSL connection error during handshake (StreamPeerTLS status code %d).", tls->get_status())); - return FAILED; - } - } - - if (!has_request) { - int read = 0; - while (true) { - ERR_FAIL_COND_V_MSG(req_pos >= WSL_MAX_HEADER_SIZE, ERR_OUT_OF_MEMORY, "WebSocket response headers are too big."); - Error err = connection->get_partial_data(&req_buf[req_pos], 1, read); - if (err != OK) { // Got an error - print_verbose(vformat("WebSocket error while getting partial data (StreamPeer error code %d).", err)); - return FAILED; - } else if (read != 1) { // Busy, wait next poll - return ERR_BUSY; - } - char *r = (char *)req_buf; - int l = req_pos; - if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') { - r[l - 3] = '\0'; - if (!_parse_request(p_protocols, r_resource_name)) { - return FAILED; - } - String s = "HTTP/1.1 101 Switching Protocols\r\n"; - s += "Upgrade: websocket\r\n"; - s += "Connection: Upgrade\r\n"; - s += "Sec-WebSocket-Accept: " + WSLPeer::compute_key_response(key) + "\r\n"; - if (!protocol.is_empty()) { - s += "Sec-WebSocket-Protocol: " + protocol + "\r\n"; - } - for (int i = 0; i < p_extra_headers.size(); i++) { - s += p_extra_headers[i] + "\r\n"; - } - s += "\r\n"; - response = s.utf8(); - has_request = true; - break; - } - req_pos += 1; - } - } - - if (has_request && response_sent < response.size() - 1) { - int sent = 0; - Error err = connection->put_partial_data((const uint8_t *)response.get_data() + response_sent, response.size() - response_sent - 1, sent); - if (err != OK) { - print_verbose(vformat("WebSocket error while putting partial data (StreamPeer error code %d).", err)); - return err; - } - response_sent += sent; - } - - if (response_sent < response.size() - 1) { - return ERR_BUSY; - } - - return OK; -} - -void WSLServer::set_extra_headers(const Vector<String> &p_headers) { - _extra_headers = p_headers; -} - -Error WSLServer::listen(int p_port, const Vector<String> p_protocols, bool gd_mp_api) { - ERR_FAIL_COND_V(is_listening(), ERR_ALREADY_IN_USE); - - _is_multiplayer = gd_mp_api; - // Strip edges from protocols. - _protocols.resize(p_protocols.size()); - String *pw = _protocols.ptrw(); - for (int i = 0; i < p_protocols.size(); i++) { - pw[i] = p_protocols[i].strip_edges(); - } - return _server->listen(p_port, bind_ip); -} - -void WSLServer::poll() { - List<int> remove_ids; - for (const KeyValue<int, Ref<WebSocketPeer>> &E : _peer_map) { - Ref<WSLPeer> peer = const_cast<WSLPeer *>(static_cast<const WSLPeer *>(E.value.ptr())); - peer->poll(); - if (!peer->is_connected_to_host()) { - _on_disconnect(E.key, peer->close_code != -1); - remove_ids.push_back(E.key); - } - } - for (int &E : remove_ids) { - _peer_map.erase(E); - } - remove_ids.clear(); - - List<Ref<PendingPeer>> remove_peers; - for (const Ref<PendingPeer> &E : _pending) { - String resource_name; - Ref<PendingPeer> ppeer = E; - Error err = ppeer->do_handshake(_protocols, handshake_timeout, resource_name, _extra_headers); - if (err == ERR_BUSY) { - continue; - } else if (err != OK) { - remove_peers.push_back(ppeer); - continue; - } - // Creating new peer - int32_t id = generate_unique_id(); - - WSLPeer::PeerData *data = memnew(struct WSLPeer::PeerData); - data->obj = this; - data->conn = ppeer->connection; - data->tcp = ppeer->tcp; - data->is_server = true; - data->id = id; - - Ref<WSLPeer> ws_peer = memnew(WSLPeer); - ws_peer->make_context(data, _in_buf_size, _in_pkt_size, _out_buf_size, _out_pkt_size); - ws_peer->set_no_delay(true); - - _peer_map[id] = ws_peer; - remove_peers.push_back(ppeer); - _on_connect(id, ppeer->protocol, resource_name); - } - for (const Ref<PendingPeer> &E : remove_peers) { - _pending.erase(E); - } - remove_peers.clear(); - - if (!_server->is_listening()) { - return; - } - - while (_server->is_connection_available()) { - Ref<StreamPeerTCP> conn = _server->take_connection(); - if (is_refusing_new_connections()) { - continue; // Conn will go out-of-scope and be closed. - } - - Ref<PendingPeer> peer = memnew(PendingPeer); - if (private_key.is_valid() && tls_cert.is_valid()) { - Ref<StreamPeerTLS> tls = Ref<StreamPeerTLS>(StreamPeerTLS::create()); - tls->set_blocking_handshake_enabled(false); - tls->accept_stream(conn, private_key, tls_cert, ca_chain); - peer->connection = tls; - peer->use_tls = true; - } else { - peer->connection = conn; - } - peer->tcp = conn; - peer->time = OS::get_singleton()->get_ticks_msec(); - _pending.push_back(peer); - } -} - -bool WSLServer::is_listening() const { - return _server->is_listening(); -} - -int WSLServer::get_max_packet_size() const { - return (1 << _out_buf_size) - PROTO_SIZE; -} - -void WSLServer::stop() { - _server->stop(); - for (const KeyValue<int, Ref<WebSocketPeer>> &E : _peer_map) { - Ref<WSLPeer> peer = const_cast<WSLPeer *>(static_cast<const WSLPeer *>(E.value.ptr())); - peer->close_now(); - } - _pending.clear(); - _peer_map.clear(); - _protocols.clear(); -} - -bool WSLServer::has_peer(int p_id) const { - return _peer_map.has(p_id); -} - -Ref<WebSocketPeer> WSLServer::get_peer(int p_id) const { - ERR_FAIL_COND_V(!has_peer(p_id), nullptr); - return _peer_map[p_id]; -} - -IPAddress WSLServer::get_peer_address(int p_peer_id) const { - ERR_FAIL_COND_V(!has_peer(p_peer_id), IPAddress()); - - return _peer_map[p_peer_id]->get_connected_host(); -} - -int WSLServer::get_peer_port(int p_peer_id) const { - ERR_FAIL_COND_V(!has_peer(p_peer_id), 0); - - return _peer_map[p_peer_id]->get_connected_port(); -} - -void WSLServer::disconnect_peer(int p_peer_id, int p_code, String p_reason) { - ERR_FAIL_COND(!has_peer(p_peer_id)); - - get_peer(p_peer_id)->close(p_code, p_reason); -} - -Error WSLServer::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) { - ERR_FAIL_COND_V_MSG(_server->is_listening(), FAILED, "Buffers sizes can only be set before listening or connecting."); - - _in_buf_size = nearest_shift(p_in_buffer - 1) + 10; - _in_pkt_size = nearest_shift(p_in_packets - 1); - _out_buf_size = nearest_shift(p_out_buffer - 1) + 10; - _out_pkt_size = nearest_shift(p_out_packets - 1); - return OK; -} - -WSLServer::WSLServer() { - _server.instantiate(); -} - -WSLServer::~WSLServer() { - stop(); -} - -#endif // WEB_ENABLED diff --git a/modules/websocket/wsl_server.h b/modules/websocket/wsl_server.h deleted file mode 100644 index df0c1dc68a..0000000000 --- a/modules/websocket/wsl_server.h +++ /dev/null @@ -1,98 +0,0 @@ -/*************************************************************************/ -/* wsl_server.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 WSL_SERVER_H -#define WSL_SERVER_H - -#ifndef WEB_ENABLED - -#include "websocket_server.h" -#include "wsl_peer.h" - -#include "core/io/stream_peer_tcp.h" -#include "core/io/stream_peer_tls.h" -#include "core/io/tcp_server.h" - -class WSLServer : public WebSocketServer { - GDCIIMPL(WSLServer, WebSocketServer); - -private: - class PendingPeer : public RefCounted { - private: - bool _parse_request(const Vector<String> p_protocols, String &r_resource_name); - - public: - Ref<StreamPeerTCP> tcp; - Ref<StreamPeer> connection; - bool use_tls = false; - - uint64_t time = 0; - uint8_t req_buf[WSL_MAX_HEADER_SIZE] = {}; - int req_pos = 0; - String key; - String protocol; - bool has_request = false; - CharString response; - int response_sent = 0; - - Error do_handshake(const Vector<String> p_protocols, uint64_t p_timeout, String &r_resource_name, const Vector<String> &p_extra_headers); - }; - - int _in_buf_size = DEF_BUF_SHIFT; - int _in_pkt_size = DEF_PKT_SHIFT; - int _out_buf_size = DEF_BUF_SHIFT; - int _out_pkt_size = DEF_PKT_SHIFT; - - List<Ref<PendingPeer>> _pending; - Ref<TCPServer> _server; - Vector<String> _protocols; - Vector<String> _extra_headers; - -public: - Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) override; - void set_extra_headers(const Vector<String> &p_headers) override; - Error listen(int p_port, const Vector<String> p_protocols = Vector<String>(), bool gd_mp_api = false) override; - void stop() override; - bool is_listening() const override; - int get_max_packet_size() const override; - bool has_peer(int p_id) const override; - Ref<WebSocketPeer> get_peer(int p_id) const override; - IPAddress get_peer_address(int p_peer_id) const override; - int get_peer_port(int p_peer_id) const override; - void disconnect_peer(int p_peer_id, int p_code = 1000, String p_reason = "") override; - virtual void poll() override; - - WSLServer(); - ~WSLServer(); -}; - -#endif // WEB_ENABLED - -#endif // WSL_SERVER_H diff --git a/modules/webxr/config.py b/modules/webxr/config.py index f676ef3483..8d75e7f531 100644 --- a/modules/webxr/config.py +++ b/modules/webxr/config.py @@ -1,5 +1,5 @@ def can_build(env, platform): - return not env["disable_3d"] + return env["opengl3"] and not env["disable_3d"] def configure(env): diff --git a/modules/webxr/doc_classes/WebXRInterface.xml b/modules/webxr/doc_classes/WebXRInterface.xml index 49ff454f07..49dd9f7318 100644 --- a/modules/webxr/doc_classes/WebXRInterface.xml +++ b/modules/webxr/doc_classes/WebXRInterface.xml @@ -18,16 +18,16 @@ func _ready(): # We assume this node has a button as a child. # This button is for the user to consent to entering immersive VR mode. - $Button.connect("pressed", self, "_on_Button_pressed") + $Button.pressed.connect(self._on_Button_pressed) webxr_interface = XRServer.find_interface("WebXR") if webxr_interface: # WebXR uses a lot of asynchronous callbacks, so we connect to various # signals in order to receive them. - webxr_interface.connect("session_supported", self, "_webxr_session_supported") - webxr_interface.connect("session_started", self, "_webxr_session_started") - webxr_interface.connect("session_ended", self, "_webxr_session_ended") - webxr_interface.connect("session_failed", self, "_webxr_session_failed") + webxr_interface.session_supported.connect(self._webxr_session_supported) + webxr_interface.session_started.connect(self._webxr_session_started) + webxr_interface.session_ended.connect(self._webxr_session_ended) + webxr_interface.session_failed.connect(self._webxr_session_failed) # This returns immediately - our _webxr_session_supported() method # (which we connected to the "session_supported" signal above) will diff --git a/modules/webxr/godot_webxr.h b/modules/webxr/godot_webxr.h index 52104895d4..d8d5bd99cc 100644 --- a/modules/webxr/godot_webxr.h +++ b/modules/webxr/godot_webxr.h @@ -65,8 +65,7 @@ extern int godot_webxr_get_view_count(); extern int *godot_webxr_get_render_target_size(); extern float *godot_webxr_get_transform_for_eye(int p_eye); extern float *godot_webxr_get_projection_for_eye(int p_eye); -extern int godot_webxr_get_external_texture_for_eye(int p_eye); -extern void godot_webxr_commit_for_eye(int p_eye); +extern void godot_webxr_commit(unsigned int p_texture); extern void godot_webxr_sample_controller_data(); extern int godot_webxr_get_controller_count(); diff --git a/modules/webxr/native/library_godot_webxr.js b/modules/webxr/native/library_godot_webxr.js index c4b21defce..c476a54c59 100644 --- a/modules/webxr/native/library_godot_webxr.js +++ b/modules/webxr/native/library_godot_webxr.js @@ -32,9 +32,6 @@ const GodotWebXR = { $GodotWebXR: { gl: null, - texture_ids: [null, null], - textures: [null, null], - session: null, space: null, frame: null, @@ -77,110 +74,6 @@ const GodotWebXR = { }, 0); }, - // Some custom WebGL code for blitting our eye textures to the - // framebuffer we get from WebXR. - shaderProgram: null, - programInfo: null, - buffer: null, - // Vertex shader source. - vsSource: ` - const vec2 scale = vec2(0.5, 0.5); - attribute vec4 aVertexPosition; - - varying highp vec2 vTextureCoord; - - void main () { - gl_Position = aVertexPosition; - vTextureCoord = aVertexPosition.xy * scale + scale; - } - `, - // Fragment shader source. - fsSource: ` - varying highp vec2 vTextureCoord; - - uniform sampler2D uSampler; - - void main() { - gl_FragColor = texture2D(uSampler, vTextureCoord); - } - `, - - initShaderProgram: (gl, vsSource, fsSource) => { - const vertexShader = GodotWebXR.loadShader(gl, gl.VERTEX_SHADER, vsSource); - const fragmentShader = GodotWebXR.loadShader(gl, gl.FRAGMENT_SHADER, fsSource); - - const shaderProgram = gl.createProgram(); - gl.attachShader(shaderProgram, vertexShader); - gl.attachShader(shaderProgram, fragmentShader); - gl.linkProgram(shaderProgram); - - if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { - GodotRuntime.error(`Unable to initialize the shader program: ${gl.getProgramInfoLog(shaderProgram)}`); - return null; - } - - return shaderProgram; - }, - loadShader: (gl, type, source) => { - const shader = gl.createShader(type); - gl.shaderSource(shader, source); - gl.compileShader(shader); - - if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - GodotRuntime.error(`An error occurred compiling the shader: ${gl.getShaderInfoLog(shader)}`); - gl.deleteShader(shader); - return null; - } - - return shader; - }, - initBuffer: (gl) => { - const positionBuffer = gl.createBuffer(); - gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); - const positions = [ - -1.0, -1.0, - 1.0, -1.0, - -1.0, 1.0, - 1.0, 1.0, - ]; - gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW); - return positionBuffer; - }, - blitTexture: (gl, texture) => { - if (GodotWebXR.shaderProgram === null) { - GodotWebXR.shaderProgram = GodotWebXR.initShaderProgram(gl, GodotWebXR.vsSource, GodotWebXR.fsSource); - GodotWebXR.programInfo = { - program: GodotWebXR.shaderProgram, - attribLocations: { - vertexPosition: gl.getAttribLocation(GodotWebXR.shaderProgram, 'aVertexPosition'), - }, - uniformLocations: { - uSampler: gl.getUniformLocation(GodotWebXR.shaderProgram, 'uSampler'), - }, - }; - GodotWebXR.buffer = GodotWebXR.initBuffer(gl); - } - - const orig_program = gl.getParameter(gl.CURRENT_PROGRAM); - gl.useProgram(GodotWebXR.shaderProgram); - - gl.bindBuffer(gl.ARRAY_BUFFER, GodotWebXR.buffer); - gl.vertexAttribPointer(GodotWebXR.programInfo.attribLocations.vertexPosition, 2, gl.FLOAT, false, 0, 0); - gl.enableVertexAttribArray(GodotWebXR.programInfo.attribLocations.vertexPosition); - - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_2D, texture); - gl.uniform1i(GodotWebXR.programInfo.uniformLocations.uSampler, 0); - - gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); - - // Restore state. - gl.bindTexture(gl.TEXTURE_2D, null); - gl.disableVertexAttribArray(GodotWebXR.programInfo.attribLocations.vertexPosition); - gl.bindBuffer(gl.ARRAY_BUFFER, null); - gl.useProgram(orig_program); - }, - // Holds the controllers list between function calls. controllers: [], @@ -370,22 +263,6 @@ const GodotWebXR = { .catch((e) => { }); } - // Clean-up the textures we allocated for each view. - const gl = GodotWebXR.gl; - for (let i = 0; i < GodotWebXR.textures.length; i++) { - const texture = GodotWebXR.textures[i]; - if (texture !== null) { - gl.deleteTexture(texture); - } - GodotWebXR.textures[i] = null; - - const texture_id = GodotWebXR.texture_ids[i]; - if (texture_id !== null) { - GL.textures[texture_id] = null; - } - GodotWebXR.texture_ids[i] = null; - } - GodotWebXR.session = null; GodotWebXR.space = null; GodotWebXR.frame = null; @@ -460,72 +337,53 @@ const GodotWebXR = { return buf; }, - godot_webxr_get_external_texture_for_eye__proxy: 'sync', - godot_webxr_get_external_texture_for_eye__sig: 'ii', - godot_webxr_get_external_texture_for_eye: function (p_eye) { - if (!GodotWebXR.session) { - return 0; - } - - const view_index = (p_eye === 2 /* ARVRInterface::EYE_RIGHT */) ? 1 : 0; - if (GodotWebXR.texture_ids[view_index]) { - return GodotWebXR.texture_ids[view_index]; - } - - // Check pose separately and after returning the cached texture id, - // because we won't get a pose in some cases if we lose tracking, and - // we don't want to return 0 just because tracking was lost. - if (!GodotWebXR.pose) { - return 0; - } - - const glLayer = GodotWebXR.session.renderState.baseLayer; - const view = GodotWebXR.pose.views[view_index]; - const viewport = glLayer.getViewport(view); - const gl = GodotWebXR.gl; - - const texture = gl.createTexture(); - gl.bindTexture(gl.TEXTURE_2D, texture); - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, viewport.width, viewport.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); - gl.bindTexture(gl.TEXTURE_2D, null); - - const texture_id = GL.getNewId(GL.textures); - GL.textures[texture_id] = texture; - GodotWebXR.textures[view_index] = texture; - GodotWebXR.texture_ids[view_index] = texture_id; - return texture_id; - }, - - godot_webxr_commit_for_eye__proxy: 'sync', - godot_webxr_commit_for_eye__sig: 'vi', - godot_webxr_commit_for_eye: function (p_eye) { + godot_webxr_commit__proxy: 'sync', + godot_webxr_commit__sig: 'vi', + godot_webxr_commit: function (p_texture) { if (!GodotWebXR.session || !GodotWebXR.pose) { return; } - const view_index = (p_eye === 2 /* ARVRInterface::EYE_RIGHT */) ? 1 : 0; const glLayer = GodotWebXR.session.renderState.baseLayer; - const view = GodotWebXR.pose.views[view_index]; - const viewport = glLayer.getViewport(view); + const views = GodotWebXR.pose.views; const gl = GodotWebXR.gl; + const texture = GL.textures[p_texture]; + const orig_framebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING); - const orig_viewport = gl.getParameter(gl.VIEWPORT); + const orig_read_framebuffer = gl.getParameter(gl.READ_FRAMEBUFFER_BINDING); + const orig_read_buffer = gl.getParameter(gl.READ_BUFFER); + const orig_draw_framebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING); + + // Copy from Godot render target into framebuffer from WebXR. + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + for (let i = 0; i < views.length; i++) { + const viewport = glLayer.getViewport(views[i]); + + const read_fbo = gl.createFramebuffer(); + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, read_fbo); + if (views.length > 1) { + gl.framebufferTextureLayer(gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, texture, 0, i); + } else { + gl.framebufferTexture2D(gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); + } + gl.readBuffer(gl.COLOR_ATTACHMENT0); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, glLayer.framebuffer); - // Bind to WebXR's framebuffer. - gl.bindFramebuffer(gl.FRAMEBUFFER, glLayer.framebuffer); - gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); + // Flip Y upside down on destination. + gl.blitFramebuffer(0, 0, viewport.width, viewport.height, + viewport.x, viewport.y + viewport.height, viewport.x + viewport.width, viewport.y, + gl.COLOR_BUFFER_BIT, gl.NEAREST); - GodotWebXR.blitTexture(gl, GodotWebXR.textures[view_index]); + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null); + gl.deleteFramebuffer(read_fbo); + } // Restore state. gl.bindFramebuffer(gl.FRAMEBUFFER, orig_framebuffer); - gl.viewport(orig_viewport[0], orig_viewport[1], orig_viewport[2], orig_viewport[3]); + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, orig_read_framebuffer); + gl.readBuffer(orig_read_buffer); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, orig_draw_framebuffer); }, godot_webxr_sample_controller_data__proxy: 'sync', diff --git a/modules/webxr/register_types.cpp b/modules/webxr/register_types.cpp index f4959c482f..8d30f4bd8c 100644 --- a/modules/webxr/register_types.cpp +++ b/modules/webxr/register_types.cpp @@ -57,7 +57,7 @@ void uninitialize_webxr_module(ModuleInitializationLevel p_level) { #ifdef WEB_ENABLED if (webxr.is_valid()) { - // uninitialise our interface if it is initialised + // uninitialize our interface if it is initialized if (webxr->is_initialized()) { webxr->uninitialize(); } diff --git a/modules/webxr/webxr_interface_js.cpp b/modules/webxr/webxr_interface_js.cpp index 7d97dbfa0b..f6ed9f027e 100644 --- a/modules/webxr/webxr_interface_js.cpp +++ b/modules/webxr/webxr_interface_js.cpp @@ -34,9 +34,11 @@ #include "core/input/input.h" #include "core/os/os.h" +#include "drivers/gles3/storage/texture_storage.h" #include "emscripten.h" #include "godot_webxr.h" #include "servers/rendering/renderer_compositor.h" +#include "servers/rendering/rendering_server_globals.h" #include <stdlib.h> @@ -232,6 +234,8 @@ bool WebXRInterfaceJS::initialize() { } // we must create a tracker for our head + head_transform.basis = Basis(); + head_transform.origin = Vector3(); head_tracker.instantiate(); head_tracker->set_tracker_type(XRServer::TRACKER_HEAD); head_tracker->set_tracker_name("head"); @@ -334,15 +338,17 @@ Transform3D WebXRInterfaceJS::get_camera_transform() { XRServer *xr_server = XRServer::get_singleton(); ERR_FAIL_NULL_V(xr_server, transform_for_eye); - float *js_matrix = godot_webxr_get_transform_for_eye(0); - if (!initialized || js_matrix == nullptr) { - return transform_for_eye; - } + if (initialized) { + float world_scale = xr_server->get_world_scale(); - transform_for_eye = _js_matrix_to_transform(js_matrix); - free(js_matrix); + // just scale our origin point of our transform + Transform3D _head_transform = head_transform; + _head_transform.origin *= world_scale; + + transform_for_eye = (xr_server->get_reference_frame()) * _head_transform; + } - return xr_server->get_reference_frame() * transform_for_eye; + return transform_for_eye; }; Transform3D WebXRInterfaceJS::get_transform_for_view(uint32_t p_view, const Transform3D &p_cam_transform) { @@ -360,6 +366,14 @@ Transform3D WebXRInterfaceJS::get_transform_for_view(uint32_t p_view, const Tran transform_for_eye = _js_matrix_to_transform(js_matrix); free(js_matrix); + float world_scale = xr_server->get_world_scale(); + // Scale only the center point of our eye transform, so we don't scale the + // distance between the eyes. + Transform3D _head_transform = head_transform; + transform_for_eye.origin -= _head_transform.origin; + _head_transform.origin *= world_scale; + transform_for_eye.origin += _head_transform.origin; + return p_cam_transform * xr_server->get_reference_frame() * transform_for_eye; }; @@ -374,15 +388,15 @@ Projection WebXRInterfaceJS::get_projection_for_view(uint32_t p_view, double p_a int k = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { - eye.matrix[i][j] = js_matrix[k++]; + eye.columns[i][j] = js_matrix[k++]; } } free(js_matrix); // Copied from godot_oculus_mobile's ovr_mobile_session.cpp - eye.matrix[2][2] = -(p_z_far + p_z_near) / (p_z_far - p_z_near); - eye.matrix[3][2] = -(2.0f * p_z_far * p_z_near) / (p_z_far - p_z_near); + eye.columns[2][2] = -(p_z_far + p_z_near) / (p_z_far - p_z_near); + eye.columns[3][2] = -(2.0f * p_z_far * p_z_near) / (p_z_far - p_z_near); return eye; } @@ -394,29 +408,32 @@ Vector<BlitToScreen> WebXRInterfaceJS::post_draw_viewport(RID p_render_target, c return blit_to_screen; } - // @todo Refactor this to be based on "views" rather than "eyes". - godot_webxr_commit_for_eye(1); - if (godot_webxr_get_view_count() > 1) { - godot_webxr_commit_for_eye(2); + GLES3::TextureStorage *texture_storage = dynamic_cast<GLES3::TextureStorage *>(RSG::texture_storage); + if (!texture_storage) { + return blit_to_screen; } + GLES3::RenderTarget *rt = texture_storage->get_render_target(p_render_target); + + godot_webxr_commit(rt->color); + return blit_to_screen; }; void WebXRInterfaceJS::process() { if (initialized) { - godot_webxr_sample_controller_data(); - + // Get the "head" position. + float *js_matrix = godot_webxr_get_transform_for_eye(0); + if (js_matrix != nullptr) { + head_transform = _js_matrix_to_transform(js_matrix); + free(js_matrix); + } if (head_tracker.is_valid()) { - // TODO set default pose to our head location (i.e. get_camera_transform without world scale and reference frame applied) - // head_tracker->set_pose("default", head_transform, Vector3(), Vector3()); + head_tracker->set_pose("default", head_transform, Vector3(), Vector3()); } + godot_webxr_sample_controller_data(); int controller_count = godot_webxr_get_controller_count(); - if (controller_count == 0) { - return; - } - for (int i = 0; i < controller_count; i++) { _update_tracker(i); } diff --git a/modules/webxr/webxr_interface_js.h b/modules/webxr/webxr_interface_js.h index dbe89dad83..319adc2ac9 100644 --- a/modules/webxr/webxr_interface_js.h +++ b/modules/webxr/webxr_interface_js.h @@ -45,6 +45,7 @@ class WebXRInterfaceJS : public WebXRInterface { private: bool initialized; Ref<XRPositionalTracker> head_tracker; + Transform3D head_transform; String session_mode; String required_features; diff --git a/modules/xatlas_unwrap/config.py b/modules/xatlas_unwrap/config.py index 2e73c51626..ecc61c2d7e 100644 --- a/modules/xatlas_unwrap/config.py +++ b/modules/xatlas_unwrap/config.py @@ -1,5 +1,5 @@ def can_build(env, platform): - return env["tools"] and platform not in ["android", "ios"] + return env.editor_build and platform not in ["android", "ios"] def configure(env): diff --git a/modules/zip/SCsub b/modules/zip/SCsub new file mode 100644 index 0000000000..b7710123fd --- /dev/null +++ b/modules/zip/SCsub @@ -0,0 +1,9 @@ +#!/usr/bin/env python + +Import("env") +Import("env_modules") + +env_zip = env_modules.Clone() + +# Module files +env_zip.add_source_files(env.modules_sources, "*.cpp") diff --git a/modules/zip/config.py b/modules/zip/config.py new file mode 100644 index 0000000000..96cd2fc5bd --- /dev/null +++ b/modules/zip/config.py @@ -0,0 +1,17 @@ +def can_build(env, platform): + return env["minizip"] + + +def configure(env): + pass + + +def get_doc_classes(): + return [ + "ZIPReader", + "ZIPPacker", + ] + + +def get_doc_path(): + return "doc_classes" diff --git a/modules/zip/doc_classes/ZIPPacker.xml b/modules/zip/doc_classes/ZIPPacker.xml new file mode 100644 index 0000000000..95d7ef50f9 --- /dev/null +++ b/modules/zip/doc_classes/ZIPPacker.xml @@ -0,0 +1,72 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="ZIPPacker" inherits="RefCounted" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> + <brief_description> + Allows the creation of zip files. + </brief_description> + <description> + This class implements a writer that allows storing the multiple blobs in a zip archive. + [codeblock] + func write_zip_file(): + var writer := ZIPPacker.new() + var err := writer.open("user://archive.zip") + if err != OK: + return err + writer.start_file("hello.txt") + writer.write_file("Hello World".to_utf8_buffer()) + writer.close_file() + + writer.close() + return OK + [/codeblock] + </description> + <tutorials> + </tutorials> + <methods> + <method name="close"> + <return type="int" enum="Error" /> + <description> + Closes the underlying resources used by this instance. + </description> + </method> + <method name="close_file"> + <return type="int" enum="Error" /> + <description> + Stops writing to a file within the archive. + It will fail if there is no open file. + </description> + </method> + <method name="open"> + <return type="int" enum="Error" /> + <param index="0" name="path" type="String" /> + <param index="1" name="append" type="int" enum="ZIPPacker.ZipAppend" default="0" /> + <description> + Opens a zip file for writing at the given path using the specified write mode. + This must be called before everything else. + </description> + </method> + <method name="start_file"> + <return type="int" enum="Error" /> + <param index="0" name="path" type="String" /> + <description> + Starts writing to a file within the archive. Only one file can be written at the same time. + Must be called after [method open]. + </description> + </method> + <method name="write_file"> + <return type="int" enum="Error" /> + <param index="0" name="data" type="PackedByteArray" /> + <description> + Write the given [param data] to the file. + Needs to be called after [method start_file]. + </description> + </method> + </methods> + <constants> + <constant name="APPEND_CREATE" value="0" enum="ZipAppend"> + </constant> + <constant name="APPEND_CREATEAFTER" value="1" enum="ZipAppend"> + </constant> + <constant name="APPEND_ADDINZIP" value="2" enum="ZipAppend"> + </constant> + </constants> +</class> diff --git a/modules/zip/doc_classes/ZIPReader.xml b/modules/zip/doc_classes/ZIPReader.xml new file mode 100644 index 0000000000..717116a531 --- /dev/null +++ b/modules/zip/doc_classes/ZIPReader.xml @@ -0,0 +1,52 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="ZIPReader" inherits="RefCounted" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> + <brief_description> + Allows reading the content of a zip file. + </brief_description> + <description> + This class implements a reader that can extract the content of individual files inside a zip archive. + [codeblock] + func read_zip_file(): + var reader := ZIPReader.new() + var err := reader.open("user://archive.zip") + if err == OK: + return PackedByteArray() + var res := reader.read_file("hello.txt") + reader.close() + return res + [/codeblock] + </description> + <tutorials> + </tutorials> + <methods> + <method name="close"> + <return type="int" enum="Error" /> + <description> + Closes the underlying resources used by this instance. + </description> + </method> + <method name="get_files"> + <return type="PackedStringArray" /> + <description> + Returns the list of names of all files in the loaded archive. + Must be called after [method open]. + </description> + </method> + <method name="open"> + <return type="int" enum="Error" /> + <param index="0" name="path" type="String" /> + <description> + Opens the zip archive at the given [param path] and reads its file index. + </description> + </method> + <method name="read_file"> + <return type="PackedByteArray" /> + <param index="0" name="path" type="String" /> + <param index="1" name="case_sensitive" type="bool" default="true" /> + <description> + Loads the whole content of a file in the loaded zip archive into memory and returns it. + Must be called after [method open]. + </description> + </method> + </methods> +</class> diff --git a/modules/zip/register_types.cpp b/modules/zip/register_types.cpp new file mode 100644 index 0000000000..20fb484cfe --- /dev/null +++ b/modules/zip/register_types.cpp @@ -0,0 +1,50 @@ +/*************************************************************************/ +/* register_types.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 "core/object/class_db.h" +#include "zip_packer.h" +#include "zip_reader.h" + +void initialize_zip_module(ModuleInitializationLevel p_level) { + if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) { + return; + } + + GDREGISTER_CLASS(ZIPPacker); + GDREGISTER_CLASS(ZIPReader); +} + +void uninitialize_zip_module(ModuleInitializationLevel p_level) { + if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) { + return; + } +} diff --git a/modules/zip/register_types.h b/modules/zip/register_types.h new file mode 100644 index 0000000000..2640be12b8 --- /dev/null +++ b/modules/zip/register_types.h @@ -0,0 +1,39 @@ +/*************************************************************************/ +/* register_types.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 ZIP_REGISTER_TYPES_H +#define ZIP_REGISTER_TYPES_H + +#include "modules/register_module_types.h" + +void initialize_zip_module(ModuleInitializationLevel p_level); +void uninitialize_zip_module(ModuleInitializationLevel p_level); + +#endif // ZIP_REGISTER_TYPES_H diff --git a/modules/zip/zip_packer.cpp b/modules/zip/zip_packer.cpp new file mode 100644 index 0000000000..5566848087 --- /dev/null +++ b/modules/zip/zip_packer.cpp @@ -0,0 +1,107 @@ +/*************************************************************************/ +/* zip_packer.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 "zip_packer.h" + +#include "core/io/zip_io.h" +#include "core/os/os.h" + +Error ZIPPacker::open(String p_path, ZipAppend p_append) { + if (fa.is_valid()) { + close(); + } + + zlib_filefunc_def io = zipio_create_io(&fa); + zf = zipOpen2(p_path.utf8().get_data(), p_append, NULL, &io); + return zf != NULL ? OK : FAILED; +} + +Error ZIPPacker::close() { + ERR_FAIL_COND_V_MSG(fa.is_null(), FAILED, "ZIPPacker cannot be closed because it is not open."); + + Error err = zipClose(zf, NULL) == ZIP_OK ? OK : FAILED; + if (err == OK) { + zf = NULL; + } + return err; +} + +Error ZIPPacker::start_file(String p_path) { + ERR_FAIL_COND_V_MSG(fa.is_null(), FAILED, "ZIPPacker must be opened before use."); + + zip_fileinfo zipfi; + + OS::DateTime time = OS::get_singleton()->get_datetime(); + + zipfi.tmz_date.tm_hour = time.hour; + zipfi.tmz_date.tm_mday = time.day; + zipfi.tmz_date.tm_min = time.minute; + zipfi.tmz_date.tm_mon = time.month - 1; + zipfi.tmz_date.tm_sec = time.second; + zipfi.tmz_date.tm_year = time.year; + zipfi.dosDate = 0; + zipfi.external_fa = 0; + zipfi.internal_fa = 0; + + int ret = zipOpenNewFileInZip(zf, p_path.utf8().get_data(), &zipfi, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_DEFAULT_COMPRESSION); + return ret == ZIP_OK ? OK : FAILED; +} + +Error ZIPPacker::write_file(Vector<uint8_t> p_data) { + ERR_FAIL_COND_V_MSG(fa.is_null(), FAILED, "ZIPPacker must be opened before use."); + + return zipWriteInFileInZip(zf, p_data.ptr(), p_data.size()) == ZIP_OK ? OK : FAILED; +} + +Error ZIPPacker::close_file() { + ERR_FAIL_COND_V_MSG(fa.is_null(), FAILED, "ZIPPacker must be opened before use."); + + return zipCloseFileInZip(zf) == ZIP_OK ? OK : FAILED; +} + +void ZIPPacker::_bind_methods() { + ClassDB::bind_method(D_METHOD("open", "path", "append"), &ZIPPacker::open, DEFVAL(Variant(APPEND_CREATE))); + ClassDB::bind_method(D_METHOD("start_file", "path"), &ZIPPacker::start_file); + ClassDB::bind_method(D_METHOD("write_file", "data"), &ZIPPacker::write_file); + ClassDB::bind_method(D_METHOD("close_file"), &ZIPPacker::close_file); + ClassDB::bind_method(D_METHOD("close"), &ZIPPacker::close); + + BIND_ENUM_CONSTANT(APPEND_CREATE); + BIND_ENUM_CONSTANT(APPEND_CREATEAFTER); + BIND_ENUM_CONSTANT(APPEND_ADDINZIP); +} + +ZIPPacker::ZIPPacker() {} + +ZIPPacker::~ZIPPacker() { + if (fa.is_valid()) { + close(); + } +} diff --git a/modules/zip/zip_packer.h b/modules/zip/zip_packer.h new file mode 100644 index 0000000000..23e96b5ad2 --- /dev/null +++ b/modules/zip/zip_packer.h @@ -0,0 +1,68 @@ +/*************************************************************************/ +/* zip_packer.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 ZIP_PACKER_H +#define ZIP_PACKER_H + +#include "core/io/file_access.h" +#include "core/object/ref_counted.h" + +#include "thirdparty/minizip/zip.h" + +class ZIPPacker : public RefCounted { + GDCLASS(ZIPPacker, RefCounted); + + Ref<FileAccess> fa; + zipFile zf; + +protected: + static void _bind_methods(); + +public: + enum ZipAppend { + APPEND_CREATE = 0, + APPEND_CREATEAFTER = 1, + APPEND_ADDINZIP = 2, + }; + + Error open(String p_path, ZipAppend p_append); + Error close(); + + Error start_file(String p_path); + Error write_file(Vector<uint8_t> p_data); + Error close_file(); + + ZIPPacker(); + ~ZIPPacker(); +}; + +VARIANT_ENUM_CAST(ZIPPacker::ZipAppend) + +#endif // ZIP_PACKER_H diff --git a/modules/zip/zip_reader.cpp b/modules/zip/zip_reader.cpp new file mode 100644 index 0000000000..f35b947cef --- /dev/null +++ b/modules/zip/zip_reader.cpp @@ -0,0 +1,123 @@ +/*************************************************************************/ +/* zip_reader.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 "zip_reader.h" + +#include "core/error/error_macros.h" +#include "core/io/zip_io.h" + +Error ZIPReader::open(String p_path) { + if (fa.is_valid()) { + close(); + } + + zlib_filefunc_def io = zipio_create_io(&fa); + uzf = unzOpen2(p_path.utf8().get_data(), &io); + return uzf != NULL ? OK : FAILED; +} + +Error ZIPReader::close() { + ERR_FAIL_COND_V_MSG(fa.is_null(), FAILED, "ZIPReader cannot be closed because it is not open."); + + return unzClose(uzf) == UNZ_OK ? OK : FAILED; +} + +PackedStringArray ZIPReader::get_files() { + ERR_FAIL_COND_V_MSG(fa.is_null(), PackedStringArray(), "ZIPReader must be opened before use."); + + List<String> s; + + if (unzGoToFirstFile(uzf) != UNZ_OK) { + return PackedStringArray(); + } + + do { + unz_file_info64 file_info; + char filename[256]; // Note filename is a path ! + int err = unzGetCurrentFileInfo64(uzf, &file_info, filename, sizeof(filename), NULL, 0, NULL, 0); + if (err == UNZ_OK) { + s.push_back(filename); + } else { + // Assume filename buffer was too small + char *long_filename_buff = (char *)memalloc(file_info.size_filename); + int err2 = unzGetCurrentFileInfo64(uzf, NULL, long_filename_buff, sizeof(long_filename_buff), NULL, 0, NULL, 0); + if (err2 == UNZ_OK) { + s.push_back(long_filename_buff); + memfree(long_filename_buff); + } + } + } while (unzGoToNextFile(uzf) == UNZ_OK); + + PackedStringArray arr; + arr.resize(s.size()); + int idx = 0; + for (const List<String>::Element *E = s.front(); E; E = E->next()) { + arr.set(idx++, E->get()); + } + return arr; +} + +PackedByteArray ZIPReader::read_file(String p_path, bool p_case_sensitive) { + ERR_FAIL_COND_V_MSG(fa.is_null(), PackedByteArray(), "ZIPReader must be opened before use."); + + int cs = p_case_sensitive ? 1 : 2; + if (unzLocateFile(uzf, p_path.utf8().get_data(), cs) != UNZ_OK) { + ERR_FAIL_V_MSG(PackedByteArray(), "File does not exist in zip archive: " + p_path); + } + if (unzOpenCurrentFile(uzf) != UNZ_OK) { + ERR_FAIL_V_MSG(PackedByteArray(), "Could not open file within zip archive."); + } + + unz_file_info info; + unzGetCurrentFileInfo(uzf, &info, NULL, 0, NULL, 0, NULL, 0); + PackedByteArray data; + data.resize(info.uncompressed_size); + + uint8_t *w = data.ptrw(); + unzReadCurrentFile(uzf, &w[0], info.uncompressed_size); + + unzCloseCurrentFile(uzf); + return data; +} + +ZIPReader::ZIPReader() {} + +ZIPReader::~ZIPReader() { + if (fa.is_valid()) { + close(); + } +} + +void ZIPReader::_bind_methods() { + ClassDB::bind_method(D_METHOD("open", "path"), &ZIPReader::open); + ClassDB::bind_method(D_METHOD("close"), &ZIPReader::close); + ClassDB::bind_method(D_METHOD("get_files"), &ZIPReader::get_files); + ClassDB::bind_method(D_METHOD("read_file", "path", "case_sensitive"), &ZIPReader::read_file, DEFVAL(Variant(true))); +} diff --git a/modules/zip/zip_reader.h b/modules/zip/zip_reader.h new file mode 100644 index 0000000000..fbc2fc0409 --- /dev/null +++ b/modules/zip/zip_reader.h @@ -0,0 +1,59 @@ +/*************************************************************************/ +/* zip_reader.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 ZIP_READER_H +#define ZIP_READER_H + +#include "core/io/file_access.h" +#include "core/object/ref_counted.h" + +#include "thirdparty/minizip/unzip.h" + +class ZIPReader : public RefCounted { + GDCLASS(ZIPReader, RefCounted) + + Ref<FileAccess> fa; + unzFile uzf; + +protected: + static void _bind_methods(); + +public: + Error open(String p_path); + Error close(); + + PackedStringArray get_files(); + PackedByteArray read_file(String p_path, bool p_case_sensitive); + + ZIPReader(); + ~ZIPReader(); +}; + +#endif // ZIP_READER_H |